2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 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 "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 1
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool has_arguments; /**< True, if this attribute has arguments. */
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
101 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
103 /** The current token. */
104 static token_t token;
105 /** The lookahead ring-buffer. */
106 static token_t lookahead_buffer[MAX_LOOKAHEAD];
107 /** Position of the next token in the lookahead buffer. */
108 static size_t lookahead_bufpos;
109 static stack_entry_t *environment_stack = NULL;
110 static stack_entry_t *label_stack = NULL;
111 static scope_t *file_scope = NULL;
112 static scope_t *current_scope = NULL;
113 /** Point to the current function declaration if inside a function. */
114 static function_t *current_function = NULL;
115 static entity_t *current_init_decl = NULL;
116 static switch_statement_t *current_switch = NULL;
117 static statement_t *current_loop = NULL;
118 static statement_t *current_parent = NULL;
119 static ms_try_statement_t *current_try = NULL;
120 static linkage_kind_t current_linkage = LINKAGE_INVALID;
121 static goto_statement_t *goto_first = NULL;
122 static goto_statement_t **goto_anchor = NULL;
123 static label_statement_t *label_first = NULL;
124 static label_statement_t **label_anchor = NULL;
125 /** current translation unit. */
126 static translation_unit_t *unit = NULL;
127 /** true if we are in a type property context (evaluation only for type. */
128 static bool in_type_prop = false;
129 /** true in we are in a __extension__ context. */
130 static bool in_gcc_extension = false;
131 static struct obstack temp_obst;
132 static entity_t *anonymous_entity;
133 static declaration_t **incomplete_arrays;
136 #define PUSH_PARENT(stmt) \
137 statement_t *const prev_parent = current_parent; \
138 ((void)(current_parent = (stmt)))
139 #define POP_PARENT ((void)(current_parent = prev_parent))
141 /** special symbol used for anonymous entities. */
142 static const symbol_t *sym_anonymous = NULL;
144 /* symbols for Microsoft extended-decl-modifier */
145 static const symbol_t *sym_align = NULL;
146 static const symbol_t *sym_allocate = NULL;
147 static const symbol_t *sym_dllimport = NULL;
148 static const symbol_t *sym_dllexport = NULL;
149 static const symbol_t *sym_naked = NULL;
150 static const symbol_t *sym_noinline = NULL;
151 static const symbol_t *sym_returns_twice = NULL;
152 static const symbol_t *sym_noreturn = NULL;
153 static const symbol_t *sym_nothrow = NULL;
154 static const symbol_t *sym_novtable = NULL;
155 static const symbol_t *sym_property = NULL;
156 static const symbol_t *sym_get = NULL;
157 static const symbol_t *sym_put = NULL;
158 static const symbol_t *sym_selectany = NULL;
159 static const symbol_t *sym_thread = NULL;
160 static const symbol_t *sym_uuid = NULL;
161 static const symbol_t *sym_deprecated = NULL;
162 static const symbol_t *sym_restrict = NULL;
163 static const symbol_t *sym_noalias = NULL;
165 /** The token anchor set */
166 static unsigned char token_anchor_set[T_LAST_TOKEN];
168 /** The current source position. */
169 #define HERE (&token.source_position)
171 /** true if we are in GCC mode. */
172 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
174 static type_t *type_valist;
176 static statement_t *parse_compound_statement(bool inside_expression_statement);
177 static statement_t *parse_statement(void);
179 static expression_t *parse_sub_expression(precedence_t);
180 static expression_t *parse_expression(void);
181 static type_t *parse_typename(void);
182 static void parse_externals(void);
183 static void parse_external(void);
185 static void parse_compound_type_entries(compound_t *compound_declaration);
187 typedef enum declarator_flags_t {
189 DECL_MAY_BE_ABSTRACT = 1U << 0,
190 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
191 DECL_IS_PARAMETER = 1U << 2
192 } declarator_flags_t;
194 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
195 declarator_flags_t flags);
197 static entity_t *record_entity(entity_t *entity, bool is_definition);
199 static void semantic_comparison(binary_expression_t *expression);
201 static void create_gnu_builtins(void);
202 static void create_microsoft_intrinsics(void);
204 #define STORAGE_CLASSES \
205 STORAGE_CLASSES_NO_EXTERN \
208 #define STORAGE_CLASSES_NO_EXTERN \
215 #define TYPE_QUALIFIERS \
220 case T__forceinline: \
221 case T___attribute__:
223 #define COMPLEX_SPECIFIERS \
225 #define IMAGINARY_SPECIFIERS \
228 #define TYPE_SPECIFIERS \
230 case T___builtin_va_list: \
250 #define DECLARATION_START \
255 #define DECLARATION_START_NO_EXTERN \
256 STORAGE_CLASSES_NO_EXTERN \
260 #define TYPENAME_START \
264 #define EXPRESSION_START \
273 case T_CHARACTER_CONSTANT: \
274 case T_FLOATINGPOINT: \
278 case T_STRING_LITERAL: \
279 case T_WIDE_CHARACTER_CONSTANT: \
280 case T_WIDE_STRING_LITERAL: \
281 case T___FUNCDNAME__: \
282 case T___FUNCSIG__: \
283 case T___FUNCTION__: \
284 case T___PRETTY_FUNCTION__: \
285 case T___alignof__: \
286 case T___builtin_classify_type: \
287 case T___builtin_constant_p: \
288 case T___builtin_isgreater: \
289 case T___builtin_isgreaterequal: \
290 case T___builtin_isless: \
291 case T___builtin_islessequal: \
292 case T___builtin_islessgreater: \
293 case T___builtin_isunordered: \
294 case T___builtin_offsetof: \
295 case T___builtin_va_arg: \
296 case T___builtin_va_start: \
307 * Allocate an AST node with given size and
308 * initialize all fields with zero.
310 static void *allocate_ast_zero(size_t size)
312 void *res = allocate_ast(size);
313 memset(res, 0, size);
318 * Returns the size of an entity node.
320 * @param kind the entity kind
322 static size_t get_entity_struct_size(entity_kind_t kind)
324 static const size_t sizes[] = {
325 [ENTITY_VARIABLE] = sizeof(variable_t),
326 [ENTITY_PARAMETER] = sizeof(parameter_t),
327 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
328 [ENTITY_FUNCTION] = sizeof(function_t),
329 [ENTITY_TYPEDEF] = sizeof(typedef_t),
330 [ENTITY_STRUCT] = sizeof(compound_t),
331 [ENTITY_UNION] = sizeof(compound_t),
332 [ENTITY_ENUM] = sizeof(enum_t),
333 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
334 [ENTITY_LABEL] = sizeof(label_t),
335 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
336 [ENTITY_NAMESPACE] = sizeof(namespace_t)
338 assert(kind < lengthof(sizes));
339 assert(sizes[kind] != 0);
344 * Allocate an entity of given kind and initialize all
347 static entity_t *allocate_entity_zero(entity_kind_t kind)
349 size_t size = get_entity_struct_size(kind);
350 entity_t *entity = allocate_ast_zero(size);
356 * Returns the size of a statement node.
358 * @param kind the statement kind
360 static size_t get_statement_struct_size(statement_kind_t kind)
362 static const size_t sizes[] = {
363 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
364 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
365 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
366 [STATEMENT_RETURN] = sizeof(return_statement_t),
367 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
368 [STATEMENT_IF] = sizeof(if_statement_t),
369 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
370 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
371 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
372 [STATEMENT_BREAK] = sizeof(statement_base_t),
373 [STATEMENT_GOTO] = sizeof(goto_statement_t),
374 [STATEMENT_LABEL] = sizeof(label_statement_t),
375 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
376 [STATEMENT_WHILE] = sizeof(while_statement_t),
377 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
378 [STATEMENT_FOR] = sizeof(for_statement_t),
379 [STATEMENT_ASM] = sizeof(asm_statement_t),
380 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
381 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
383 assert(kind < lengthof(sizes));
384 assert(sizes[kind] != 0);
389 * Returns the size of an expression node.
391 * @param kind the expression kind
393 static size_t get_expression_struct_size(expression_kind_t kind)
395 static const size_t sizes[] = {
396 [EXPR_INVALID] = sizeof(expression_base_t),
397 [EXPR_REFERENCE] = sizeof(reference_expression_t),
398 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
399 [EXPR_CONST] = sizeof(const_expression_t),
400 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
401 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
402 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
403 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
404 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
405 [EXPR_CALL] = sizeof(call_expression_t),
406 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
407 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
408 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
409 [EXPR_SELECT] = sizeof(select_expression_t),
410 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
411 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
412 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
413 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
414 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
415 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
416 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
417 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
418 [EXPR_VA_START] = sizeof(va_start_expression_t),
419 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
420 [EXPR_STATEMENT] = sizeof(statement_expression_t),
421 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
423 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
424 return sizes[EXPR_UNARY_FIRST];
426 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
427 return sizes[EXPR_BINARY_FIRST];
429 assert(kind < lengthof(sizes));
430 assert(sizes[kind] != 0);
435 * Allocate a statement node of given kind and initialize all
436 * fields with zero. Sets its source position to the position
437 * of the current token.
439 static statement_t *allocate_statement_zero(statement_kind_t kind)
441 size_t size = get_statement_struct_size(kind);
442 statement_t *res = allocate_ast_zero(size);
444 res->base.kind = kind;
445 res->base.parent = current_parent;
446 res->base.source_position = token.source_position;
451 * Allocate an expression node of given kind and initialize all
454 static expression_t *allocate_expression_zero(expression_kind_t kind)
456 size_t size = get_expression_struct_size(kind);
457 expression_t *res = allocate_ast_zero(size);
459 res->base.kind = kind;
460 res->base.type = type_error_type;
461 res->base.source_position = token.source_position;
466 * Creates a new invalid expression at the source position
467 * of the current token.
469 static expression_t *create_invalid_expression(void)
471 return allocate_expression_zero(EXPR_INVALID);
475 * Creates a new invalid statement.
477 static statement_t *create_invalid_statement(void)
479 return allocate_statement_zero(STATEMENT_INVALID);
483 * Allocate a new empty statement.
485 static statement_t *create_empty_statement(void)
487 return allocate_statement_zero(STATEMENT_EMPTY);
491 * Returns the size of a type node.
493 * @param kind the type kind
495 static size_t get_type_struct_size(type_kind_t kind)
497 static const size_t sizes[] = {
498 [TYPE_ATOMIC] = sizeof(atomic_type_t),
499 [TYPE_COMPLEX] = sizeof(complex_type_t),
500 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
501 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
502 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
503 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
504 [TYPE_ENUM] = sizeof(enum_type_t),
505 [TYPE_FUNCTION] = sizeof(function_type_t),
506 [TYPE_POINTER] = sizeof(pointer_type_t),
507 [TYPE_ARRAY] = sizeof(array_type_t),
508 [TYPE_BUILTIN] = sizeof(builtin_type_t),
509 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
510 [TYPE_TYPEOF] = sizeof(typeof_type_t),
512 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
513 assert(kind <= TYPE_TYPEOF);
514 assert(sizes[kind] != 0);
519 * Allocate a type node of given kind and initialize all
522 * @param kind type kind to allocate
524 static type_t *allocate_type_zero(type_kind_t kind)
526 size_t size = get_type_struct_size(kind);
527 type_t *res = obstack_alloc(type_obst, size);
528 memset(res, 0, size);
529 res->base.kind = kind;
535 * Returns the size of an initializer node.
537 * @param kind the initializer kind
539 static size_t get_initializer_size(initializer_kind_t kind)
541 static const size_t sizes[] = {
542 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
543 [INITIALIZER_STRING] = sizeof(initializer_string_t),
544 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
545 [INITIALIZER_LIST] = sizeof(initializer_list_t),
546 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
548 assert(kind < lengthof(sizes));
549 assert(sizes[kind] != 0);
554 * Allocate an initializer node of given kind and initialize all
557 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
559 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
566 * Returns the index of the top element of the environment stack.
568 static size_t environment_top(void)
570 return ARR_LEN(environment_stack);
574 * Returns the index of the top element of the global label stack.
576 static size_t label_top(void)
578 return ARR_LEN(label_stack);
582 * Return the next token.
584 static inline void next_token(void)
586 token = lookahead_buffer[lookahead_bufpos];
587 lookahead_buffer[lookahead_bufpos] = lexer_token;
590 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
593 print_token(stderr, &token);
594 fprintf(stderr, "\n");
599 * Return the next token with a given lookahead.
601 static inline const token_t *look_ahead(size_t num)
603 assert(0 < num && num <= MAX_LOOKAHEAD);
604 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
605 return &lookahead_buffer[pos];
609 * Adds a token type to the token type anchor set (a multi-set).
611 static void add_anchor_token(int token_type)
613 assert(0 <= token_type && token_type < T_LAST_TOKEN);
614 ++token_anchor_set[token_type];
618 * Set the number of tokens types of the given type
619 * to zero and return the old count.
621 static int save_and_reset_anchor_state(int token_type)
623 assert(0 <= token_type && token_type < T_LAST_TOKEN);
624 int count = token_anchor_set[token_type];
625 token_anchor_set[token_type] = 0;
630 * Restore the number of token types to the given count.
632 static void restore_anchor_state(int token_type, int count)
634 assert(0 <= token_type && token_type < T_LAST_TOKEN);
635 token_anchor_set[token_type] = count;
639 * Remove a token type from the token type anchor set (a multi-set).
641 static void rem_anchor_token(int token_type)
643 assert(0 <= token_type && token_type < T_LAST_TOKEN);
644 assert(token_anchor_set[token_type] != 0);
645 --token_anchor_set[token_type];
649 * Return true if the token type of the current token is
652 static bool at_anchor(void)
656 return token_anchor_set[token.type];
660 * Eat tokens until a matching token type is found.
662 static void eat_until_matching_token(int type)
666 case '(': end_token = ')'; break;
667 case '{': end_token = '}'; break;
668 case '[': end_token = ']'; break;
669 default: end_token = type; break;
672 unsigned parenthesis_count = 0;
673 unsigned brace_count = 0;
674 unsigned bracket_count = 0;
675 while (token.type != end_token ||
676 parenthesis_count != 0 ||
678 bracket_count != 0) {
679 switch (token.type) {
681 case '(': ++parenthesis_count; break;
682 case '{': ++brace_count; break;
683 case '[': ++bracket_count; break;
686 if (parenthesis_count > 0)
696 if (bracket_count > 0)
699 if (token.type == end_token &&
700 parenthesis_count == 0 &&
714 * Eat input tokens until an anchor is found.
716 static void eat_until_anchor(void)
718 while (token_anchor_set[token.type] == 0) {
719 if (token.type == '(' || token.type == '{' || token.type == '[')
720 eat_until_matching_token(token.type);
726 * Eat a whole block from input tokens.
728 static void eat_block(void)
730 eat_until_matching_token('{');
731 if (token.type == '}')
735 #define eat(token_type) (assert(token.type == (token_type)), next_token())
738 * Report a parse error because an expected token was not found.
741 #if defined __GNUC__ && __GNUC__ >= 4
742 __attribute__((sentinel))
744 void parse_error_expected(const char *message, ...)
746 if (message != NULL) {
747 errorf(HERE, "%s", message);
750 va_start(ap, message);
751 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
756 * Report an incompatible type.
758 static void type_error_incompatible(const char *msg,
759 const source_position_t *source_position, type_t *type1, type_t *type2)
761 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
766 * Expect the current token is the expected token.
767 * If not, generate an error, eat the current statement,
768 * and goto the end_error label.
770 #define expect(expected, error_label) \
772 if (UNLIKELY(token.type != (expected))) { \
773 parse_error_expected(NULL, (expected), NULL); \
774 add_anchor_token(expected); \
775 eat_until_anchor(); \
776 if (token.type == expected) \
778 rem_anchor_token(expected); \
785 * Push a given scope on the scope stack and make it the
788 static scope_t *scope_push(scope_t *new_scope)
790 if (current_scope != NULL) {
791 new_scope->depth = current_scope->depth + 1;
794 scope_t *old_scope = current_scope;
795 current_scope = new_scope;
800 * Pop the current scope from the scope stack.
802 static void scope_pop(scope_t *old_scope)
804 current_scope = old_scope;
808 * Search an entity by its symbol in a given namespace.
810 static entity_t *get_entity(const symbol_t *const symbol,
811 namespace_tag_t namespc)
813 entity_t *entity = symbol->entity;
814 for (; entity != NULL; entity = entity->base.symbol_next) {
815 if (entity->base.namespc == namespc)
823 * pushs an entity on the environment stack and links the corresponding symbol
826 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
828 symbol_t *symbol = entity->base.symbol;
829 entity_namespace_t namespc = entity->base.namespc;
830 assert(namespc != NAMESPACE_INVALID);
832 /* replace/add entity into entity list of the symbol */
835 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
840 /* replace an entry? */
841 if (iter->base.namespc == namespc) {
842 entity->base.symbol_next = iter->base.symbol_next;
848 /* remember old declaration */
850 entry.symbol = symbol;
851 entry.old_entity = iter;
852 entry.namespc = namespc;
853 ARR_APP1(stack_entry_t, *stack_ptr, entry);
857 * Push an entity on the environment stack.
859 static void environment_push(entity_t *entity)
861 assert(entity->base.source_position.input_name != NULL);
862 assert(entity->base.parent_scope != NULL);
863 stack_push(&environment_stack, entity);
867 * Push a declaration on the global label stack.
869 * @param declaration the declaration
871 static void label_push(entity_t *label)
873 /* we abuse the parameters scope as parent for the labels */
874 label->base.parent_scope = ¤t_function->parameters;
875 stack_push(&label_stack, label);
879 * pops symbols from the environment stack until @p new_top is the top element
881 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
883 stack_entry_t *stack = *stack_ptr;
884 size_t top = ARR_LEN(stack);
887 assert(new_top <= top);
891 for (i = top; i > new_top; --i) {
892 stack_entry_t *entry = &stack[i - 1];
894 entity_t *old_entity = entry->old_entity;
895 symbol_t *symbol = entry->symbol;
896 entity_namespace_t namespc = entry->namespc;
898 /* replace with old_entity/remove */
901 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
903 assert(iter != NULL);
904 /* replace an entry? */
905 if (iter->base.namespc == namespc)
909 /* restore definition from outer scopes (if there was one) */
910 if (old_entity != NULL) {
911 old_entity->base.symbol_next = iter->base.symbol_next;
912 *anchor = old_entity;
914 /* remove entry from list */
915 *anchor = iter->base.symbol_next;
919 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
923 * Pop all entries from the environment stack until the new_top
926 * @param new_top the new stack top
928 static void environment_pop_to(size_t new_top)
930 stack_pop_to(&environment_stack, new_top);
934 * Pop all entries from the global label stack until the new_top
937 * @param new_top the new stack top
939 static void label_pop_to(size_t new_top)
941 stack_pop_to(&label_stack, new_top);
944 static int get_akind_rank(atomic_type_kind_t akind)
950 * Return the type rank for an atomic type.
952 static int get_rank(const type_t *type)
954 assert(!is_typeref(type));
955 if (type->kind == TYPE_ENUM)
956 return get_akind_rank(type->enumt.akind);
958 assert(type->kind == TYPE_ATOMIC);
959 return get_akind_rank(type->atomic.akind);
963 * Do integer promotion for a given type.
965 * @param type the type to promote
966 * @return the promoted type
968 static type_t *promote_integer(type_t *type)
970 if (type->kind == TYPE_BITFIELD)
971 type = type->bitfield.base_type;
973 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
980 * Create a cast expression.
982 * @param expression the expression to cast
983 * @param dest_type the destination type
985 static expression_t *create_cast_expression(expression_t *expression,
988 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
990 cast->unary.value = expression;
991 cast->base.type = dest_type;
997 * Check if a given expression represents a null pointer constant.
999 * @param expression the expression to check
1001 static bool is_null_pointer_constant(const expression_t *expression)
1003 /* skip void* cast */
1004 if (expression->kind == EXPR_UNARY_CAST ||
1005 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1006 type_t *const type = skip_typeref(expression->base.type);
1007 if (types_compatible(type, type_void_ptr))
1008 expression = expression->unary.value;
1011 type_t *const type = skip_typeref(expression->base.type);
1013 is_type_integer(type) &&
1014 is_constant_expression(expression) &&
1015 fold_constant(expression) == 0;
1019 * Create an implicit cast expression.
1021 * @param expression the expression to cast
1022 * @param dest_type the destination type
1024 static expression_t *create_implicit_cast(expression_t *expression,
1027 type_t *const source_type = expression->base.type;
1029 if (source_type == dest_type)
1032 return create_cast_expression(expression, dest_type);
1035 typedef enum assign_error_t {
1037 ASSIGN_ERROR_INCOMPATIBLE,
1038 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1039 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1040 ASSIGN_WARNING_POINTER_FROM_INT,
1041 ASSIGN_WARNING_INT_FROM_POINTER
1044 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1045 const expression_t *const right,
1046 const char *context,
1047 const source_position_t *source_position)
1049 type_t *const orig_type_right = right->base.type;
1050 type_t *const type_left = skip_typeref(orig_type_left);
1051 type_t *const type_right = skip_typeref(orig_type_right);
1054 case ASSIGN_SUCCESS:
1056 case ASSIGN_ERROR_INCOMPATIBLE:
1057 errorf(source_position,
1058 "destination type '%T' in %s is incompatible with type '%T'",
1059 orig_type_left, context, orig_type_right);
1062 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1063 if (warning.other) {
1064 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1065 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1067 /* the left type has all qualifiers from the right type */
1068 unsigned missing_qualifiers
1069 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1070 warningf(source_position,
1071 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1072 orig_type_left, context, orig_type_right, missing_qualifiers);
1077 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1078 if (warning.other) {
1079 warningf(source_position,
1080 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1081 orig_type_left, context, right, orig_type_right);
1085 case ASSIGN_WARNING_POINTER_FROM_INT:
1086 if (warning.other) {
1087 warningf(source_position,
1088 "%s makes pointer '%T' from integer '%T' without a cast",
1089 context, orig_type_left, orig_type_right);
1093 case ASSIGN_WARNING_INT_FROM_POINTER:
1094 if (warning.other) {
1095 warningf(source_position,
1096 "%s makes integer '%T' from pointer '%T' without a cast",
1097 context, orig_type_left, orig_type_right);
1102 panic("invalid error value");
1106 /** Implements the rules from §6.5.16.1 */
1107 static assign_error_t semantic_assign(type_t *orig_type_left,
1108 const expression_t *const right)
1110 type_t *const orig_type_right = right->base.type;
1111 type_t *const type_left = skip_typeref(orig_type_left);
1112 type_t *const type_right = skip_typeref(orig_type_right);
1114 if (is_type_pointer(type_left)) {
1115 if (is_null_pointer_constant(right)) {
1116 return ASSIGN_SUCCESS;
1117 } else if (is_type_pointer(type_right)) {
1118 type_t *points_to_left
1119 = skip_typeref(type_left->pointer.points_to);
1120 type_t *points_to_right
1121 = skip_typeref(type_right->pointer.points_to);
1122 assign_error_t res = ASSIGN_SUCCESS;
1124 /* the left type has all qualifiers from the right type */
1125 unsigned missing_qualifiers
1126 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1127 if (missing_qualifiers != 0) {
1128 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1131 points_to_left = get_unqualified_type(points_to_left);
1132 points_to_right = get_unqualified_type(points_to_right);
1134 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1137 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1138 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1139 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1142 if (!types_compatible(points_to_left, points_to_right)) {
1143 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1147 } else if (is_type_integer(type_right)) {
1148 return ASSIGN_WARNING_POINTER_FROM_INT;
1150 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1151 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1152 && is_type_pointer(type_right))) {
1153 return ASSIGN_SUCCESS;
1154 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1155 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1156 type_t *const unqual_type_left = get_unqualified_type(type_left);
1157 type_t *const unqual_type_right = get_unqualified_type(type_right);
1158 if (types_compatible(unqual_type_left, unqual_type_right)) {
1159 return ASSIGN_SUCCESS;
1161 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1162 return ASSIGN_WARNING_INT_FROM_POINTER;
1165 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1166 return ASSIGN_SUCCESS;
1168 return ASSIGN_ERROR_INCOMPATIBLE;
1171 static expression_t *parse_constant_expression(void)
1173 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1175 if (!is_constant_expression(result)) {
1176 errorf(&result->base.source_position,
1177 "expression '%E' is not constant", result);
1183 static expression_t *parse_assignment_expression(void)
1185 return parse_sub_expression(PREC_ASSIGNMENT);
1188 static string_t parse_string_literals(void)
1190 assert(token.type == T_STRING_LITERAL);
1191 string_t result = token.v.string;
1195 while (token.type == T_STRING_LITERAL) {
1196 result = concat_strings(&result, &token.v.string);
1203 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1204 [GNU_AK_CONST] = "const",
1205 [GNU_AK_VOLATILE] = "volatile",
1206 [GNU_AK_CDECL] = "cdecl",
1207 [GNU_AK_STDCALL] = "stdcall",
1208 [GNU_AK_FASTCALL] = "fastcall",
1209 [GNU_AK_DEPRECATED] = "deprecated",
1210 [GNU_AK_NOINLINE] = "noinline",
1211 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1212 [GNU_AK_NORETURN] = "noreturn",
1213 [GNU_AK_NAKED] = "naked",
1214 [GNU_AK_PURE] = "pure",
1215 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1216 [GNU_AK_MALLOC] = "malloc",
1217 [GNU_AK_WEAK] = "weak",
1218 [GNU_AK_CONSTRUCTOR] = "constructor",
1219 [GNU_AK_DESTRUCTOR] = "destructor",
1220 [GNU_AK_NOTHROW] = "nothrow",
1221 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1222 [GNU_AK_COMMON] = "common",
1223 [GNU_AK_NOCOMMON] = "nocommon",
1224 [GNU_AK_PACKED] = "packed",
1225 [GNU_AK_SHARED] = "shared",
1226 [GNU_AK_NOTSHARED] = "notshared",
1227 [GNU_AK_USED] = "used",
1228 [GNU_AK_UNUSED] = "unused",
1229 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1230 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1231 [GNU_AK_LONGCALL] = "longcall",
1232 [GNU_AK_SHORTCALL] = "shortcall",
1233 [GNU_AK_LONG_CALL] = "long_call",
1234 [GNU_AK_SHORT_CALL] = "short_call",
1235 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1236 [GNU_AK_INTERRUPT] = "interrupt",
1237 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1238 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1239 [GNU_AK_NESTING] = "nesting",
1240 [GNU_AK_NEAR] = "near",
1241 [GNU_AK_FAR] = "far",
1242 [GNU_AK_SIGNAL] = "signal",
1243 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1244 [GNU_AK_TINY_DATA] = "tiny_data",
1245 [GNU_AK_SAVEALL] = "saveall",
1246 [GNU_AK_FLATTEN] = "flatten",
1247 [GNU_AK_SSEREGPARM] = "sseregparm",
1248 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1249 [GNU_AK_RETURN_TWICE] = "return_twice",
1250 [GNU_AK_MAY_ALIAS] = "may_alias",
1251 [GNU_AK_MS_STRUCT] = "ms_struct",
1252 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1253 [GNU_AK_DLLIMPORT] = "dllimport",
1254 [GNU_AK_DLLEXPORT] = "dllexport",
1255 [GNU_AK_ALIGNED] = "aligned",
1256 [GNU_AK_ALIAS] = "alias",
1257 [GNU_AK_SECTION] = "section",
1258 [GNU_AK_FORMAT] = "format",
1259 [GNU_AK_FORMAT_ARG] = "format_arg",
1260 [GNU_AK_WEAKREF] = "weakref",
1261 [GNU_AK_NONNULL] = "nonnull",
1262 [GNU_AK_TLS_MODEL] = "tls_model",
1263 [GNU_AK_VISIBILITY] = "visibility",
1264 [GNU_AK_REGPARM] = "regparm",
1265 [GNU_AK_MODE] = "mode",
1266 [GNU_AK_MODEL] = "model",
1267 [GNU_AK_TRAP_EXIT] = "trap_exit",
1268 [GNU_AK_SP_SWITCH] = "sp_switch",
1269 [GNU_AK_SENTINEL] = "sentinel"
1273 * compare two string, ignoring double underscores on the second.
1275 static int strcmp_underscore(const char *s1, const char *s2)
1277 if (s2[0] == '_' && s2[1] == '_') {
1278 size_t len2 = strlen(s2);
1279 size_t len1 = strlen(s1);
1280 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1281 return strncmp(s1, s2+2, len2-4);
1285 return strcmp(s1, s2);
1289 * Allocate a new gnu temporal attribute of given kind.
1291 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1293 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1294 attribute->kind = kind;
1295 attribute->next = NULL;
1296 attribute->invalid = false;
1297 attribute->has_arguments = false;
1303 * Parse one constant expression argument of the given attribute.
1305 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1307 expression_t *expression;
1308 add_anchor_token(')');
1309 expression = parse_constant_expression();
1310 rem_anchor_token(')');
1311 expect(')', end_error);
1312 attribute->u.argument = fold_constant(expression);
1315 attribute->invalid = true;
1319 * Parse a list of constant expressions arguments of the given attribute.
1321 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1323 argument_list_t **list = &attribute->u.arguments;
1324 argument_list_t *entry;
1325 expression_t *expression;
1326 add_anchor_token(')');
1327 add_anchor_token(',');
1329 expression = parse_constant_expression();
1330 entry = obstack_alloc(&temp_obst, sizeof(entry));
1331 entry->argument = fold_constant(expression);
1334 list = &entry->next;
1335 if (token.type != ',')
1339 rem_anchor_token(',');
1340 rem_anchor_token(')');
1341 expect(')', end_error);
1344 attribute->invalid = true;
1348 * Parse one string literal argument of the given attribute.
1350 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1353 add_anchor_token('(');
1354 if (token.type != T_STRING_LITERAL) {
1355 parse_error_expected("while parsing attribute directive",
1356 T_STRING_LITERAL, NULL);
1359 *string = parse_string_literals();
1360 rem_anchor_token('(');
1361 expect(')', end_error);
1364 attribute->invalid = true;
1368 * Parse one tls model of the given attribute.
1370 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1372 static const char *const tls_models[] = {
1378 string_t string = { NULL, 0 };
1379 parse_gnu_attribute_string_arg(attribute, &string);
1380 if (string.begin != NULL) {
1381 for (size_t i = 0; i < 4; ++i) {
1382 if (strcmp(tls_models[i], string.begin) == 0) {
1383 attribute->u.value = i;
1387 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1389 attribute->invalid = true;
1393 * Parse one tls model of the given attribute.
1395 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1397 static const char *const visibilities[] = {
1403 string_t string = { NULL, 0 };
1404 parse_gnu_attribute_string_arg(attribute, &string);
1405 if (string.begin != NULL) {
1406 for (size_t i = 0; i < 4; ++i) {
1407 if (strcmp(visibilities[i], string.begin) == 0) {
1408 attribute->u.value = i;
1412 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1414 attribute->invalid = true;
1418 * Parse one (code) model of the given attribute.
1420 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1422 static const char *const visibilities[] = {
1427 string_t string = { NULL, 0 };
1428 parse_gnu_attribute_string_arg(attribute, &string);
1429 if (string.begin != NULL) {
1430 for (int i = 0; i < 3; ++i) {
1431 if (strcmp(visibilities[i], string.begin) == 0) {
1432 attribute->u.value = i;
1436 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1438 attribute->invalid = true;
1442 * Parse one mode of the given attribute.
1444 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1446 add_anchor_token(')');
1448 if (token.type != T_IDENTIFIER) {
1449 expect(T_IDENTIFIER, end_error);
1452 attribute->u.symbol = token.v.symbol;
1455 rem_anchor_token(')');
1456 expect(')', end_error);
1459 attribute->invalid = true;
1463 * Parse one interrupt argument of the given attribute.
1465 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1467 static const char *const interrupts[] = {
1474 string_t string = { NULL, 0 };
1475 parse_gnu_attribute_string_arg(attribute, &string);
1476 if (string.begin != NULL) {
1477 for (size_t i = 0; i < 5; ++i) {
1478 if (strcmp(interrupts[i], string.begin) == 0) {
1479 attribute->u.value = i;
1483 errorf(HERE, "'%s' is not an interrupt", string.begin);
1485 attribute->invalid = true;
1489 * Parse ( identifier, const expression, const expression )
1491 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1493 static const char *const format_names[] = {
1501 if (token.type != T_IDENTIFIER) {
1502 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1505 const char *name = token.v.symbol->string;
1506 for (i = 0; i < 4; ++i) {
1507 if (strcmp_underscore(format_names[i], name) == 0)
1511 if (warning.attribute)
1512 warningf(HERE, "'%s' is an unrecognized format function type", name);
1516 expect(',', end_error);
1517 add_anchor_token(')');
1518 add_anchor_token(',');
1519 parse_constant_expression();
1520 rem_anchor_token(',');
1521 rem_anchor_token(')');
1523 expect(',', end_error);
1524 add_anchor_token(')');
1525 parse_constant_expression();
1526 rem_anchor_token(')');
1527 expect(')', end_error);
1530 attribute->u.value = true;
1534 * Check that a given GNU attribute has no arguments.
1536 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1538 if (!attribute->has_arguments)
1541 /* should have no arguments */
1542 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1543 eat_until_matching_token('(');
1544 /* we have already consumed '(', so we stop before ')', eat it */
1546 attribute->invalid = true;
1550 * Parse one GNU attribute.
1552 * Note that attribute names can be specified WITH or WITHOUT
1553 * double underscores, ie const or __const__.
1555 * The following attributes are parsed without arguments
1580 * no_instrument_function
1581 * warn_unused_result
1598 * externally_visible
1606 * The following attributes are parsed with arguments
1607 * aligned( const expression )
1608 * alias( string literal )
1609 * section( string literal )
1610 * format( identifier, const expression, const expression )
1611 * format_arg( const expression )
1612 * tls_model( string literal )
1613 * visibility( string literal )
1614 * regparm( const expression )
1615 * model( string leteral )
1616 * trap_exit( const expression )
1617 * sp_switch( string literal )
1619 * The following attributes might have arguments
1620 * weak_ref( string literal )
1621 * non_null( const expression // ',' )
1622 * interrupt( string literal )
1623 * sentinel( constant expression )
1625 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1627 gnu_attribute_t *head = *attributes;
1628 gnu_attribute_t *last = *attributes;
1629 decl_modifiers_t modifiers = 0;
1630 gnu_attribute_t *attribute;
1632 eat(T___attribute__);
1633 expect('(', end_error);
1634 expect('(', end_error);
1636 if (token.type != ')') {
1637 /* find the end of the list */
1639 while (last->next != NULL)
1643 /* non-empty attribute list */
1646 if (token.type == T_const) {
1648 } else if (token.type == T_volatile) {
1650 } else if (token.type == T_cdecl) {
1651 /* __attribute__((cdecl)), WITH ms mode */
1653 } else if (token.type == T_IDENTIFIER) {
1654 const symbol_t *sym = token.v.symbol;
1657 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1664 for (i = 0; i < GNU_AK_LAST; ++i) {
1665 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1668 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1671 if (kind == GNU_AK_LAST) {
1672 if (warning.attribute)
1673 warningf(HERE, "'%s' attribute directive ignored", name);
1675 /* skip possible arguments */
1676 if (token.type == '(') {
1677 eat_until_matching_token(')');
1680 /* check for arguments */
1681 attribute = allocate_gnu_attribute(kind);
1682 if (token.type == '(') {
1684 if (token.type == ')') {
1685 /* empty args are allowed */
1688 attribute->has_arguments = true;
1692 case GNU_AK_VOLATILE:
1697 case GNU_AK_NOCOMMON:
1699 case GNU_AK_NOTSHARED:
1700 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1701 case GNU_AK_WARN_UNUSED_RESULT:
1702 case GNU_AK_LONGCALL:
1703 case GNU_AK_SHORTCALL:
1704 case GNU_AK_LONG_CALL:
1705 case GNU_AK_SHORT_CALL:
1706 case GNU_AK_FUNCTION_VECTOR:
1707 case GNU_AK_INTERRUPT_HANDLER:
1708 case GNU_AK_NMI_HANDLER:
1709 case GNU_AK_NESTING:
1713 case GNU_AK_EIGTHBIT_DATA:
1714 case GNU_AK_TINY_DATA:
1715 case GNU_AK_SAVEALL:
1716 case GNU_AK_FLATTEN:
1717 case GNU_AK_SSEREGPARM:
1718 case GNU_AK_EXTERNALLY_VISIBLE:
1719 case GNU_AK_RETURN_TWICE:
1720 case GNU_AK_MAY_ALIAS:
1721 case GNU_AK_MS_STRUCT:
1722 case GNU_AK_GCC_STRUCT:
1725 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1726 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1727 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1728 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1729 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1730 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1731 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1732 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1733 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1734 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1735 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1736 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1737 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1738 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1739 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1740 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1741 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1742 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1743 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1745 case GNU_AK_ALIGNED:
1746 /* __align__ may be used without an argument */
1747 if (attribute->has_arguments) {
1748 parse_gnu_attribute_const_arg(attribute);
1752 case GNU_AK_FORMAT_ARG:
1753 case GNU_AK_REGPARM:
1754 case GNU_AK_TRAP_EXIT:
1755 if (!attribute->has_arguments) {
1756 /* should have arguments */
1757 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1758 attribute->invalid = true;
1760 parse_gnu_attribute_const_arg(attribute);
1763 case GNU_AK_SECTION:
1764 case GNU_AK_SP_SWITCH:
1765 if (!attribute->has_arguments) {
1766 /* should have arguments */
1767 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1768 attribute->invalid = true;
1770 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1773 if (!attribute->has_arguments) {
1774 /* should have arguments */
1775 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1776 attribute->invalid = true;
1778 parse_gnu_attribute_format_args(attribute);
1780 case GNU_AK_WEAKREF:
1781 /* may have one string argument */
1782 if (attribute->has_arguments)
1783 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1785 case GNU_AK_NONNULL:
1786 if (attribute->has_arguments)
1787 parse_gnu_attribute_const_arg_list(attribute);
1789 case GNU_AK_TLS_MODEL:
1790 if (!attribute->has_arguments) {
1791 /* should have arguments */
1792 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1794 parse_gnu_attribute_tls_model_arg(attribute);
1796 case GNU_AK_VISIBILITY:
1797 if (!attribute->has_arguments) {
1798 /* should have arguments */
1799 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1801 parse_gnu_attribute_visibility_arg(attribute);
1804 if (!attribute->has_arguments) {
1805 /* should have arguments */
1806 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1808 parse_gnu_attribute_model_arg(attribute);
1812 if (!attribute->has_arguments) {
1813 /* should have arguments */
1814 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1816 parse_gnu_attribute_mode_arg(attribute);
1819 case GNU_AK_INTERRUPT:
1820 /* may have one string argument */
1821 if (attribute->has_arguments)
1822 parse_gnu_attribute_interrupt_arg(attribute);
1824 case GNU_AK_SENTINEL:
1825 /* may have one string argument */
1826 if (attribute->has_arguments)
1827 parse_gnu_attribute_const_arg(attribute);
1830 /* already handled */
1834 check_no_argument(attribute, name);
1837 if (attribute != NULL) {
1839 last->next = attribute;
1842 head = last = attribute;
1846 if (token.type != ',')
1851 expect(')', end_error);
1852 expect(')', end_error);
1860 * Parse GNU attributes.
1862 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1864 decl_modifiers_t modifiers = 0;
1867 switch (token.type) {
1868 case T___attribute__:
1869 modifiers |= parse_gnu_attribute(attributes);
1874 expect('(', end_error);
1875 if (token.type != T_STRING_LITERAL) {
1876 parse_error_expected("while parsing assembler attribute",
1877 T_STRING_LITERAL, NULL);
1878 eat_until_matching_token('(');
1881 parse_string_literals();
1883 expect(')', end_error);
1886 case T_cdecl: modifiers |= DM_CDECL; break;
1887 case T__fastcall: modifiers |= DM_FASTCALL; break;
1888 case T__stdcall: modifiers |= DM_STDCALL; break;
1891 /* TODO record modifier */
1893 warningf(HERE, "Ignoring declaration modifier %K", &token);
1897 default: return modifiers;
1904 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1906 static entity_t *determine_lhs_ent(expression_t *const expr,
1909 switch (expr->kind) {
1910 case EXPR_REFERENCE: {
1911 entity_t *const entity = expr->reference.entity;
1912 /* we should only find variables as lvalues... */
1913 if (entity->base.kind != ENTITY_VARIABLE
1914 && entity->base.kind != ENTITY_PARAMETER)
1920 case EXPR_ARRAY_ACCESS: {
1921 expression_t *const ref = expr->array_access.array_ref;
1922 entity_t * ent = NULL;
1923 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1924 ent = determine_lhs_ent(ref, lhs_ent);
1927 mark_vars_read(expr->select.compound, lhs_ent);
1929 mark_vars_read(expr->array_access.index, lhs_ent);
1934 if (is_type_compound(skip_typeref(expr->base.type))) {
1935 return determine_lhs_ent(expr->select.compound, lhs_ent);
1937 mark_vars_read(expr->select.compound, lhs_ent);
1942 case EXPR_UNARY_DEREFERENCE: {
1943 expression_t *const val = expr->unary.value;
1944 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1946 return determine_lhs_ent(val->unary.value, lhs_ent);
1948 mark_vars_read(val, NULL);
1954 mark_vars_read(expr, NULL);
1959 #define ENT_ANY ((entity_t*)-1)
1962 * Mark declarations, which are read. This is used to detect variables, which
1966 * x is not marked as "read", because it is only read to calculate its own new
1970 * x and y are not detected as "not read", because multiple variables are
1973 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1975 switch (expr->kind) {
1976 case EXPR_REFERENCE: {
1977 entity_t *const entity = expr->reference.entity;
1978 if (entity->kind != ENTITY_VARIABLE
1979 && entity->kind != ENTITY_PARAMETER)
1982 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1983 if (entity->kind == ENTITY_VARIABLE) {
1984 entity->variable.read = true;
1986 entity->parameter.read = true;
1993 // TODO respect pure/const
1994 mark_vars_read(expr->call.function, NULL);
1995 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1996 mark_vars_read(arg->expression, NULL);
2000 case EXPR_CONDITIONAL:
2001 // TODO lhs_decl should depend on whether true/false have an effect
2002 mark_vars_read(expr->conditional.condition, NULL);
2003 if (expr->conditional.true_expression != NULL)
2004 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2005 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2009 if (lhs_ent == ENT_ANY
2010 && !is_type_compound(skip_typeref(expr->base.type)))
2012 mark_vars_read(expr->select.compound, lhs_ent);
2015 case EXPR_ARRAY_ACCESS: {
2016 expression_t *const ref = expr->array_access.array_ref;
2017 mark_vars_read(ref, lhs_ent);
2018 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2019 mark_vars_read(expr->array_access.index, lhs_ent);
2024 mark_vars_read(expr->va_arge.ap, lhs_ent);
2027 case EXPR_UNARY_CAST:
2028 /* Special case: Use void cast to mark a variable as "read" */
2029 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2034 case EXPR_UNARY_THROW:
2035 if (expr->unary.value == NULL)
2038 case EXPR_UNARY_DEREFERENCE:
2039 case EXPR_UNARY_DELETE:
2040 case EXPR_UNARY_DELETE_ARRAY:
2041 if (lhs_ent == ENT_ANY)
2045 case EXPR_UNARY_NEGATE:
2046 case EXPR_UNARY_PLUS:
2047 case EXPR_UNARY_BITWISE_NEGATE:
2048 case EXPR_UNARY_NOT:
2049 case EXPR_UNARY_TAKE_ADDRESS:
2050 case EXPR_UNARY_POSTFIX_INCREMENT:
2051 case EXPR_UNARY_POSTFIX_DECREMENT:
2052 case EXPR_UNARY_PREFIX_INCREMENT:
2053 case EXPR_UNARY_PREFIX_DECREMENT:
2054 case EXPR_UNARY_CAST_IMPLICIT:
2055 case EXPR_UNARY_ASSUME:
2057 mark_vars_read(expr->unary.value, lhs_ent);
2060 case EXPR_BINARY_ADD:
2061 case EXPR_BINARY_SUB:
2062 case EXPR_BINARY_MUL:
2063 case EXPR_BINARY_DIV:
2064 case EXPR_BINARY_MOD:
2065 case EXPR_BINARY_EQUAL:
2066 case EXPR_BINARY_NOTEQUAL:
2067 case EXPR_BINARY_LESS:
2068 case EXPR_BINARY_LESSEQUAL:
2069 case EXPR_BINARY_GREATER:
2070 case EXPR_BINARY_GREATEREQUAL:
2071 case EXPR_BINARY_BITWISE_AND:
2072 case EXPR_BINARY_BITWISE_OR:
2073 case EXPR_BINARY_BITWISE_XOR:
2074 case EXPR_BINARY_LOGICAL_AND:
2075 case EXPR_BINARY_LOGICAL_OR:
2076 case EXPR_BINARY_SHIFTLEFT:
2077 case EXPR_BINARY_SHIFTRIGHT:
2078 case EXPR_BINARY_COMMA:
2079 case EXPR_BINARY_ISGREATER:
2080 case EXPR_BINARY_ISGREATEREQUAL:
2081 case EXPR_BINARY_ISLESS:
2082 case EXPR_BINARY_ISLESSEQUAL:
2083 case EXPR_BINARY_ISLESSGREATER:
2084 case EXPR_BINARY_ISUNORDERED:
2085 mark_vars_read(expr->binary.left, lhs_ent);
2086 mark_vars_read(expr->binary.right, lhs_ent);
2089 case EXPR_BINARY_ASSIGN:
2090 case EXPR_BINARY_MUL_ASSIGN:
2091 case EXPR_BINARY_DIV_ASSIGN:
2092 case EXPR_BINARY_MOD_ASSIGN:
2093 case EXPR_BINARY_ADD_ASSIGN:
2094 case EXPR_BINARY_SUB_ASSIGN:
2095 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2096 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2097 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2098 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2099 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2100 if (lhs_ent == ENT_ANY)
2102 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2103 mark_vars_read(expr->binary.right, lhs_ent);
2108 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2114 case EXPR_CHARACTER_CONSTANT:
2115 case EXPR_WIDE_CHARACTER_CONSTANT:
2116 case EXPR_STRING_LITERAL:
2117 case EXPR_WIDE_STRING_LITERAL:
2118 case EXPR_COMPOUND_LITERAL: // TODO init?
2120 case EXPR_CLASSIFY_TYPE:
2123 case EXPR_BUILTIN_CONSTANT_P:
2124 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
2126 case EXPR_STATEMENT: // TODO
2127 case EXPR_LABEL_ADDRESS:
2128 case EXPR_REFERENCE_ENUM_VALUE:
2132 panic("unhandled expression");
2135 static designator_t *parse_designation(void)
2137 designator_t *result = NULL;
2138 designator_t *last = NULL;
2141 designator_t *designator;
2142 switch (token.type) {
2144 designator = allocate_ast_zero(sizeof(designator[0]));
2145 designator->source_position = token.source_position;
2147 add_anchor_token(']');
2148 designator->array_index = parse_constant_expression();
2149 rem_anchor_token(']');
2150 expect(']', end_error);
2153 designator = allocate_ast_zero(sizeof(designator[0]));
2154 designator->source_position = token.source_position;
2156 if (token.type != T_IDENTIFIER) {
2157 parse_error_expected("while parsing designator",
2158 T_IDENTIFIER, NULL);
2161 designator->symbol = token.v.symbol;
2165 expect('=', end_error);
2169 assert(designator != NULL);
2171 last->next = designator;
2173 result = designator;
2181 static initializer_t *initializer_from_string(array_type_t *type,
2182 const string_t *const string)
2184 /* TODO: check len vs. size of array type */
2187 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2188 initializer->string.string = *string;
2193 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2194 wide_string_t *const string)
2196 /* TODO: check len vs. size of array type */
2199 initializer_t *const initializer =
2200 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2201 initializer->wide_string.string = *string;
2207 * Build an initializer from a given expression.
2209 static initializer_t *initializer_from_expression(type_t *orig_type,
2210 expression_t *expression)
2212 /* TODO check that expression is a constant expression */
2214 /* §6.7.8.14/15 char array may be initialized by string literals */
2215 type_t *type = skip_typeref(orig_type);
2216 type_t *expr_type_orig = expression->base.type;
2217 type_t *expr_type = skip_typeref(expr_type_orig);
2218 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2219 array_type_t *const array_type = &type->array;
2220 type_t *const element_type = skip_typeref(array_type->element_type);
2222 if (element_type->kind == TYPE_ATOMIC) {
2223 atomic_type_kind_t akind = element_type->atomic.akind;
2224 switch (expression->kind) {
2225 case EXPR_STRING_LITERAL:
2226 if (akind == ATOMIC_TYPE_CHAR
2227 || akind == ATOMIC_TYPE_SCHAR
2228 || akind == ATOMIC_TYPE_UCHAR) {
2229 return initializer_from_string(array_type,
2230 &expression->string.value);
2234 case EXPR_WIDE_STRING_LITERAL: {
2235 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2236 if (get_unqualified_type(element_type) == bare_wchar_type) {
2237 return initializer_from_wide_string(array_type,
2238 &expression->wide_string.value);
2249 assign_error_t error = semantic_assign(type, expression);
2250 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2252 report_assign_error(error, type, expression, "initializer",
2253 &expression->base.source_position);
2255 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2257 if (type->kind == TYPE_BITFIELD) {
2258 type = type->bitfield.base_type;
2261 result->value.value = create_implicit_cast(expression, type);
2267 * Checks if a given expression can be used as an constant initializer.
2269 static bool is_initializer_constant(const expression_t *expression)
2271 return is_constant_expression(expression)
2272 || is_address_constant(expression);
2276 * Parses an scalar initializer.
2278 * §6.7.8.11; eat {} without warning
2280 static initializer_t *parse_scalar_initializer(type_t *type,
2281 bool must_be_constant)
2283 /* there might be extra {} hierarchies */
2285 if (token.type == '{') {
2287 warningf(HERE, "extra curly braces around scalar initializer");
2291 } while (token.type == '{');
2294 expression_t *expression = parse_assignment_expression();
2295 mark_vars_read(expression, NULL);
2296 if (must_be_constant && !is_initializer_constant(expression)) {
2297 errorf(&expression->base.source_position,
2298 "Initialisation expression '%E' is not constant",
2302 initializer_t *initializer = initializer_from_expression(type, expression);
2304 if (initializer == NULL) {
2305 errorf(&expression->base.source_position,
2306 "expression '%E' (type '%T') doesn't match expected type '%T'",
2307 expression, expression->base.type, type);
2312 bool additional_warning_displayed = false;
2313 while (braces > 0) {
2314 if (token.type == ',') {
2317 if (token.type != '}') {
2318 if (!additional_warning_displayed && warning.other) {
2319 warningf(HERE, "additional elements in scalar initializer");
2320 additional_warning_displayed = true;
2331 * An entry in the type path.
2333 typedef struct type_path_entry_t type_path_entry_t;
2334 struct type_path_entry_t {
2335 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2337 size_t index; /**< For array types: the current index. */
2338 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2343 * A type path expression a position inside compound or array types.
2345 typedef struct type_path_t type_path_t;
2346 struct type_path_t {
2347 type_path_entry_t *path; /**< An flexible array containing the current path. */
2348 type_t *top_type; /**< type of the element the path points */
2349 size_t max_index; /**< largest index in outermost array */
2353 * Prints a type path for debugging.
2355 static __attribute__((unused)) void debug_print_type_path(
2356 const type_path_t *path)
2358 size_t len = ARR_LEN(path->path);
2360 for (size_t i = 0; i < len; ++i) {
2361 const type_path_entry_t *entry = & path->path[i];
2363 type_t *type = skip_typeref(entry->type);
2364 if (is_type_compound(type)) {
2365 /* in gcc mode structs can have no members */
2366 if (entry->v.compound_entry == NULL) {
2370 fprintf(stderr, ".%s",
2371 entry->v.compound_entry->base.symbol->string);
2372 } else if (is_type_array(type)) {
2373 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2375 fprintf(stderr, "-INVALID-");
2378 if (path->top_type != NULL) {
2379 fprintf(stderr, " (");
2380 print_type(path->top_type);
2381 fprintf(stderr, ")");
2386 * Return the top type path entry, ie. in a path
2387 * (type).a.b returns the b.
2389 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2391 size_t len = ARR_LEN(path->path);
2393 return &path->path[len-1];
2397 * Enlarge the type path by an (empty) element.
2399 static type_path_entry_t *append_to_type_path(type_path_t *path)
2401 size_t len = ARR_LEN(path->path);
2402 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2404 type_path_entry_t *result = & path->path[len];
2405 memset(result, 0, sizeof(result[0]));
2410 * Descending into a sub-type. Enter the scope of the current top_type.
2412 static void descend_into_subtype(type_path_t *path)
2414 type_t *orig_top_type = path->top_type;
2415 type_t *top_type = skip_typeref(orig_top_type);
2417 type_path_entry_t *top = append_to_type_path(path);
2418 top->type = top_type;
2420 if (is_type_compound(top_type)) {
2421 compound_t *compound = top_type->compound.compound;
2422 entity_t *entry = compound->members.entities;
2424 if (entry != NULL) {
2425 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2426 top->v.compound_entry = &entry->declaration;
2427 path->top_type = entry->declaration.type;
2429 path->top_type = NULL;
2431 } else if (is_type_array(top_type)) {
2433 path->top_type = top_type->array.element_type;
2435 assert(!is_type_valid(top_type));
2440 * Pop an entry from the given type path, ie. returning from
2441 * (type).a.b to (type).a
2443 static void ascend_from_subtype(type_path_t *path)
2445 type_path_entry_t *top = get_type_path_top(path);
2447 path->top_type = top->type;
2449 size_t len = ARR_LEN(path->path);
2450 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2454 * Pop entries from the given type path until the given
2455 * path level is reached.
2457 static void ascend_to(type_path_t *path, size_t top_path_level)
2459 size_t len = ARR_LEN(path->path);
2461 while (len > top_path_level) {
2462 ascend_from_subtype(path);
2463 len = ARR_LEN(path->path);
2467 static bool walk_designator(type_path_t *path, const designator_t *designator,
2468 bool used_in_offsetof)
2470 for (; designator != NULL; designator = designator->next) {
2471 type_path_entry_t *top = get_type_path_top(path);
2472 type_t *orig_type = top->type;
2474 type_t *type = skip_typeref(orig_type);
2476 if (designator->symbol != NULL) {
2477 symbol_t *symbol = designator->symbol;
2478 if (!is_type_compound(type)) {
2479 if (is_type_valid(type)) {
2480 errorf(&designator->source_position,
2481 "'.%Y' designator used for non-compound type '%T'",
2485 top->type = type_error_type;
2486 top->v.compound_entry = NULL;
2487 orig_type = type_error_type;
2489 compound_t *compound = type->compound.compound;
2490 entity_t *iter = compound->members.entities;
2491 for (; iter != NULL; iter = iter->base.next) {
2492 if (iter->base.symbol == symbol) {
2497 errorf(&designator->source_position,
2498 "'%T' has no member named '%Y'", orig_type, symbol);
2501 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2502 if (used_in_offsetof) {
2503 type_t *real_type = skip_typeref(iter->declaration.type);
2504 if (real_type->kind == TYPE_BITFIELD) {
2505 errorf(&designator->source_position,
2506 "offsetof designator '%Y' may not specify bitfield",
2512 top->type = orig_type;
2513 top->v.compound_entry = &iter->declaration;
2514 orig_type = iter->declaration.type;
2517 expression_t *array_index = designator->array_index;
2518 assert(designator->array_index != NULL);
2520 if (!is_type_array(type)) {
2521 if (is_type_valid(type)) {
2522 errorf(&designator->source_position,
2523 "[%E] designator used for non-array type '%T'",
2524 array_index, orig_type);
2529 long index = fold_constant(array_index);
2530 if (!used_in_offsetof) {
2532 errorf(&designator->source_position,
2533 "array index [%E] must be positive", array_index);
2534 } else if (type->array.size_constant) {
2535 long array_size = type->array.size;
2536 if (index >= array_size) {
2537 errorf(&designator->source_position,
2538 "designator [%E] (%d) exceeds array size %d",
2539 array_index, index, array_size);
2544 top->type = orig_type;
2545 top->v.index = (size_t) index;
2546 orig_type = type->array.element_type;
2548 path->top_type = orig_type;
2550 if (designator->next != NULL) {
2551 descend_into_subtype(path);
2560 static void advance_current_object(type_path_t *path, size_t top_path_level)
2562 type_path_entry_t *top = get_type_path_top(path);
2564 type_t *type = skip_typeref(top->type);
2565 if (is_type_union(type)) {
2566 /* in unions only the first element is initialized */
2567 top->v.compound_entry = NULL;
2568 } else if (is_type_struct(type)) {
2569 declaration_t *entry = top->v.compound_entry;
2571 entity_t *next_entity = entry->base.next;
2572 if (next_entity != NULL) {
2573 assert(is_declaration(next_entity));
2574 entry = &next_entity->declaration;
2579 top->v.compound_entry = entry;
2580 if (entry != NULL) {
2581 path->top_type = entry->type;
2584 } else if (is_type_array(type)) {
2585 assert(is_type_array(type));
2589 if (!type->array.size_constant || top->v.index < type->array.size) {
2593 assert(!is_type_valid(type));
2597 /* we're past the last member of the current sub-aggregate, try if we
2598 * can ascend in the type hierarchy and continue with another subobject */
2599 size_t len = ARR_LEN(path->path);
2601 if (len > top_path_level) {
2602 ascend_from_subtype(path);
2603 advance_current_object(path, top_path_level);
2605 path->top_type = NULL;
2610 * skip until token is found.
2612 static void skip_until(int type)
2614 while (token.type != type) {
2615 if (token.type == T_EOF)
2622 * skip any {...} blocks until a closing bracket is reached.
2624 static void skip_initializers(void)
2626 if (token.type == '{')
2629 while (token.type != '}') {
2630 if (token.type == T_EOF)
2632 if (token.type == '{') {
2640 static initializer_t *create_empty_initializer(void)
2642 static initializer_t empty_initializer
2643 = { .list = { { INITIALIZER_LIST }, 0 } };
2644 return &empty_initializer;
2648 * Parse a part of an initialiser for a struct or union,
2650 static initializer_t *parse_sub_initializer(type_path_t *path,
2651 type_t *outer_type, size_t top_path_level,
2652 parse_initializer_env_t *env)
2654 if (token.type == '}') {
2655 /* empty initializer */
2656 return create_empty_initializer();
2659 type_t *orig_type = path->top_type;
2660 type_t *type = NULL;
2662 if (orig_type == NULL) {
2663 /* We are initializing an empty compound. */
2665 type = skip_typeref(orig_type);
2668 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2671 designator_t *designator = NULL;
2672 if (token.type == '.' || token.type == '[') {
2673 designator = parse_designation();
2674 goto finish_designator;
2675 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2676 /* GNU-style designator ("identifier: value") */
2677 designator = allocate_ast_zero(sizeof(designator[0]));
2678 designator->source_position = token.source_position;
2679 designator->symbol = token.v.symbol;
2684 /* reset path to toplevel, evaluate designator from there */
2685 ascend_to(path, top_path_level);
2686 if (!walk_designator(path, designator, false)) {
2687 /* can't continue after designation error */
2691 initializer_t *designator_initializer
2692 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2693 designator_initializer->designator.designator = designator;
2694 ARR_APP1(initializer_t*, initializers, designator_initializer);
2696 orig_type = path->top_type;
2697 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2702 if (token.type == '{') {
2703 if (type != NULL && is_type_scalar(type)) {
2704 sub = parse_scalar_initializer(type, env->must_be_constant);
2708 if (env->entity != NULL) {
2710 "extra brace group at end of initializer for '%Y'",
2711 env->entity->base.symbol);
2713 errorf(HERE, "extra brace group at end of initializer");
2716 descend_into_subtype(path);
2718 add_anchor_token('}');
2719 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2721 rem_anchor_token('}');
2724 ascend_from_subtype(path);
2725 expect('}', end_error);
2727 expect('}', end_error);
2728 goto error_parse_next;
2732 /* must be an expression */
2733 expression_t *expression = parse_assignment_expression();
2734 mark_vars_read(expression, NULL);
2736 if (env->must_be_constant && !is_initializer_constant(expression)) {
2737 errorf(&expression->base.source_position,
2738 "Initialisation expression '%E' is not constant",
2743 /* we are already outside, ... */
2744 type_t *const outer_type_skip = skip_typeref(outer_type);
2745 if (is_type_compound(outer_type_skip) &&
2746 !outer_type_skip->compound.compound->complete) {
2747 goto error_parse_next;
2752 /* handle { "string" } special case */
2753 if ((expression->kind == EXPR_STRING_LITERAL
2754 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2755 && outer_type != NULL) {
2756 sub = initializer_from_expression(outer_type, expression);
2758 if (token.type == ',') {
2761 if (token.type != '}' && warning.other) {
2762 warningf(HERE, "excessive elements in initializer for type '%T'",
2765 /* TODO: eat , ... */
2770 /* descend into subtypes until expression matches type */
2772 orig_type = path->top_type;
2773 type = skip_typeref(orig_type);
2775 sub = initializer_from_expression(orig_type, expression);
2779 if (!is_type_valid(type)) {
2782 if (is_type_scalar(type)) {
2783 errorf(&expression->base.source_position,
2784 "expression '%E' doesn't match expected type '%T'",
2785 expression, orig_type);
2789 descend_into_subtype(path);
2793 /* update largest index of top array */
2794 const type_path_entry_t *first = &path->path[0];
2795 type_t *first_type = first->type;
2796 first_type = skip_typeref(first_type);
2797 if (is_type_array(first_type)) {
2798 size_t index = first->v.index;
2799 if (index > path->max_index)
2800 path->max_index = index;
2804 /* append to initializers list */
2805 ARR_APP1(initializer_t*, initializers, sub);
2808 if (warning.other) {
2809 if (env->entity != NULL) {
2810 warningf(HERE, "excess elements in struct initializer for '%Y'",
2811 env->entity->base.symbol);
2813 warningf(HERE, "excess elements in struct initializer");
2819 if (token.type == '}') {
2822 expect(',', end_error);
2823 if (token.type == '}') {
2828 /* advance to the next declaration if we are not at the end */
2829 advance_current_object(path, top_path_level);
2830 orig_type = path->top_type;
2831 if (orig_type != NULL)
2832 type = skip_typeref(orig_type);
2838 size_t len = ARR_LEN(initializers);
2839 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2840 initializer_t *result = allocate_ast_zero(size);
2841 result->kind = INITIALIZER_LIST;
2842 result->list.len = len;
2843 memcpy(&result->list.initializers, initializers,
2844 len * sizeof(initializers[0]));
2846 DEL_ARR_F(initializers);
2847 ascend_to(path, top_path_level+1);
2852 skip_initializers();
2853 DEL_ARR_F(initializers);
2854 ascend_to(path, top_path_level+1);
2859 * Parses an initializer. Parsers either a compound literal
2860 * (env->declaration == NULL) or an initializer of a declaration.
2862 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2864 type_t *type = skip_typeref(env->type);
2865 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2866 initializer_t *result;
2868 if (is_type_scalar(type)) {
2869 result = parse_scalar_initializer(type, env->must_be_constant);
2870 } else if (token.type == '{') {
2874 memset(&path, 0, sizeof(path));
2875 path.top_type = env->type;
2876 path.path = NEW_ARR_F(type_path_entry_t, 0);
2878 descend_into_subtype(&path);
2880 add_anchor_token('}');
2881 result = parse_sub_initializer(&path, env->type, 1, env);
2882 rem_anchor_token('}');
2884 max_index = path.max_index;
2885 DEL_ARR_F(path.path);
2887 expect('}', end_error);
2889 /* parse_scalar_initializer() also works in this case: we simply
2890 * have an expression without {} around it */
2891 result = parse_scalar_initializer(type, env->must_be_constant);
2894 /* §6.7.8:22 array initializers for arrays with unknown size determine
2895 * the array type size */
2896 if (is_type_array(type) && type->array.size_expression == NULL
2897 && result != NULL) {
2899 switch (result->kind) {
2900 case INITIALIZER_LIST:
2901 assert(max_index != 0xdeadbeaf);
2902 size = max_index + 1;
2905 case INITIALIZER_STRING:
2906 size = result->string.string.size;
2909 case INITIALIZER_WIDE_STRING:
2910 size = result->wide_string.string.size;
2913 case INITIALIZER_DESIGNATOR:
2914 case INITIALIZER_VALUE:
2915 /* can happen for parse errors */
2920 internal_errorf(HERE, "invalid initializer type");
2923 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2924 cnst->base.type = type_size_t;
2925 cnst->conste.v.int_value = size;
2927 type_t *new_type = duplicate_type(type);
2929 new_type->array.size_expression = cnst;
2930 new_type->array.size_constant = true;
2931 new_type->array.has_implicit_size = true;
2932 new_type->array.size = size;
2933 env->type = new_type;
2941 static void append_entity(scope_t *scope, entity_t *entity)
2943 if (scope->last_entity != NULL) {
2944 scope->last_entity->base.next = entity;
2946 scope->entities = entity;
2948 scope->last_entity = entity;
2952 static compound_t *parse_compound_type_specifier(bool is_struct)
2954 gnu_attribute_t *attributes = NULL;
2955 decl_modifiers_t modifiers = 0;
2962 symbol_t *symbol = NULL;
2963 compound_t *compound = NULL;
2965 if (token.type == T___attribute__) {
2966 modifiers |= parse_attributes(&attributes);
2969 if (token.type == T_IDENTIFIER) {
2970 symbol = token.v.symbol;
2973 namespace_tag_t const namespc =
2974 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2975 entity_t *entity = get_entity(symbol, namespc);
2976 if (entity != NULL) {
2977 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2978 compound = &entity->compound;
2979 if (compound->base.parent_scope != current_scope &&
2980 (token.type == '{' || token.type == ';')) {
2981 /* we're in an inner scope and have a definition. Shadow
2982 * existing definition in outer scope */
2984 } else if (compound->complete && token.type == '{') {
2985 assert(symbol != NULL);
2986 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2987 is_struct ? "struct" : "union", symbol,
2988 &compound->base.source_position);
2989 /* clear members in the hope to avoid further errors */
2990 compound->members.entities = NULL;
2993 } else if (token.type != '{') {
2995 parse_error_expected("while parsing struct type specifier",
2996 T_IDENTIFIER, '{', NULL);
2998 parse_error_expected("while parsing union type specifier",
2999 T_IDENTIFIER, '{', NULL);
3005 if (compound == NULL) {
3006 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3007 entity_t *entity = allocate_entity_zero(kind);
3008 compound = &entity->compound;
3010 compound->base.namespc =
3011 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3012 compound->base.source_position = token.source_position;
3013 compound->base.symbol = symbol;
3014 compound->base.parent_scope = current_scope;
3015 if (symbol != NULL) {
3016 environment_push(entity);
3018 append_entity(current_scope, entity);
3021 if (token.type == '{') {
3022 parse_compound_type_entries(compound);
3023 modifiers |= parse_attributes(&attributes);
3025 if (symbol == NULL) {
3026 assert(anonymous_entity == NULL);
3027 anonymous_entity = (entity_t*)compound;
3031 compound->modifiers |= modifiers;
3035 static void parse_enum_entries(type_t *const enum_type)
3039 if (token.type == '}') {
3040 errorf(HERE, "empty enum not allowed");
3045 add_anchor_token('}');
3047 if (token.type != T_IDENTIFIER) {
3048 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3050 rem_anchor_token('}');
3054 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3055 entity->enum_value.enum_type = enum_type;
3056 entity->base.symbol = token.v.symbol;
3057 entity->base.source_position = token.source_position;
3060 if (token.type == '=') {
3062 expression_t *value = parse_constant_expression();
3064 value = create_implicit_cast(value, enum_type);
3065 entity->enum_value.value = value;
3070 record_entity(entity, false);
3072 if (token.type != ',')
3075 } while (token.type != '}');
3076 rem_anchor_token('}');
3078 expect('}', end_error);
3084 static type_t *parse_enum_specifier(void)
3086 gnu_attribute_t *attributes = NULL;
3091 if (token.type == T_IDENTIFIER) {
3092 symbol = token.v.symbol;
3095 entity = get_entity(symbol, NAMESPACE_ENUM);
3096 if (entity != NULL) {
3097 assert(entity->kind == ENTITY_ENUM);
3098 if (entity->base.parent_scope != current_scope &&
3099 (token.type == '{' || token.type == ';')) {
3100 /* we're in an inner scope and have a definition. Shadow
3101 * existing definition in outer scope */
3103 } else if (entity->enume.complete && token.type == '{') {
3104 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3105 symbol, &entity->base.source_position);
3108 } else if (token.type != '{') {
3109 parse_error_expected("while parsing enum type specifier",
3110 T_IDENTIFIER, '{', NULL);
3117 if (entity == NULL) {
3118 entity = allocate_entity_zero(ENTITY_ENUM);
3119 entity->base.namespc = NAMESPACE_ENUM;
3120 entity->base.source_position = token.source_position;
3121 entity->base.symbol = symbol;
3122 entity->base.parent_scope = current_scope;
3125 type_t *const type = allocate_type_zero(TYPE_ENUM);
3126 type->enumt.enume = &entity->enume;
3127 type->enumt.akind = ATOMIC_TYPE_INT;
3129 if (token.type == '{') {
3130 if (symbol != NULL) {
3131 environment_push(entity);
3133 append_entity(current_scope, entity);
3134 entity->enume.complete = true;
3136 parse_enum_entries(type);
3137 parse_attributes(&attributes);
3139 if (symbol == NULL) {
3140 assert(anonymous_entity == NULL);
3141 anonymous_entity = entity;
3143 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3144 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3152 * if a symbol is a typedef to another type, return true
3154 static bool is_typedef_symbol(symbol_t *symbol)
3156 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3157 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3160 static type_t *parse_typeof(void)
3166 expect('(', end_error);
3167 add_anchor_token(')');
3169 expression_t *expression = NULL;
3171 bool old_type_prop = in_type_prop;
3172 bool old_gcc_extension = in_gcc_extension;
3173 in_type_prop = true;
3175 while (token.type == T___extension__) {
3176 /* This can be a prefix to a typename or an expression. */
3178 in_gcc_extension = true;
3180 switch (token.type) {
3182 if (is_typedef_symbol(token.v.symbol)) {
3183 type = parse_typename();
3185 expression = parse_expression();
3186 type = revert_automatic_type_conversion(expression);
3191 type = parse_typename();
3195 expression = parse_expression();
3196 type = expression->base.type;
3199 in_type_prop = old_type_prop;
3200 in_gcc_extension = old_gcc_extension;
3202 rem_anchor_token(')');
3203 expect(')', end_error);
3205 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3206 typeof_type->typeoft.expression = expression;
3207 typeof_type->typeoft.typeof_type = type;
3214 typedef enum specifiers_t {
3215 SPECIFIER_SIGNED = 1 << 0,
3216 SPECIFIER_UNSIGNED = 1 << 1,
3217 SPECIFIER_LONG = 1 << 2,
3218 SPECIFIER_INT = 1 << 3,
3219 SPECIFIER_DOUBLE = 1 << 4,
3220 SPECIFIER_CHAR = 1 << 5,
3221 SPECIFIER_WCHAR_T = 1 << 6,
3222 SPECIFIER_SHORT = 1 << 7,
3223 SPECIFIER_LONG_LONG = 1 << 8,
3224 SPECIFIER_FLOAT = 1 << 9,
3225 SPECIFIER_BOOL = 1 << 10,
3226 SPECIFIER_VOID = 1 << 11,
3227 SPECIFIER_INT8 = 1 << 12,
3228 SPECIFIER_INT16 = 1 << 13,
3229 SPECIFIER_INT32 = 1 << 14,
3230 SPECIFIER_INT64 = 1 << 15,
3231 SPECIFIER_INT128 = 1 << 16,
3232 SPECIFIER_COMPLEX = 1 << 17,
3233 SPECIFIER_IMAGINARY = 1 << 18,
3236 static type_t *create_builtin_type(symbol_t *const symbol,
3237 type_t *const real_type)
3239 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3240 type->builtin.symbol = symbol;
3241 type->builtin.real_type = real_type;
3242 return identify_new_type(type);
3245 static type_t *get_typedef_type(symbol_t *symbol)
3247 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3248 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3251 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3252 type->typedeft.typedefe = &entity->typedefe;
3258 * check for the allowed MS alignment values.
3260 static bool check_alignment_value(long long intvalue)
3262 if (intvalue < 1 || intvalue > 8192) {
3263 errorf(HERE, "illegal alignment value");
3266 unsigned v = (unsigned)intvalue;
3267 for (unsigned i = 1; i <= 8192; i += i) {
3271 errorf(HERE, "alignment must be power of two");
3275 #define DET_MOD(name, tag) do { \
3276 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3277 *modifiers |= tag; \
3280 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3282 decl_modifiers_t *modifiers = &specifiers->modifiers;
3285 if (token.type == T_restrict) {
3287 DET_MOD(restrict, DM_RESTRICT);
3289 } else if (token.type != T_IDENTIFIER)
3291 symbol_t *symbol = token.v.symbol;
3292 if (symbol == sym_align) {
3294 expect('(', end_error);
3295 if (token.type != T_INTEGER)
3297 if (check_alignment_value(token.v.intvalue)) {
3298 if (specifiers->alignment != 0 && warning.other)
3299 warningf(HERE, "align used more than once");
3300 specifiers->alignment = (unsigned char)token.v.intvalue;
3303 expect(')', end_error);
3304 } else if (symbol == sym_allocate) {
3306 expect('(', end_error);
3307 if (token.type != T_IDENTIFIER)
3309 (void)token.v.symbol;
3310 expect(')', end_error);
3311 } else if (symbol == sym_dllimport) {
3313 DET_MOD(dllimport, DM_DLLIMPORT);
3314 } else if (symbol == sym_dllexport) {
3316 DET_MOD(dllexport, DM_DLLEXPORT);
3317 } else if (symbol == sym_thread) {
3319 DET_MOD(thread, DM_THREAD);
3320 } else if (symbol == sym_naked) {
3322 DET_MOD(naked, DM_NAKED);
3323 } else if (symbol == sym_noinline) {
3325 DET_MOD(noinline, DM_NOINLINE);
3326 } else if (symbol == sym_returns_twice) {
3328 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3329 } else if (symbol == sym_noreturn) {
3331 DET_MOD(noreturn, DM_NORETURN);
3332 } else if (symbol == sym_nothrow) {
3334 DET_MOD(nothrow, DM_NOTHROW);
3335 } else if (symbol == sym_novtable) {
3337 DET_MOD(novtable, DM_NOVTABLE);
3338 } else if (symbol == sym_property) {
3340 expect('(', end_error);
3342 bool is_get = false;
3343 if (token.type != T_IDENTIFIER)
3345 if (token.v.symbol == sym_get) {
3347 } else if (token.v.symbol == sym_put) {
3349 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3353 expect('=', end_error);
3354 if (token.type != T_IDENTIFIER)
3357 if (specifiers->get_property_sym != NULL) {
3358 errorf(HERE, "get property name already specified");
3360 specifiers->get_property_sym = token.v.symbol;
3363 if (specifiers->put_property_sym != NULL) {
3364 errorf(HERE, "put property name already specified");
3366 specifiers->put_property_sym = token.v.symbol;
3370 if (token.type == ',') {
3376 expect(')', end_error);
3377 } else if (symbol == sym_selectany) {
3379 DET_MOD(selectany, DM_SELECTANY);
3380 } else if (symbol == sym_uuid) {
3382 expect('(', end_error);
3383 if (token.type != T_STRING_LITERAL)
3386 expect(')', end_error);
3387 } else if (symbol == sym_deprecated) {
3389 if (specifiers->deprecated != 0 && warning.other)
3390 warningf(HERE, "deprecated used more than once");
3391 specifiers->deprecated = true;
3392 if (token.type == '(') {
3394 if (token.type == T_STRING_LITERAL) {
3395 specifiers->deprecated_string = token.v.string.begin;
3398 errorf(HERE, "string literal expected");
3400 expect(')', end_error);
3402 } else if (symbol == sym_noalias) {
3404 DET_MOD(noalias, DM_NOALIAS);
3407 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3409 if (token.type == '(')
3413 if (token.type == ',')
3420 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3422 entity_t *entity = allocate_entity_zero(kind);
3423 entity->base.source_position = *HERE;
3424 entity->base.symbol = symbol;
3425 if (is_declaration(entity)) {
3426 entity->declaration.type = type_error_type;
3427 entity->declaration.implicit = true;
3428 } else if (kind == ENTITY_TYPEDEF) {
3429 entity->typedefe.type = type_error_type;
3430 entity->typedefe.builtin = true;
3432 if (kind != ENTITY_COMPOUND_MEMBER)
3433 record_entity(entity, false);
3437 static variable_t *parse_microsoft_based(void)
3439 if (token.type != T_IDENTIFIER) {
3440 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3443 symbol_t *symbol = token.v.symbol;
3444 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3446 variable_t *variable;
3447 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3448 errorf(HERE, "'%Y' is not a variable name.", symbol);
3449 variable = &create_error_entity(symbol, ENTITY_VARIABLE)->variable;
3451 variable = &entity->variable;
3453 type_t *const type = variable->base.type;
3454 if (is_type_valid(type)) {
3455 if (! is_type_pointer(skip_typeref(type))) {
3456 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3458 if (variable->base.base.parent_scope != file_scope) {
3459 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3468 * Finish the construction of a struct type by calculating
3469 * its size, offsets, alignment.
3471 static void finish_struct_type(compound_type_t *type)
3473 assert(type->compound != NULL);
3475 compound_t *compound = type->compound;
3476 if (!compound->complete)
3481 il_alignment_t alignment = 1;
3482 bool need_pad = false;
3484 entity_t *entry = compound->members.entities;
3485 for (; entry != NULL; entry = entry->base.next) {
3486 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3489 type_t *m_type = skip_typeref(entry->declaration.type);
3490 if (! is_type_valid(m_type)) {
3491 /* simply ignore errors here */
3494 il_alignment_t m_alignment = m_type->base.alignment;
3495 if (m_alignment > alignment)
3496 alignment = m_alignment;
3498 offset = (size + m_alignment - 1) & -m_alignment;
3502 entry->compound_member.offset = offset;
3503 size = offset + m_type->base.size;
3505 if (type->base.alignment != 0) {
3506 alignment = type->base.alignment;
3509 offset = (size + alignment - 1) & -alignment;
3514 if (warning.padded) {
3515 warningf(&compound->base.source_position, "'%T' needs padding", type);
3518 if (compound->modifiers & DM_PACKED && warning.packed) {
3519 warningf(&compound->base.source_position,
3520 "superfluous packed attribute on '%T'", type);
3524 type->base.size = offset;
3525 type->base.alignment = alignment;
3529 * Finish the construction of an union type by calculating
3530 * its size and alignment.
3532 static void finish_union_type(compound_type_t *type)
3534 assert(type->compound != NULL);
3536 compound_t *compound = type->compound;
3537 if (! compound->complete)
3541 il_alignment_t alignment = 1;
3543 entity_t *entry = compound->members.entities;
3544 for (; entry != NULL; entry = entry->base.next) {
3545 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3548 type_t *m_type = skip_typeref(entry->declaration.type);
3549 if (! is_type_valid(m_type))
3552 entry->compound_member.offset = 0;
3553 if (m_type->base.size > size)
3554 size = m_type->base.size;
3555 if (m_type->base.alignment > alignment)
3556 alignment = m_type->base.alignment;
3558 if (type->base.alignment != 0) {
3559 alignment = type->base.alignment;
3561 size = (size + alignment - 1) & -alignment;
3562 type->base.size = size;
3563 type->base.alignment = alignment;
3566 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3569 type_t *type = skip_typeref(orig_type);
3571 /* at least: byte, word, pointer, list of machine modes
3572 * __XXX___ is interpreted as XXX */
3574 /* This isn't really correct, the backend should provide a list of machine
3575 * specific modes (according to gcc philosophy that is...) */
3576 const char *symbol_str = attribute->u.symbol->string;
3577 bool sign = is_type_signed(type);
3578 atomic_type_kind_t akind;
3579 if (strcmp_underscore("QI", symbol_str) == 0 ||
3580 strcmp_underscore("byte", symbol_str) == 0) {
3581 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3582 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3583 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3584 } else if (strcmp_underscore("SI", symbol_str) == 0
3585 || strcmp_underscore("word", symbol_str) == 0
3586 || strcmp_underscore("pointer", symbol_str) == 0) {
3587 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3588 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3589 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3592 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3596 if (type->kind == TYPE_ATOMIC) {
3597 type_t *copy = duplicate_type(type);
3598 copy->atomic.akind = akind;
3599 return identify_new_type(copy);
3600 } else if (type->kind == TYPE_ENUM) {
3601 type_t *copy = duplicate_type(type);
3602 copy->enumt.akind = akind;
3603 return identify_new_type(copy);
3604 } else if (is_type_pointer(type)) {
3605 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3609 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3613 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3616 const gnu_attribute_t *attribute = attributes;
3617 for ( ; attribute != NULL; attribute = attribute->next) {
3618 if (attribute->invalid)
3621 if (attribute->kind == GNU_AK_MODE) {
3622 type = handle_attribute_mode(attribute, type);
3623 } else if (attribute->kind == GNU_AK_ALIGNED) {
3624 int alignment = 32; /* TODO: fill in maximum useful alignment for
3626 if (attribute->has_arguments)
3627 alignment = attribute->u.argument;
3629 type_t *copy = duplicate_type(type);
3630 copy->base.alignment = attribute->u.argument;
3631 type = identify_new_type(copy);
3638 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3640 type_t *type = NULL;
3641 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3642 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3643 unsigned type_specifiers = 0;
3644 bool newtype = false;
3645 bool saw_error = false;
3646 bool old_gcc_extension = in_gcc_extension;
3648 specifiers->source_position = token.source_position;
3651 specifiers->modifiers
3652 |= parse_attributes(&specifiers->gnu_attributes);
3654 switch (token.type) {
3656 #define MATCH_STORAGE_CLASS(token, class) \
3658 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3659 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3661 specifiers->storage_class = class; \
3662 if (specifiers->thread_local) \
3663 goto check_thread_storage_class; \
3667 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3668 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3669 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3670 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3671 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3675 expect('(', end_error);
3676 add_anchor_token(')');
3677 parse_microsoft_extended_decl_modifier(specifiers);
3678 rem_anchor_token(')');
3679 expect(')', end_error);
3683 if (specifiers->thread_local) {
3684 errorf(HERE, "duplicate '__thread'");
3686 specifiers->thread_local = true;
3687 check_thread_storage_class:
3688 switch (specifiers->storage_class) {
3689 case STORAGE_CLASS_EXTERN:
3690 case STORAGE_CLASS_NONE:
3691 case STORAGE_CLASS_STATIC:
3695 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3696 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3697 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3698 wrong_thread_stoarge_class:
3699 errorf(HERE, "'__thread' used with '%s'", wrong);
3706 /* type qualifiers */
3707 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3709 qualifiers |= qualifier; \
3713 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3714 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3715 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3716 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3717 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3718 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3719 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3720 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3722 case T___extension__:
3724 in_gcc_extension = true;
3727 /* type specifiers */
3728 #define MATCH_SPECIFIER(token, specifier, name) \
3730 if (type_specifiers & specifier) { \
3731 errorf(HERE, "multiple " name " type specifiers given"); \
3733 type_specifiers |= specifier; \
3738 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3739 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3740 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3741 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3742 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3743 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3744 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3745 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3746 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3747 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3748 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3749 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3750 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3751 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3752 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3753 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3754 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3755 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3757 case T__forceinline:
3758 /* only in microsoft mode */
3759 specifiers->modifiers |= DM_FORCEINLINE;
3764 specifiers->is_inline = true;
3768 if (type_specifiers & SPECIFIER_LONG_LONG) {
3769 errorf(HERE, "multiple type specifiers given");
3770 } else if (type_specifiers & SPECIFIER_LONG) {
3771 type_specifiers |= SPECIFIER_LONG_LONG;
3773 type_specifiers |= SPECIFIER_LONG;
3779 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3781 type->compound.compound = parse_compound_type_specifier(true);
3782 finish_struct_type(&type->compound);
3786 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3787 type->compound.compound = parse_compound_type_specifier(false);
3788 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3789 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3790 finish_union_type(&type->compound);
3794 type = parse_enum_specifier();
3797 type = parse_typeof();
3799 case T___builtin_va_list:
3800 type = duplicate_type(type_valist);
3804 case T_IDENTIFIER: {
3805 /* only parse identifier if we haven't found a type yet */
3806 if (type != NULL || type_specifiers != 0) {
3807 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3808 * declaration, so it doesn't generate errors about expecting '(' or
3810 switch (look_ahead(1)->type) {
3817 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3821 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3826 goto finish_specifiers;
3830 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3831 if (typedef_type == NULL) {
3832 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3833 * declaration, so it doesn't generate 'implicit int' followed by more
3834 * errors later on. */
3835 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3841 errorf(HERE, "%K does not name a type", &token);
3844 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3846 type = allocate_type_zero(TYPE_TYPEDEF);
3847 type->typedeft.typedefe = &entity->typedefe;
3851 if (la1_type == '&' || la1_type == '*')
3852 goto finish_specifiers;
3857 goto finish_specifiers;
3862 type = typedef_type;
3866 /* function specifier */
3868 goto finish_specifiers;
3873 specifiers->modifiers
3874 |= parse_attributes(&specifiers->gnu_attributes);
3876 in_gcc_extension = old_gcc_extension;
3878 if (type == NULL || (saw_error && type_specifiers != 0)) {
3879 atomic_type_kind_t atomic_type;
3881 /* match valid basic types */
3882 switch (type_specifiers) {
3883 case SPECIFIER_VOID:
3884 atomic_type = ATOMIC_TYPE_VOID;
3886 case SPECIFIER_WCHAR_T:
3887 atomic_type = ATOMIC_TYPE_WCHAR_T;
3889 case SPECIFIER_CHAR:
3890 atomic_type = ATOMIC_TYPE_CHAR;
3892 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3893 atomic_type = ATOMIC_TYPE_SCHAR;
3895 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3896 atomic_type = ATOMIC_TYPE_UCHAR;
3898 case SPECIFIER_SHORT:
3899 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3900 case SPECIFIER_SHORT | SPECIFIER_INT:
3901 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3902 atomic_type = ATOMIC_TYPE_SHORT;
3904 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3905 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3906 atomic_type = ATOMIC_TYPE_USHORT;
3909 case SPECIFIER_SIGNED:
3910 case SPECIFIER_SIGNED | SPECIFIER_INT:
3911 atomic_type = ATOMIC_TYPE_INT;
3913 case SPECIFIER_UNSIGNED:
3914 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3915 atomic_type = ATOMIC_TYPE_UINT;
3917 case SPECIFIER_LONG:
3918 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3919 case SPECIFIER_LONG | SPECIFIER_INT:
3920 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3921 atomic_type = ATOMIC_TYPE_LONG;
3923 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3924 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3925 atomic_type = ATOMIC_TYPE_ULONG;
3928 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3929 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3930 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3931 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3933 atomic_type = ATOMIC_TYPE_LONGLONG;
3934 goto warn_about_long_long;
3936 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3937 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3939 atomic_type = ATOMIC_TYPE_ULONGLONG;
3940 warn_about_long_long:
3941 if (warning.long_long) {
3942 warningf(&specifiers->source_position,
3943 "ISO C90 does not support 'long long'");
3947 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3948 atomic_type = unsigned_int8_type_kind;
3951 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3952 atomic_type = unsigned_int16_type_kind;
3955 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3956 atomic_type = unsigned_int32_type_kind;
3959 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3960 atomic_type = unsigned_int64_type_kind;
3963 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3964 atomic_type = unsigned_int128_type_kind;
3967 case SPECIFIER_INT8:
3968 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3969 atomic_type = int8_type_kind;
3972 case SPECIFIER_INT16:
3973 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3974 atomic_type = int16_type_kind;
3977 case SPECIFIER_INT32:
3978 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3979 atomic_type = int32_type_kind;
3982 case SPECIFIER_INT64:
3983 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3984 atomic_type = int64_type_kind;
3987 case SPECIFIER_INT128:
3988 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3989 atomic_type = int128_type_kind;
3992 case SPECIFIER_FLOAT:
3993 atomic_type = ATOMIC_TYPE_FLOAT;
3995 case SPECIFIER_DOUBLE:
3996 atomic_type = ATOMIC_TYPE_DOUBLE;
3998 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3999 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4001 case SPECIFIER_BOOL:
4002 atomic_type = ATOMIC_TYPE_BOOL;
4004 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4005 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4006 atomic_type = ATOMIC_TYPE_FLOAT;
4008 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4009 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4010 atomic_type = ATOMIC_TYPE_DOUBLE;
4012 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4013 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4014 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4017 /* invalid specifier combination, give an error message */
4018 if (type_specifiers == 0) {
4022 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4023 if (!(c_mode & _CXX) && !strict_mode) {
4024 if (warning.implicit_int) {
4025 warningf(HERE, "no type specifiers in declaration, using 'int'");
4027 atomic_type = ATOMIC_TYPE_INT;
4030 errorf(HERE, "no type specifiers given in declaration");
4032 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4033 (type_specifiers & SPECIFIER_UNSIGNED)) {
4034 errorf(HERE, "signed and unsigned specifiers given");
4035 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4036 errorf(HERE, "only integer types can be signed or unsigned");
4038 errorf(HERE, "multiple datatypes in declaration");
4043 if (type_specifiers & SPECIFIER_COMPLEX) {
4044 type = allocate_type_zero(TYPE_COMPLEX);
4045 type->complex.akind = atomic_type;
4046 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4047 type = allocate_type_zero(TYPE_IMAGINARY);
4048 type->imaginary.akind = atomic_type;
4050 type = allocate_type_zero(TYPE_ATOMIC);
4051 type->atomic.akind = atomic_type;
4053 type->base.alignment = get_atomic_type_alignment(atomic_type);
4054 unsigned const size = get_atomic_type_size(atomic_type);
4056 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4058 } else if (type_specifiers != 0) {
4059 errorf(HERE, "multiple datatypes in declaration");
4062 /* FIXME: check type qualifiers here */
4064 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4065 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4066 type->base.qualifiers = qualifiers;
4067 type->base.modifiers = modifiers;
4070 type = identify_new_type(type);
4072 type = typehash_insert(type);
4075 type = handle_type_attributes(specifiers->gnu_attributes, type);
4076 specifiers->type = type;
4080 specifiers->type = type_error_type;
4084 static type_qualifiers_t parse_type_qualifiers(void)
4086 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4089 switch (token.type) {
4090 /* type qualifiers */
4091 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4092 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4093 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4094 /* microsoft extended type modifiers */
4095 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4096 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4097 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4098 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4099 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4108 * Parses an K&R identifier list
4110 static void parse_identifier_list(scope_t *scope)
4113 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4114 entity->base.source_position = token.source_position;
4115 entity->base.namespc = NAMESPACE_NORMAL;
4116 entity->base.symbol = token.v.symbol;
4117 /* a K&R parameter has no type, yet */
4121 append_entity(scope, entity);
4123 if (token.type != ',') {
4127 } while (token.type == T_IDENTIFIER);
4130 static entity_t *parse_parameter(void)
4132 declaration_specifiers_t specifiers;
4133 memset(&specifiers, 0, sizeof(specifiers));
4135 parse_declaration_specifiers(&specifiers);
4137 entity_t *entity = parse_declarator(&specifiers,
4138 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4139 anonymous_entity = NULL;
4143 static void semantic_parameter_incomplete(const entity_t *entity)
4145 assert(entity->kind == ENTITY_PARAMETER);
4147 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4148 * list in a function declarator that is part of a
4149 * definition of that function shall not have
4150 * incomplete type. */
4151 type_t *type = skip_typeref(entity->declaration.type);
4152 if (is_type_incomplete(type)) {
4153 errorf(&entity->base.source_position,
4154 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4155 entity->declaration.type);
4160 * Parses function type parameters (and optionally creates variable_t entities
4161 * for them in a scope)
4163 static void parse_parameters(function_type_t *type, scope_t *scope)
4166 add_anchor_token(')');
4167 int saved_comma_state = save_and_reset_anchor_state(',');
4169 if (token.type == T_IDENTIFIER &&
4170 !is_typedef_symbol(token.v.symbol)) {
4171 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4172 if (la1_type == ',' || la1_type == ')') {
4173 type->kr_style_parameters = true;
4174 type->unspecified_parameters = true;
4175 parse_identifier_list(scope);
4176 goto parameters_finished;
4180 if (token.type == ')') {
4181 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4182 if (!(c_mode & _CXX))
4183 type->unspecified_parameters = true;
4184 goto parameters_finished;
4187 function_parameter_t *parameter;
4188 function_parameter_t *last_parameter = NULL;
4191 switch (token.type) {
4194 type->variadic = true;
4195 goto parameters_finished;
4198 case T___extension__:
4201 entity_t *entity = parse_parameter();
4202 if (entity->kind == ENTITY_TYPEDEF) {
4203 errorf(&entity->base.source_position,
4204 "typedef not allowed as function parameter");
4207 assert(is_declaration(entity));
4209 /* func(void) is not a parameter */
4210 if (last_parameter == NULL
4211 && token.type == ')'
4212 && entity->base.symbol == NULL
4213 && skip_typeref(entity->declaration.type) == type_void) {
4214 goto parameters_finished;
4216 semantic_parameter_incomplete(entity);
4218 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4219 memset(parameter, 0, sizeof(parameter[0]));
4220 parameter->type = entity->declaration.type;
4222 if (scope != NULL) {
4223 append_entity(scope, entity);
4226 if (last_parameter != NULL) {
4227 last_parameter->next = parameter;
4229 type->parameters = parameter;
4231 last_parameter = parameter;
4236 goto parameters_finished;
4238 if (token.type != ',') {
4239 goto parameters_finished;
4245 parameters_finished:
4246 rem_anchor_token(')');
4247 expect(')', end_error);
4250 restore_anchor_state(',', saved_comma_state);
4253 typedef enum construct_type_kind_t {
4256 CONSTRUCT_REFERENCE,
4259 } construct_type_kind_t;
4261 typedef union construct_type_t construct_type_t;
4263 typedef struct construct_type_base_t {
4264 construct_type_kind_t kind;
4265 construct_type_t *next;
4266 } construct_type_base_t;
4268 typedef struct parsed_pointer_t {
4269 construct_type_base_t base;
4270 type_qualifiers_t type_qualifiers;
4271 variable_t *base_variable; /**< MS __based extension. */
4274 typedef struct parsed_reference_t {
4275 construct_type_base_t base;
4276 } parsed_reference_t;
4278 typedef struct construct_function_type_t {
4279 construct_type_base_t base;
4280 type_t *function_type;
4281 } construct_function_type_t;
4283 typedef struct parsed_array_t {
4284 construct_type_base_t base;
4285 type_qualifiers_t type_qualifiers;
4291 union construct_type_t {
4292 construct_type_kind_t kind;
4293 construct_type_base_t base;
4294 parsed_pointer_t pointer;
4295 parsed_reference_t reference;
4296 construct_function_type_t function;
4297 parsed_array_t array;
4300 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4304 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->pointer));
4305 parsed_pointer_t *pointer = &cons->pointer;
4306 memset(pointer, 0, sizeof(*pointer));
4307 cons->kind = CONSTRUCT_POINTER;
4308 pointer->type_qualifiers = parse_type_qualifiers();
4309 pointer->base_variable = base_variable;
4314 static construct_type_t *parse_reference_declarator(void)
4318 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
4319 parsed_reference_t *reference = &cons->reference;
4320 memset(reference, 0, sizeof(*reference));
4321 cons->kind = CONSTRUCT_REFERENCE;
4326 static construct_type_t *parse_array_declarator(void)
4329 add_anchor_token(']');
4331 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
4332 parsed_array_t *array = &cons->array;
4333 memset(array, 0, sizeof(*array));
4334 cons->kind = CONSTRUCT_ARRAY;
4336 if (token.type == T_static) {
4337 array->is_static = true;
4341 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4342 if (type_qualifiers != 0) {
4343 if (token.type == T_static) {
4344 array->is_static = true;
4348 array->type_qualifiers = type_qualifiers;
4350 if (token.type == '*' && look_ahead(1)->type == ']') {
4351 array->is_variable = true;
4353 } else if (token.type != ']') {
4354 expression_t *const size = parse_assignment_expression();
4356 mark_vars_read(size, NULL);
4359 rem_anchor_token(']');
4360 expect(']', end_error);
4366 static construct_type_t *parse_function_declarator(scope_t *scope,
4367 decl_modifiers_t modifiers)
4369 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4370 function_type_t *ftype = &type->function;
4372 ftype->linkage = current_linkage;
4374 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4375 case DM_NONE: break;
4376 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4377 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4378 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4379 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4382 errorf(HERE, "multiple calling conventions in declaration");
4386 parse_parameters(ftype, scope);
4388 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
4389 construct_function_type_t *function = &cons->function;
4390 memset(function, 0, sizeof(*function));
4391 cons->kind = CONSTRUCT_FUNCTION;
4392 function->function_type = type;
4397 typedef struct parse_declarator_env_t {
4398 decl_modifiers_t modifiers;
4400 source_position_t source_position;
4402 } parse_declarator_env_t;
4404 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4405 bool may_be_abstract)
4407 /* construct a single linked list of construct_type_t's which describe
4408 * how to construct the final declarator type */
4409 construct_type_t *first = NULL;
4410 construct_type_t **anchor = &first;
4411 gnu_attribute_t *attributes = NULL;
4413 decl_modifiers_t modifiers = parse_attributes(&attributes);
4416 construct_type_t *type;
4417 variable_t *based = NULL; /* MS __based extension */
4418 switch (token.type) {
4420 if (!(c_mode & _CXX))
4421 errorf(HERE, "references are only available for C++");
4422 type = parse_reference_declarator();
4426 source_position_t const pos = *HERE;
4428 expect('(', end_error);
4429 add_anchor_token(')');
4430 based = parse_microsoft_based();
4431 rem_anchor_token(')');
4432 expect(')', end_error);
4433 if (token.type != '*') {
4434 if (token.type == T__based) {
4435 errorf(&pos, "__based type modifier specified more than once");
4436 } else if (warning.other) {
4438 "__based does not precede a pointer declarator, ignored");
4446 type = parse_pointer_declarator(based);
4450 goto ptr_operator_end;
4454 anchor = &type->base.next;
4456 /* TODO: find out if this is correct */
4457 modifiers |= parse_attributes(&attributes);
4462 modifiers |= env->modifiers;
4463 env->modifiers = modifiers;
4466 construct_type_t *inner_types = NULL;
4468 switch (token.type) {
4471 errorf(HERE, "no identifier expected in typename");
4473 env->symbol = token.v.symbol;
4474 env->source_position = token.source_position;
4479 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4480 * interpreted as ``function with no parameter specification'', rather
4481 * than redundant parentheses around the omitted identifier. */
4482 if (look_ahead(1)->type != ')') {
4484 add_anchor_token(')');
4485 inner_types = parse_inner_declarator(env, may_be_abstract);
4486 if (inner_types != NULL) {
4487 /* All later declarators only modify the return type */
4490 rem_anchor_token(')');
4491 expect(')', end_error);
4495 if (may_be_abstract)
4497 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4502 construct_type_t **const p = anchor;
4505 construct_type_t *type;
4506 switch (token.type) {
4508 scope_t *scope = NULL;
4510 scope = &env->parameters;
4512 type = parse_function_declarator(scope, modifiers);
4516 type = parse_array_declarator();
4519 goto declarator_finished;
4522 /* insert in the middle of the list (at p) */
4523 type->base.next = *p;
4526 anchor = &type->base.next;
4529 declarator_finished:
4530 /* append inner_types at the end of the list, we don't to set anchor anymore
4531 * as it's not needed anymore */
4532 *anchor = inner_types;
4539 static void parse_declaration_attributes(entity_t *entity)
4541 gnu_attribute_t *attributes = NULL;
4542 decl_modifiers_t modifiers = parse_attributes(&attributes);
4548 if (entity->kind == ENTITY_TYPEDEF) {
4549 modifiers |= entity->typedefe.modifiers;
4550 type = entity->typedefe.type;
4552 assert(is_declaration(entity));
4553 modifiers |= entity->declaration.modifiers;
4554 type = entity->declaration.type;
4559 gnu_attribute_t *attribute = attributes;
4560 for ( ; attribute != NULL; attribute = attribute->next) {
4561 if (attribute->invalid)
4564 if (attribute->kind == GNU_AK_MODE) {
4565 type = handle_attribute_mode(attribute, type);
4566 } else if (attribute->kind == GNU_AK_ALIGNED) {
4567 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4568 if (attribute->has_arguments)
4569 alignment = attribute->u.argument;
4571 if (entity->kind == ENTITY_TYPEDEF) {
4572 type_t *copy = duplicate_type(type);
4573 copy->base.alignment = attribute->u.argument;
4574 type = identify_new_type(copy);
4575 } else if(entity->kind == ENTITY_VARIABLE) {
4576 entity->variable.alignment = alignment;
4577 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4578 entity->compound_member.alignment = alignment;
4583 type_modifiers_t type_modifiers = type->base.modifiers;
4584 if (modifiers & DM_TRANSPARENT_UNION)
4585 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4587 if (type->base.modifiers != type_modifiers) {
4588 type_t *copy = duplicate_type(type);
4589 copy->base.modifiers = type_modifiers;
4590 type = identify_new_type(copy);
4593 if (entity->kind == ENTITY_TYPEDEF) {
4594 entity->typedefe.type = type;
4595 entity->typedefe.modifiers = modifiers;
4597 entity->declaration.type = type;
4598 entity->declaration.modifiers = modifiers;
4602 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4604 construct_type_t *iter = construct_list;
4605 for (; iter != NULL; iter = iter->base.next) {
4606 switch (iter->kind) {
4607 case CONSTRUCT_INVALID:
4609 case CONSTRUCT_FUNCTION: {
4610 construct_function_type_t *function = &iter->function;
4611 type_t *function_type = function->function_type;
4613 function_type->function.return_type = type;
4615 type_t *skipped_return_type = skip_typeref(type);
4617 if (is_type_function(skipped_return_type)) {
4618 errorf(HERE, "function returning function is not allowed");
4619 } else if (is_type_array(skipped_return_type)) {
4620 errorf(HERE, "function returning array is not allowed");
4622 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4624 "type qualifiers in return type of function type are meaningless");
4628 /* The function type was constructed earlier. Freeing it here will
4629 * destroy other types. */
4630 type = typehash_insert(function_type);
4634 case CONSTRUCT_POINTER: {
4635 if (is_type_reference(skip_typeref(type)))
4636 errorf(HERE, "cannot declare a pointer to reference");
4638 parsed_pointer_t *pointer = &iter->pointer;
4639 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4643 case CONSTRUCT_REFERENCE:
4644 if (is_type_reference(skip_typeref(type)))
4645 errorf(HERE, "cannot declare a reference to reference");
4647 type = make_reference_type(type);
4650 case CONSTRUCT_ARRAY: {
4651 if (is_type_reference(skip_typeref(type)))
4652 errorf(HERE, "cannot declare an array of references");
4654 parsed_array_t *array = &iter->array;
4655 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4657 expression_t *size_expression = array->size;
4658 if (size_expression != NULL) {
4660 = create_implicit_cast(size_expression, type_size_t);
4663 array_type->base.qualifiers = array->type_qualifiers;
4664 array_type->array.element_type = type;
4665 array_type->array.is_static = array->is_static;
4666 array_type->array.is_variable = array->is_variable;
4667 array_type->array.size_expression = size_expression;
4669 if (size_expression != NULL) {
4670 if (is_constant_expression(size_expression)) {
4671 array_type->array.size_constant = true;
4672 array_type->array.size
4673 = fold_constant(size_expression);
4675 array_type->array.is_vla = true;
4679 type_t *skipped_type = skip_typeref(type);
4681 if (is_type_incomplete(skipped_type)) {
4682 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4683 } else if (is_type_function(skipped_type)) {
4684 errorf(HERE, "array of functions is not allowed");
4686 type = identify_new_type(array_type);
4690 internal_errorf(HERE, "invalid type construction found");
4696 static type_t *automatic_type_conversion(type_t *orig_type);
4698 static type_t *semantic_parameter(const source_position_t *pos,
4700 const declaration_specifiers_t *specifiers,
4703 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4704 * shall be adjusted to ``qualified pointer to type'',
4706 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4707 * type'' shall be adjusted to ``pointer to function
4708 * returning type'', as in 6.3.2.1. */
4709 type = automatic_type_conversion(type);
4711 if (specifiers->is_inline && is_type_valid(type)) {
4712 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4715 /* §6.9.1:6 The declarations in the declaration list shall contain
4716 * no storage-class specifier other than register and no
4717 * initializations. */
4718 if (specifiers->thread_local || (
4719 specifiers->storage_class != STORAGE_CLASS_NONE &&
4720 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4722 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4725 /* delay test for incomplete type, because we might have (void)
4726 * which is legal but incomplete... */
4731 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4732 declarator_flags_t flags)
4734 parse_declarator_env_t env;
4735 memset(&env, 0, sizeof(env));
4736 env.modifiers = specifiers->modifiers;
4738 construct_type_t *construct_type =
4739 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4741 construct_declarator_type(construct_type, specifiers->type);
4742 type_t *type = skip_typeref(orig_type);
4744 if (construct_type != NULL) {
4745 obstack_free(&temp_obst, construct_type);
4749 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4750 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4751 entity->base.symbol = env.symbol;
4752 entity->base.source_position = env.source_position;
4753 entity->typedefe.type = orig_type;
4755 if (anonymous_entity != NULL) {
4756 if (is_type_compound(type)) {
4757 assert(anonymous_entity->compound.alias == NULL);
4758 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4759 anonymous_entity->kind == ENTITY_UNION);
4760 anonymous_entity->compound.alias = entity;
4761 anonymous_entity = NULL;
4762 } else if (is_type_enum(type)) {
4763 assert(anonymous_entity->enume.alias == NULL);
4764 assert(anonymous_entity->kind == ENTITY_ENUM);
4765 anonymous_entity->enume.alias = entity;
4766 anonymous_entity = NULL;
4770 /* create a declaration type entity */
4771 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4772 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4774 if (env.symbol != NULL) {
4775 if (specifiers->is_inline && is_type_valid(type)) {
4776 errorf(&env.source_position,
4777 "compound member '%Y' declared 'inline'", env.symbol);
4780 if (specifiers->thread_local ||
4781 specifiers->storage_class != STORAGE_CLASS_NONE) {
4782 errorf(&env.source_position,
4783 "compound member '%Y' must have no storage class",
4787 } else if (flags & DECL_IS_PARAMETER) {
4788 orig_type = semantic_parameter(&env.source_position, orig_type,
4789 specifiers, env.symbol);
4791 entity = allocate_entity_zero(ENTITY_PARAMETER);
4792 } else if (is_type_function(type)) {
4793 entity = allocate_entity_zero(ENTITY_FUNCTION);
4795 entity->function.is_inline = specifiers->is_inline;
4796 entity->function.parameters = env.parameters;
4798 if (env.symbol != NULL) {
4799 if (specifiers->thread_local || (
4800 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4801 specifiers->storage_class != STORAGE_CLASS_NONE &&
4802 specifiers->storage_class != STORAGE_CLASS_STATIC
4804 errorf(&env.source_position,
4805 "invalid storage class for function '%Y'", env.symbol);
4809 entity = allocate_entity_zero(ENTITY_VARIABLE);
4811 entity->variable.get_property_sym = specifiers->get_property_sym;
4812 entity->variable.put_property_sym = specifiers->put_property_sym;
4814 entity->variable.thread_local = specifiers->thread_local;
4816 if (env.symbol != NULL) {
4817 if (specifiers->is_inline && is_type_valid(type)) {
4818 errorf(&env.source_position,
4819 "variable '%Y' declared 'inline'", env.symbol);
4822 bool invalid_storage_class = false;
4823 if (current_scope == file_scope) {
4824 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4825 specifiers->storage_class != STORAGE_CLASS_NONE &&
4826 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4827 invalid_storage_class = true;
4830 if (specifiers->thread_local &&
4831 specifiers->storage_class == STORAGE_CLASS_NONE) {
4832 invalid_storage_class = true;
4835 if (invalid_storage_class) {
4836 errorf(&env.source_position,
4837 "invalid storage class for variable '%Y'", env.symbol);
4842 if (env.symbol != NULL) {
4843 entity->base.symbol = env.symbol;
4844 entity->base.source_position = env.source_position;
4846 entity->base.source_position = specifiers->source_position;
4848 entity->base.namespc = NAMESPACE_NORMAL;
4849 entity->declaration.type = orig_type;
4850 entity->declaration.modifiers = env.modifiers;
4851 entity->declaration.deprecated_string = specifiers->deprecated_string;
4853 storage_class_t storage_class = specifiers->storage_class;
4854 entity->declaration.declared_storage_class = storage_class;
4856 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4857 storage_class = STORAGE_CLASS_AUTO;
4858 entity->declaration.storage_class = storage_class;
4861 parse_declaration_attributes(entity);
4866 static type_t *parse_abstract_declarator(type_t *base_type)
4868 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4870 type_t *result = construct_declarator_type(construct_type, base_type);
4871 if (construct_type != NULL) {
4872 obstack_free(&temp_obst, construct_type);
4879 * Check if the declaration of main is suspicious. main should be a
4880 * function with external linkage, returning int, taking either zero
4881 * arguments, two, or three arguments of appropriate types, ie.
4883 * int main([ int argc, char **argv [, char **env ] ]).
4885 * @param decl the declaration to check
4886 * @param type the function type of the declaration
4888 static void check_type_of_main(const entity_t *entity)
4890 const source_position_t *pos = &entity->base.source_position;
4891 if (entity->kind != ENTITY_FUNCTION) {
4892 warningf(pos, "'main' is not a function");
4896 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4897 warningf(pos, "'main' is normally a non-static function");
4900 type_t *type = skip_typeref(entity->declaration.type);
4901 assert(is_type_function(type));
4903 function_type_t *func_type = &type->function;
4904 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4905 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4906 func_type->return_type);
4908 const function_parameter_t *parm = func_type->parameters;
4910 type_t *const first_type = parm->type;
4911 if (!types_compatible(skip_typeref(first_type), type_int)) {
4913 "first argument of 'main' should be 'int', but is '%T'",
4918 type_t *const second_type = parm->type;
4919 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4920 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4924 type_t *const third_type = parm->type;
4925 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4926 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4930 goto warn_arg_count;
4934 warningf(pos, "'main' takes only zero, two or three arguments");
4940 * Check if a symbol is the equal to "main".
4942 static bool is_sym_main(const symbol_t *const sym)
4944 return strcmp(sym->string, "main") == 0;
4947 static void error_redefined_as_different_kind(const source_position_t *pos,
4948 const entity_t *old, entity_kind_t new_kind)
4950 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4951 get_entity_kind_name(old->kind), old->base.symbol,
4952 get_entity_kind_name(new_kind), &old->base.source_position);
4955 static bool is_error_entity(entity_t *const ent)
4957 if (is_declaration(ent)) {
4958 return is_type_valid(skip_typeref(ent->declaration.type));
4959 } else if (ent->kind == ENTITY_TYPEDEF) {
4960 return is_type_valid(skip_typeref(ent->typedefe.type));
4966 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4967 * for various problems that occur for multiple definitions
4969 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4971 const symbol_t *const symbol = entity->base.symbol;
4972 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4973 const source_position_t *pos = &entity->base.source_position;
4975 /* can happen in error cases */
4979 entity_t *const previous_entity = get_entity(symbol, namespc);
4980 /* pushing the same entity twice will break the stack structure */
4981 assert(previous_entity != entity);
4983 if (entity->kind == ENTITY_FUNCTION) {
4984 type_t *const orig_type = entity->declaration.type;
4985 type_t *const type = skip_typeref(orig_type);
4987 assert(is_type_function(type));
4988 if (type->function.unspecified_parameters &&
4989 warning.strict_prototypes &&
4990 previous_entity == NULL) {
4991 warningf(pos, "function declaration '%#T' is not a prototype",
4995 if (warning.main && current_scope == file_scope
4996 && is_sym_main(symbol)) {
4997 check_type_of_main(entity);
5001 if (is_declaration(entity) &&
5002 warning.nested_externs &&
5003 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5004 current_scope != file_scope) {
5005 warningf(pos, "nested extern declaration of '%#T'",
5006 entity->declaration.type, symbol);
5009 if (previous_entity != NULL) {
5010 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
5011 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5012 assert(previous_entity->kind == ENTITY_PARAMETER);
5014 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5015 entity->declaration.type, symbol,
5016 previous_entity->declaration.type, symbol,
5017 &previous_entity->base.source_position);
5021 if (previous_entity->base.parent_scope == current_scope) {
5022 if (previous_entity->kind != entity->kind) {
5023 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5024 error_redefined_as_different_kind(pos, previous_entity,
5029 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5030 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5031 symbol, &previous_entity->base.source_position);
5034 if (previous_entity->kind == ENTITY_TYPEDEF) {
5035 /* TODO: C++ allows this for exactly the same type */
5036 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5037 symbol, &previous_entity->base.source_position);
5041 /* at this point we should have only VARIABLES or FUNCTIONS */
5042 assert(is_declaration(previous_entity) && is_declaration(entity));
5044 declaration_t *const prev_decl = &previous_entity->declaration;
5045 declaration_t *const decl = &entity->declaration;
5047 /* can happen for K&R style declarations */
5048 if (prev_decl->type == NULL &&
5049 previous_entity->kind == ENTITY_PARAMETER &&
5050 entity->kind == ENTITY_PARAMETER) {
5051 prev_decl->type = decl->type;
5052 prev_decl->storage_class = decl->storage_class;
5053 prev_decl->declared_storage_class = decl->declared_storage_class;
5054 prev_decl->modifiers = decl->modifiers;
5055 prev_decl->deprecated_string = decl->deprecated_string;
5056 return previous_entity;
5059 type_t *const orig_type = decl->type;
5060 assert(orig_type != NULL);
5061 type_t *const type = skip_typeref(orig_type);
5062 type_t *const prev_type = skip_typeref(prev_decl->type);
5064 if (!types_compatible(type, prev_type)) {
5066 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5067 orig_type, symbol, prev_decl->type, symbol,
5068 &previous_entity->base.source_position);
5070 unsigned old_storage_class = prev_decl->storage_class;
5071 if (warning.redundant_decls &&
5074 !(prev_decl->modifiers & DM_USED) &&
5075 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5076 warningf(&previous_entity->base.source_position,
5077 "unnecessary static forward declaration for '%#T'",
5078 prev_decl->type, symbol);
5081 storage_class_t new_storage_class = decl->storage_class;
5083 /* pretend no storage class means extern for function
5084 * declarations (except if the previous declaration is neither
5085 * none nor extern) */
5086 if (entity->kind == ENTITY_FUNCTION) {
5087 /* the previous declaration could have unspecified parameters or
5088 * be a typedef, so use the new type */
5089 if (prev_type->function.unspecified_parameters || is_definition)
5090 prev_decl->type = type;
5092 switch (old_storage_class) {
5093 case STORAGE_CLASS_NONE:
5094 old_storage_class = STORAGE_CLASS_EXTERN;
5097 case STORAGE_CLASS_EXTERN:
5098 if (is_definition) {
5099 if (warning.missing_prototypes &&
5100 prev_type->function.unspecified_parameters &&
5101 !is_sym_main(symbol)) {
5102 warningf(pos, "no previous prototype for '%#T'",
5105 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5106 new_storage_class = STORAGE_CLASS_EXTERN;
5113 } else if (is_type_incomplete(prev_type)) {
5114 prev_decl->type = type;
5117 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5118 new_storage_class == STORAGE_CLASS_EXTERN) {
5119 warn_redundant_declaration:
5120 if (!is_definition &&
5121 warning.redundant_decls &&
5122 is_type_valid(prev_type) &&
5123 strcmp(previous_entity->base.source_position.input_name,
5124 "<builtin>") != 0) {
5126 "redundant declaration for '%Y' (declared %P)",
5127 symbol, &previous_entity->base.source_position);
5129 } else if (current_function == NULL) {
5130 if (old_storage_class != STORAGE_CLASS_STATIC &&
5131 new_storage_class == STORAGE_CLASS_STATIC) {
5133 "static declaration of '%Y' follows non-static declaration (declared %P)",
5134 symbol, &previous_entity->base.source_position);
5135 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5136 prev_decl->storage_class = STORAGE_CLASS_NONE;
5137 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5139 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5141 goto error_redeclaration;
5142 goto warn_redundant_declaration;
5144 } else if (is_type_valid(prev_type)) {
5145 if (old_storage_class == new_storage_class) {
5146 error_redeclaration:
5147 errorf(pos, "redeclaration of '%Y' (declared %P)",
5148 symbol, &previous_entity->base.source_position);
5151 "redeclaration of '%Y' with different linkage (declared %P)",
5152 symbol, &previous_entity->base.source_position);
5157 prev_decl->modifiers |= decl->modifiers;
5158 if (entity->kind == ENTITY_FUNCTION) {
5159 previous_entity->function.is_inline |= entity->function.is_inline;
5161 return previous_entity;
5164 if (warning.shadow) {
5165 warningf(pos, "%s '%Y' shadows %s (declared %P)",
5166 get_entity_kind_name(entity->kind), symbol,
5167 get_entity_kind_name(previous_entity->kind),
5168 &previous_entity->base.source_position);
5172 if (entity->kind == ENTITY_FUNCTION) {
5173 if (is_definition &&
5174 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5175 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5176 warningf(pos, "no previous prototype for '%#T'",
5177 entity->declaration.type, symbol);
5178 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5179 warningf(pos, "no previous declaration for '%#T'",
5180 entity->declaration.type, symbol);
5183 } else if (warning.missing_declarations &&
5184 entity->kind == ENTITY_VARIABLE &&
5185 current_scope == file_scope) {
5186 declaration_t *declaration = &entity->declaration;
5187 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5188 warningf(pos, "no previous declaration for '%#T'",
5189 declaration->type, symbol);
5194 assert(entity->base.parent_scope == NULL);
5195 assert(current_scope != NULL);
5197 entity->base.parent_scope = current_scope;
5198 entity->base.namespc = NAMESPACE_NORMAL;
5199 environment_push(entity);
5200 append_entity(current_scope, entity);
5205 static void parser_error_multiple_definition(entity_t *entity,
5206 const source_position_t *source_position)
5208 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5209 entity->base.symbol, &entity->base.source_position);
5212 static bool is_declaration_specifier(const token_t *token,
5213 bool only_specifiers_qualifiers)
5215 switch (token->type) {
5220 return is_typedef_symbol(token->v.symbol);
5222 case T___extension__:
5224 return !only_specifiers_qualifiers;
5231 static void parse_init_declarator_rest(entity_t *entity)
5233 assert(is_declaration(entity));
5234 declaration_t *const declaration = &entity->declaration;
5238 type_t *orig_type = declaration->type;
5239 type_t *type = skip_typeref(orig_type);
5241 if (entity->kind == ENTITY_VARIABLE
5242 && entity->variable.initializer != NULL) {
5243 parser_error_multiple_definition(entity, HERE);
5246 bool must_be_constant = false;
5247 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5248 entity->base.parent_scope == file_scope) {
5249 must_be_constant = true;
5252 if (is_type_function(type)) {
5253 errorf(&entity->base.source_position,
5254 "function '%#T' is initialized like a variable",
5255 orig_type, entity->base.symbol);
5256 orig_type = type_error_type;
5259 parse_initializer_env_t env;
5260 env.type = orig_type;
5261 env.must_be_constant = must_be_constant;
5262 env.entity = entity;
5263 current_init_decl = entity;
5265 initializer_t *initializer = parse_initializer(&env);
5266 current_init_decl = NULL;
5268 if (entity->kind == ENTITY_VARIABLE) {
5269 /* §6.7.5:22 array initializers for arrays with unknown size
5270 * determine the array type size */
5271 declaration->type = env.type;
5272 entity->variable.initializer = initializer;
5276 /* parse rest of a declaration without any declarator */
5277 static void parse_anonymous_declaration_rest(
5278 const declaration_specifiers_t *specifiers)
5281 anonymous_entity = NULL;
5283 if (warning.other) {
5284 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5285 specifiers->thread_local) {
5286 warningf(&specifiers->source_position,
5287 "useless storage class in empty declaration");
5290 type_t *type = specifiers->type;
5291 switch (type->kind) {
5292 case TYPE_COMPOUND_STRUCT:
5293 case TYPE_COMPOUND_UNION: {
5294 if (type->compound.compound->base.symbol == NULL) {
5295 warningf(&specifiers->source_position,
5296 "unnamed struct/union that defines no instances");
5305 warningf(&specifiers->source_position, "empty declaration");
5311 static void check_variable_type_complete(entity_t *ent)
5313 if (ent->kind != ENTITY_VARIABLE)
5316 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5317 * type for the object shall be complete [...] */
5318 declaration_t *decl = &ent->declaration;
5319 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
5320 decl->storage_class == STORAGE_CLASS_STATIC)
5323 type_t *const orig_type = decl->type;
5324 type_t *const type = skip_typeref(orig_type);
5325 if (!is_type_incomplete(type))
5328 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5329 * are given length one. */
5330 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5331 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5335 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5336 orig_type, ent->base.symbol);
5340 static void parse_declaration_rest(entity_t *ndeclaration,
5341 const declaration_specifiers_t *specifiers,
5342 parsed_declaration_func finished_declaration,
5343 declarator_flags_t flags)
5345 add_anchor_token(';');
5346 add_anchor_token(',');
5348 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5350 if (token.type == '=') {
5351 parse_init_declarator_rest(entity);
5352 } else if (entity->kind == ENTITY_VARIABLE) {
5353 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5354 * [...] where the extern specifier is explicitly used. */
5355 declaration_t *decl = &entity->declaration;
5356 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5357 type_t *type = decl->type;
5358 if (is_type_reference(skip_typeref(type))) {
5359 errorf(&entity->base.source_position,
5360 "reference '%#T' must be initialized",
5361 type, entity->base.symbol);
5366 check_variable_type_complete(entity);
5368 if (token.type != ',')
5372 add_anchor_token('=');
5373 ndeclaration = parse_declarator(specifiers, flags);
5374 rem_anchor_token('=');
5376 expect(';', end_error);
5379 anonymous_entity = NULL;
5380 rem_anchor_token(';');
5381 rem_anchor_token(',');
5384 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5386 symbol_t *symbol = entity->base.symbol;
5387 if (symbol == NULL) {
5388 errorf(HERE, "anonymous declaration not valid as function parameter");
5392 assert(entity->base.namespc == NAMESPACE_NORMAL);
5393 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5394 if (previous_entity == NULL
5395 || previous_entity->base.parent_scope != current_scope) {
5396 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5401 if (is_definition) {
5402 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5405 return record_entity(entity, false);
5408 static void parse_declaration(parsed_declaration_func finished_declaration,
5409 declarator_flags_t flags)
5411 declaration_specifiers_t specifiers;
5412 memset(&specifiers, 0, sizeof(specifiers));
5414 add_anchor_token(';');
5415 parse_declaration_specifiers(&specifiers);
5416 rem_anchor_token(';');
5418 if (token.type == ';') {
5419 parse_anonymous_declaration_rest(&specifiers);
5421 entity_t *entity = parse_declarator(&specifiers, flags);
5422 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5426 static type_t *get_default_promoted_type(type_t *orig_type)
5428 type_t *result = orig_type;
5430 type_t *type = skip_typeref(orig_type);
5431 if (is_type_integer(type)) {
5432 result = promote_integer(type);
5433 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
5434 result = type_double;
5440 static void parse_kr_declaration_list(entity_t *entity)
5442 if (entity->kind != ENTITY_FUNCTION)
5445 type_t *type = skip_typeref(entity->declaration.type);
5446 assert(is_type_function(type));
5447 if (!type->function.kr_style_parameters)
5451 add_anchor_token('{');
5453 /* push function parameters */
5454 size_t const top = environment_top();
5455 scope_t *old_scope = scope_push(&entity->function.parameters);
5457 entity_t *parameter = entity->function.parameters.entities;
5458 for ( ; parameter != NULL; parameter = parameter->base.next) {
5459 assert(parameter->base.parent_scope == NULL);
5460 parameter->base.parent_scope = current_scope;
5461 environment_push(parameter);
5464 /* parse declaration list */
5466 switch (token.type) {
5468 case T___extension__:
5469 /* This covers symbols, which are no type, too, and results in
5470 * better error messages. The typical cases are misspelled type
5471 * names and missing includes. */
5473 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5481 /* pop function parameters */
5482 assert(current_scope == &entity->function.parameters);
5483 scope_pop(old_scope);
5484 environment_pop_to(top);
5486 /* update function type */
5487 type_t *new_type = duplicate_type(type);
5489 function_parameter_t *parameters = NULL;
5490 function_parameter_t *last_parameter = NULL;
5492 parameter = entity->function.parameters.entities;
5493 for (; parameter != NULL; parameter = parameter->base.next) {
5494 if (parameter->kind != ENTITY_PARAMETER)
5497 type_t *parameter_type = parameter->declaration.type;
5498 if (parameter_type == NULL) {
5500 errorf(HERE, "no type specified for function parameter '%Y'",
5501 parameter->base.symbol);
5503 if (warning.implicit_int) {
5504 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5505 parameter->base.symbol);
5507 parameter_type = type_int;
5508 parameter->declaration.type = parameter_type;
5512 semantic_parameter_incomplete(parameter);
5513 parameter_type = parameter->declaration.type;
5516 * we need the default promoted types for the function type
5518 parameter_type = get_default_promoted_type(parameter_type);
5520 function_parameter_t *function_parameter
5521 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5522 memset(function_parameter, 0, sizeof(function_parameter[0]));
5524 function_parameter->type = parameter_type;
5525 if (last_parameter != NULL) {
5526 last_parameter->next = function_parameter;
5528 parameters = function_parameter;
5530 last_parameter = function_parameter;
5533 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
5535 new_type->function.parameters = parameters;
5536 new_type->function.unspecified_parameters = true;
5538 new_type = identify_new_type(new_type);
5540 entity->declaration.type = new_type;
5542 rem_anchor_token('{');
5545 static bool first_err = true;
5548 * When called with first_err set, prints the name of the current function,
5551 static void print_in_function(void)
5555 diagnosticf("%s: In function '%Y':\n",
5556 current_function->base.base.source_position.input_name,
5557 current_function->base.base.symbol);
5562 * Check if all labels are defined in the current function.
5563 * Check if all labels are used in the current function.
5565 static void check_labels(void)
5567 for (const goto_statement_t *goto_statement = goto_first;
5568 goto_statement != NULL;
5569 goto_statement = goto_statement->next) {
5570 /* skip computed gotos */
5571 if (goto_statement->expression != NULL)
5574 label_t *label = goto_statement->label;
5577 if (label->base.source_position.input_name == NULL) {
5578 print_in_function();
5579 errorf(&goto_statement->base.source_position,
5580 "label '%Y' used but not defined", label->base.symbol);
5584 if (warning.unused_label) {
5585 for (const label_statement_t *label_statement = label_first;
5586 label_statement != NULL;
5587 label_statement = label_statement->next) {
5588 label_t *label = label_statement->label;
5590 if (! label->used) {
5591 print_in_function();
5592 warningf(&label_statement->base.source_position,
5593 "label '%Y' defined but not used", label->base.symbol);
5599 static void warn_unused_entity(entity_t *entity, entity_t *last)
5601 entity_t const *const end = last != NULL ? last->base.next : NULL;
5602 for (; entity != end; entity = entity->base.next) {
5603 if (!is_declaration(entity))
5606 declaration_t *declaration = &entity->declaration;
5607 if (declaration->implicit)
5610 if (!declaration->used) {
5611 print_in_function();
5612 const char *what = get_entity_kind_name(entity->kind);
5613 warningf(&entity->base.source_position, "%s '%Y' is unused",
5614 what, entity->base.symbol);
5615 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5616 print_in_function();
5617 const char *what = get_entity_kind_name(entity->kind);
5618 warningf(&entity->base.source_position, "%s '%Y' is never read",
5619 what, entity->base.symbol);
5624 static void check_unused_variables(statement_t *const stmt, void *const env)
5628 switch (stmt->kind) {
5629 case STATEMENT_DECLARATION: {
5630 declaration_statement_t const *const decls = &stmt->declaration;
5631 warn_unused_entity(decls->declarations_begin,
5632 decls->declarations_end);
5637 warn_unused_entity(stmt->fors.scope.entities, NULL);
5646 * Check declarations of current_function for unused entities.
5648 static void check_declarations(void)
5650 if (warning.unused_parameter) {
5651 const scope_t *scope = ¤t_function->parameters;
5653 /* do not issue unused warnings for main */
5654 if (!is_sym_main(current_function->base.base.symbol)) {
5655 warn_unused_entity(scope->entities, NULL);
5658 if (warning.unused_variable) {
5659 walk_statements(current_function->statement, check_unused_variables,
5664 static int determine_truth(expression_t const* const cond)
5667 !is_constant_expression(cond) ? 0 :
5668 fold_constant(cond) != 0 ? 1 :
5672 static void check_reachable(statement_t *);
5673 static bool reaches_end;
5675 static bool expression_returns(expression_t const *const expr)
5677 switch (expr->kind) {
5679 expression_t const *const func = expr->call.function;
5680 if (func->kind == EXPR_REFERENCE) {
5681 entity_t *entity = func->reference.entity;
5682 if (entity->kind == ENTITY_FUNCTION
5683 && entity->declaration.modifiers & DM_NORETURN)
5687 if (!expression_returns(func))
5690 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5691 if (!expression_returns(arg->expression))
5698 case EXPR_REFERENCE:
5699 case EXPR_REFERENCE_ENUM_VALUE:
5701 case EXPR_CHARACTER_CONSTANT:
5702 case EXPR_WIDE_CHARACTER_CONSTANT:
5703 case EXPR_STRING_LITERAL:
5704 case EXPR_WIDE_STRING_LITERAL:
5705 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5706 case EXPR_LABEL_ADDRESS:
5707 case EXPR_CLASSIFY_TYPE:
5708 case EXPR_SIZEOF: // TODO handle obscure VLA case
5711 case EXPR_BUILTIN_CONSTANT_P:
5712 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5717 case EXPR_STATEMENT: {
5718 bool old_reaches_end = reaches_end;
5719 reaches_end = false;
5720 check_reachable(expr->statement.statement);
5721 bool returns = reaches_end;
5722 reaches_end = old_reaches_end;
5726 case EXPR_CONDITIONAL:
5727 // TODO handle constant expression
5729 if (!expression_returns(expr->conditional.condition))
5732 if (expr->conditional.true_expression != NULL
5733 && expression_returns(expr->conditional.true_expression))
5736 return expression_returns(expr->conditional.false_expression);
5739 return expression_returns(expr->select.compound);
5741 case EXPR_ARRAY_ACCESS:
5743 expression_returns(expr->array_access.array_ref) &&
5744 expression_returns(expr->array_access.index);
5747 return expression_returns(expr->va_starte.ap);
5750 return expression_returns(expr->va_arge.ap);
5752 EXPR_UNARY_CASES_MANDATORY
5753 return expression_returns(expr->unary.value);
5755 case EXPR_UNARY_THROW:
5759 // TODO handle constant lhs of && and ||
5761 expression_returns(expr->binary.left) &&
5762 expression_returns(expr->binary.right);
5768 panic("unhandled expression");
5771 static bool initializer_returns(initializer_t const *const init)
5773 switch (init->kind) {
5774 case INITIALIZER_VALUE:
5775 return expression_returns(init->value.value);
5777 case INITIALIZER_LIST: {
5778 initializer_t * const* i = init->list.initializers;
5779 initializer_t * const* const end = i + init->list.len;
5780 bool returns = true;
5781 for (; i != end; ++i) {
5782 if (!initializer_returns(*i))
5788 case INITIALIZER_STRING:
5789 case INITIALIZER_WIDE_STRING:
5790 case INITIALIZER_DESIGNATOR: // designators have no payload
5793 panic("unhandled initializer");
5796 static bool noreturn_candidate;
5798 static void check_reachable(statement_t *const stmt)
5800 if (stmt->base.reachable)
5802 if (stmt->kind != STATEMENT_DO_WHILE)
5803 stmt->base.reachable = true;
5805 statement_t *last = stmt;
5807 switch (stmt->kind) {
5808 case STATEMENT_INVALID:
5809 case STATEMENT_EMPTY:
5811 next = stmt->base.next;
5814 case STATEMENT_DECLARATION: {
5815 declaration_statement_t const *const decl = &stmt->declaration;
5816 entity_t const * ent = decl->declarations_begin;
5817 entity_t const *const last = decl->declarations_end;
5819 for (;; ent = ent->base.next) {
5820 if (ent->kind == ENTITY_VARIABLE &&
5821 ent->variable.initializer != NULL &&
5822 !initializer_returns(ent->variable.initializer)) {
5829 next = stmt->base.next;
5833 case STATEMENT_COMPOUND:
5834 next = stmt->compound.statements;
5836 next = stmt->base.next;
5839 case STATEMENT_RETURN: {
5840 expression_t const *const val = stmt->returns.value;
5841 if (val == NULL || expression_returns(val))
5842 noreturn_candidate = false;
5846 case STATEMENT_IF: {
5847 if_statement_t const *const ifs = &stmt->ifs;
5848 expression_t const *const cond = ifs->condition;
5850 if (!expression_returns(cond))
5853 int const val = determine_truth(cond);
5856 check_reachable(ifs->true_statement);
5861 if (ifs->false_statement != NULL) {
5862 check_reachable(ifs->false_statement);
5866 next = stmt->base.next;
5870 case STATEMENT_SWITCH: {
5871 switch_statement_t const *const switchs = &stmt->switchs;
5872 expression_t const *const expr = switchs->expression;
5874 if (!expression_returns(expr))
5877 if (is_constant_expression(expr)) {
5878 long const val = fold_constant(expr);
5879 case_label_statement_t * defaults = NULL;
5880 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5881 if (i->expression == NULL) {
5886 if (i->first_case <= val && val <= i->last_case) {
5887 check_reachable((statement_t*)i);
5892 if (defaults != NULL) {
5893 check_reachable((statement_t*)defaults);
5897 bool has_default = false;
5898 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5899 if (i->expression == NULL)
5902 check_reachable((statement_t*)i);
5909 next = stmt->base.next;
5913 case STATEMENT_EXPRESSION: {
5914 /* Check for noreturn function call */
5915 expression_t const *const expr = stmt->expression.expression;
5916 if (!expression_returns(expr))
5919 next = stmt->base.next;
5923 case STATEMENT_CONTINUE: {
5924 statement_t *parent = stmt;
5926 parent = parent->base.parent;
5927 if (parent == NULL) /* continue not within loop */
5931 switch (parent->kind) {
5932 case STATEMENT_WHILE: goto continue_while;
5933 case STATEMENT_DO_WHILE: goto continue_do_while;
5934 case STATEMENT_FOR: goto continue_for;
5941 case STATEMENT_BREAK: {
5942 statement_t *parent = stmt;
5944 parent = parent->base.parent;
5945 if (parent == NULL) /* break not within loop/switch */
5948 switch (parent->kind) {
5949 case STATEMENT_SWITCH:
5950 case STATEMENT_WHILE:
5951 case STATEMENT_DO_WHILE:
5954 next = parent->base.next;
5955 goto found_break_parent;
5964 case STATEMENT_GOTO:
5965 if (stmt->gotos.expression) {
5966 if (!expression_returns(stmt->gotos.expression))
5969 statement_t *parent = stmt->base.parent;
5970 if (parent == NULL) /* top level goto */
5974 next = stmt->gotos.label->statement;
5975 if (next == NULL) /* missing label */
5980 case STATEMENT_LABEL:
5981 next = stmt->label.statement;
5984 case STATEMENT_CASE_LABEL:
5985 next = stmt->case_label.statement;
5988 case STATEMENT_WHILE: {
5989 while_statement_t const *const whiles = &stmt->whiles;
5990 expression_t const *const cond = whiles->condition;
5992 if (!expression_returns(cond))
5995 int const val = determine_truth(cond);
5998 check_reachable(whiles->body);
6003 next = stmt->base.next;
6007 case STATEMENT_DO_WHILE:
6008 next = stmt->do_while.body;
6011 case STATEMENT_FOR: {
6012 for_statement_t *const fors = &stmt->fors;
6014 if (fors->condition_reachable)
6016 fors->condition_reachable = true;
6018 expression_t const *const cond = fors->condition;
6023 } else if (expression_returns(cond)) {
6024 val = determine_truth(cond);
6030 check_reachable(fors->body);
6035 next = stmt->base.next;
6039 case STATEMENT_MS_TRY: {
6040 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6041 check_reachable(ms_try->try_statement);
6042 next = ms_try->final_statement;
6046 case STATEMENT_LEAVE: {
6047 statement_t *parent = stmt;
6049 parent = parent->base.parent;
6050 if (parent == NULL) /* __leave not within __try */
6053 if (parent->kind == STATEMENT_MS_TRY) {
6055 next = parent->ms_try.final_statement;
6063 panic("invalid statement kind");
6066 while (next == NULL) {
6067 next = last->base.parent;
6069 noreturn_candidate = false;
6071 type_t *const type = skip_typeref(current_function->base.type);
6072 assert(is_type_function(type));
6073 type_t *const ret = skip_typeref(type->function.return_type);
6074 if (warning.return_type &&
6075 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6076 is_type_valid(ret) &&
6077 !is_sym_main(current_function->base.base.symbol)) {
6078 warningf(&stmt->base.source_position,
6079 "control reaches end of non-void function");
6084 switch (next->kind) {
6085 case STATEMENT_INVALID:
6086 case STATEMENT_EMPTY:
6087 case STATEMENT_DECLARATION:
6088 case STATEMENT_EXPRESSION:
6090 case STATEMENT_RETURN:
6091 case STATEMENT_CONTINUE:
6092 case STATEMENT_BREAK:
6093 case STATEMENT_GOTO:
6094 case STATEMENT_LEAVE:
6095 panic("invalid control flow in function");
6097 case STATEMENT_COMPOUND:
6098 if (next->compound.stmt_expr) {
6104 case STATEMENT_SWITCH:
6105 case STATEMENT_LABEL:
6106 case STATEMENT_CASE_LABEL:
6108 next = next->base.next;
6111 case STATEMENT_WHILE: {
6113 if (next->base.reachable)
6115 next->base.reachable = true;
6117 while_statement_t const *const whiles = &next->whiles;
6118 expression_t const *const cond = whiles->condition;
6120 if (!expression_returns(cond))
6123 int const val = determine_truth(cond);
6126 check_reachable(whiles->body);
6132 next = next->base.next;
6136 case STATEMENT_DO_WHILE: {
6138 if (next->base.reachable)
6140 next->base.reachable = true;
6142 do_while_statement_t const *const dw = &next->do_while;
6143 expression_t const *const cond = dw->condition;
6145 if (!expression_returns(cond))
6148 int const val = determine_truth(cond);
6151 check_reachable(dw->body);
6157 next = next->base.next;
6161 case STATEMENT_FOR: {
6163 for_statement_t *const fors = &next->fors;
6165 fors->step_reachable = true;
6167 if (fors->condition_reachable)
6169 fors->condition_reachable = true;
6171 expression_t const *const cond = fors->condition;
6176 } else if (expression_returns(cond)) {
6177 val = determine_truth(cond);
6183 check_reachable(fors->body);
6189 next = next->base.next;
6193 case STATEMENT_MS_TRY:
6195 next = next->ms_try.final_statement;
6200 check_reachable(next);
6203 static void check_unreachable(statement_t* const stmt, void *const env)
6207 switch (stmt->kind) {
6208 case STATEMENT_DO_WHILE:
6209 if (!stmt->base.reachable) {
6210 expression_t const *const cond = stmt->do_while.condition;
6211 if (determine_truth(cond) >= 0) {
6212 warningf(&cond->base.source_position,
6213 "condition of do-while-loop is unreachable");
6218 case STATEMENT_FOR: {
6219 for_statement_t const* const fors = &stmt->fors;
6221 // if init and step are unreachable, cond is unreachable, too
6222 if (!stmt->base.reachable && !fors->step_reachable) {
6223 warningf(&stmt->base.source_position, "statement is unreachable");
6225 if (!stmt->base.reachable && fors->initialisation != NULL) {
6226 warningf(&fors->initialisation->base.source_position,
6227 "initialisation of for-statement is unreachable");
6230 if (!fors->condition_reachable && fors->condition != NULL) {
6231 warningf(&fors->condition->base.source_position,
6232 "condition of for-statement is unreachable");
6235 if (!fors->step_reachable && fors->step != NULL) {
6236 warningf(&fors->step->base.source_position,
6237 "step of for-statement is unreachable");
6243 case STATEMENT_COMPOUND:
6244 if (stmt->compound.statements != NULL)
6246 goto warn_unreachable;
6248 case STATEMENT_DECLARATION: {
6249 /* Only warn if there is at least one declarator with an initializer.
6250 * This typically occurs in switch statements. */
6251 declaration_statement_t const *const decl = &stmt->declaration;
6252 entity_t const * ent = decl->declarations_begin;
6253 entity_t const *const last = decl->declarations_end;
6255 for (;; ent = ent->base.next) {
6256 if (ent->kind == ENTITY_VARIABLE &&
6257 ent->variable.initializer != NULL) {
6258 goto warn_unreachable;
6268 if (!stmt->base.reachable)
6269 warningf(&stmt->base.source_position, "statement is unreachable");
6274 static void parse_external_declaration(void)
6276 /* function-definitions and declarations both start with declaration
6278 declaration_specifiers_t specifiers;
6279 memset(&specifiers, 0, sizeof(specifiers));
6281 add_anchor_token(';');
6282 parse_declaration_specifiers(&specifiers);
6283 rem_anchor_token(';');
6285 /* must be a declaration */
6286 if (token.type == ';') {
6287 parse_anonymous_declaration_rest(&specifiers);
6291 add_anchor_token(',');
6292 add_anchor_token('=');
6293 add_anchor_token(';');
6294 add_anchor_token('{');
6296 /* declarator is common to both function-definitions and declarations */
6297 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6299 rem_anchor_token('{');
6300 rem_anchor_token(';');
6301 rem_anchor_token('=');
6302 rem_anchor_token(',');
6304 /* must be a declaration */
6305 switch (token.type) {
6309 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6314 /* must be a function definition */
6315 parse_kr_declaration_list(ndeclaration);
6317 if (token.type != '{') {
6318 parse_error_expected("while parsing function definition", '{', NULL);
6319 eat_until_matching_token(';');
6323 assert(is_declaration(ndeclaration));
6324 type_t *const orig_type = ndeclaration->declaration.type;
6325 type_t * type = skip_typeref(orig_type);
6327 if (!is_type_function(type)) {
6328 if (is_type_valid(type)) {
6329 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6330 type, ndeclaration->base.symbol);
6334 } else if (is_typeref(orig_type)) {
6336 errorf(&ndeclaration->base.source_position,
6337 "type of function definition '%#T' is a typedef",
6338 orig_type, ndeclaration->base.symbol);
6341 if (warning.aggregate_return &&
6342 is_type_compound(skip_typeref(type->function.return_type))) {
6343 warningf(HERE, "function '%Y' returns an aggregate",
6344 ndeclaration->base.symbol);
6346 if (warning.traditional && !type->function.unspecified_parameters) {
6347 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6348 ndeclaration->base.symbol);
6350 if (warning.old_style_definition && type->function.unspecified_parameters) {
6351 warningf(HERE, "old-style function definition '%Y'",
6352 ndeclaration->base.symbol);
6355 /* §6.7.5.3:14 a function definition with () means no
6356 * parameters (and not unspecified parameters) */
6357 if (type->function.unspecified_parameters &&
6358 type->function.parameters == NULL &&
6359 !type->function.kr_style_parameters) {
6360 type_t *copy = duplicate_type(type);
6361 copy->function.unspecified_parameters = false;
6362 type = identify_new_type(copy);
6364 ndeclaration->declaration.type = type;
6367 entity_t *const entity = record_entity(ndeclaration, true);
6368 assert(entity->kind == ENTITY_FUNCTION);
6369 assert(ndeclaration->kind == ENTITY_FUNCTION);
6371 function_t *function = &entity->function;
6372 if (ndeclaration != entity) {
6373 function->parameters = ndeclaration->function.parameters;
6375 assert(is_declaration(entity));
6376 type = skip_typeref(entity->declaration.type);
6378 /* push function parameters and switch scope */
6379 size_t const top = environment_top();
6380 scope_t *old_scope = scope_push(&function->parameters);
6382 entity_t *parameter = function->parameters.entities;
6383 for (; parameter != NULL; parameter = parameter->base.next) {
6384 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6385 parameter->base.parent_scope = current_scope;
6387 assert(parameter->base.parent_scope == NULL
6388 || parameter->base.parent_scope == current_scope);
6389 parameter->base.parent_scope = current_scope;
6390 if (parameter->base.symbol == NULL) {
6391 errorf(¶meter->base.source_position, "parameter name omitted");
6394 environment_push(parameter);
6397 if (function->statement != NULL) {
6398 parser_error_multiple_definition(entity, HERE);
6401 /* parse function body */
6402 int label_stack_top = label_top();
6403 function_t *old_current_function = current_function;
6404 current_function = function;
6405 current_parent = NULL;
6408 goto_anchor = &goto_first;
6410 label_anchor = &label_first;
6412 statement_t *const body = parse_compound_statement(false);
6413 function->statement = body;
6416 check_declarations();
6417 if (warning.return_type ||
6418 warning.unreachable_code ||
6419 (warning.missing_noreturn
6420 && !(function->base.modifiers & DM_NORETURN))) {
6421 noreturn_candidate = true;
6422 check_reachable(body);
6423 if (warning.unreachable_code)
6424 walk_statements(body, check_unreachable, NULL);
6425 if (warning.missing_noreturn &&
6426 noreturn_candidate &&
6427 !(function->base.modifiers & DM_NORETURN)) {
6428 warningf(&body->base.source_position,
6429 "function '%#T' is candidate for attribute 'noreturn'",
6430 type, entity->base.symbol);
6434 assert(current_parent == NULL);
6435 assert(current_function == function);
6436 current_function = old_current_function;
6437 label_pop_to(label_stack_top);
6440 assert(current_scope == &function->parameters);
6441 scope_pop(old_scope);
6442 environment_pop_to(top);
6445 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6446 source_position_t *source_position,
6447 const symbol_t *symbol)
6449 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6451 type->bitfield.base_type = base_type;
6452 type->bitfield.size_expression = size;
6455 type_t *skipped_type = skip_typeref(base_type);
6456 if (!is_type_integer(skipped_type)) {
6457 errorf(HERE, "bitfield base type '%T' is not an integer type",
6461 bit_size = skipped_type->base.size * 8;
6464 if (is_constant_expression(size)) {
6465 long v = fold_constant(size);
6468 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6469 } else if (v == 0) {
6470 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6471 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6472 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6474 type->bitfield.bit_size = v;
6481 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6483 entity_t *iter = compound->members.entities;
6484 for (; iter != NULL; iter = iter->base.next) {
6485 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6488 if (iter->base.symbol == symbol) {
6490 } else if (iter->base.symbol == NULL) {
6491 type_t *type = skip_typeref(iter->declaration.type);
6492 if (is_type_compound(type)) {
6494 = find_compound_entry(type->compound.compound, symbol);
6505 static void parse_compound_declarators(compound_t *compound,
6506 const declaration_specifiers_t *specifiers)
6511 if (token.type == ':') {
6512 source_position_t source_position = *HERE;
6515 type_t *base_type = specifiers->type;
6516 expression_t *size = parse_constant_expression();
6518 type_t *type = make_bitfield_type(base_type, size,
6519 &source_position, sym_anonymous);
6521 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6522 entity->base.namespc = NAMESPACE_NORMAL;
6523 entity->base.source_position = source_position;
6524 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6525 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6526 entity->declaration.modifiers = specifiers->modifiers;
6527 entity->declaration.type = type;
6528 append_entity(&compound->members, entity);
6530 entity = parse_declarator(specifiers,
6531 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6532 if (entity->kind == ENTITY_TYPEDEF) {
6533 errorf(&entity->base.source_position,
6534 "typedef not allowed as compound member");
6536 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6538 /* make sure we don't define a symbol multiple times */
6539 symbol_t *symbol = entity->base.symbol;
6540 if (symbol != NULL) {
6541 entity_t *prev = find_compound_entry(compound, symbol);
6543 errorf(&entity->base.source_position,
6544 "multiple declarations of symbol '%Y' (declared %P)",
6545 symbol, &prev->base.source_position);
6549 if (token.type == ':') {
6550 source_position_t source_position = *HERE;
6552 expression_t *size = parse_constant_expression();
6554 type_t *type = entity->declaration.type;
6555 type_t *bitfield_type = make_bitfield_type(type, size,
6556 &source_position, entity->base.symbol);
6557 entity->declaration.type = bitfield_type;
6559 type_t *orig_type = entity->declaration.type;
6560 type_t *type = skip_typeref(orig_type);
6561 if (is_type_function(type)) {
6562 errorf(&entity->base.source_position,
6563 "compound member '%Y' must not have function type '%T'",
6564 entity->base.symbol, orig_type);
6565 } else if (is_type_incomplete(type)) {
6566 /* §6.7.2.1:16 flexible array member */
6567 if (!is_type_array(type) ||
6568 token.type != ';' ||
6569 look_ahead(1)->type != '}') {
6570 errorf(&entity->base.source_position,
6571 "compound member '%Y' has incomplete type '%T'",
6572 entity->base.symbol, orig_type);
6577 append_entity(&compound->members, entity);
6581 if (token.type != ',')
6585 expect(';', end_error);
6588 anonymous_entity = NULL;
6591 static void parse_compound_type_entries(compound_t *compound)
6594 add_anchor_token('}');
6596 while (token.type != '}') {
6597 if (token.type == T_EOF) {
6598 errorf(HERE, "EOF while parsing struct");
6601 declaration_specifiers_t specifiers;
6602 memset(&specifiers, 0, sizeof(specifiers));
6603 parse_declaration_specifiers(&specifiers);
6605 parse_compound_declarators(compound, &specifiers);
6607 rem_anchor_token('}');
6611 compound->complete = true;
6614 static type_t *parse_typename(void)
6616 declaration_specifiers_t specifiers;
6617 memset(&specifiers, 0, sizeof(specifiers));
6618 parse_declaration_specifiers(&specifiers);
6619 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6620 specifiers.thread_local) {
6621 /* TODO: improve error message, user does probably not know what a
6622 * storage class is...
6624 errorf(HERE, "typename may not have a storage class");
6627 type_t *result = parse_abstract_declarator(specifiers.type);
6635 typedef expression_t* (*parse_expression_function)(void);
6636 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6638 typedef struct expression_parser_function_t expression_parser_function_t;
6639 struct expression_parser_function_t {
6640 parse_expression_function parser;
6641 precedence_t infix_precedence;
6642 parse_expression_infix_function infix_parser;
6645 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6648 * Prints an error message if an expression was expected but not read
6650 static expression_t *expected_expression_error(void)
6652 /* skip the error message if the error token was read */
6653 if (token.type != T_ERROR) {
6654 errorf(HERE, "expected expression, got token %K", &token);
6658 return create_invalid_expression();
6662 * Parse a string constant.
6664 static expression_t *parse_string_const(void)
6667 if (token.type == T_STRING_LITERAL) {
6668 string_t res = token.v.string;
6670 while (token.type == T_STRING_LITERAL) {
6671 res = concat_strings(&res, &token.v.string);
6674 if (token.type != T_WIDE_STRING_LITERAL) {
6675 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6676 /* note: that we use type_char_ptr here, which is already the
6677 * automatic converted type. revert_automatic_type_conversion
6678 * will construct the array type */
6679 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6680 cnst->string.value = res;
6684 wres = concat_string_wide_string(&res, &token.v.wide_string);
6686 wres = token.v.wide_string;
6691 switch (token.type) {
6692 case T_WIDE_STRING_LITERAL:
6693 wres = concat_wide_strings(&wres, &token.v.wide_string);
6696 case T_STRING_LITERAL:
6697 wres = concat_wide_string_string(&wres, &token.v.string);
6701 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6702 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6703 cnst->wide_string.value = wres;
6712 * Parse a boolean constant.
6714 static expression_t *parse_bool_const(bool value)
6716 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6717 cnst->base.type = type_bool;
6718 cnst->conste.v.int_value = value;
6726 * Parse an integer constant.
6728 static expression_t *parse_int_const(void)
6730 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6731 cnst->base.type = token.datatype;
6732 cnst->conste.v.int_value = token.v.intvalue;
6740 * Parse a character constant.
6742 static expression_t *parse_character_constant(void)
6744 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6745 cnst->base.type = token.datatype;
6746 cnst->conste.v.character = token.v.string;
6748 if (cnst->conste.v.character.size != 1) {
6750 errorf(HERE, "more than 1 character in character constant");
6751 } else if (warning.multichar) {
6752 warningf(HERE, "multi-character character constant");
6761 * Parse a wide character constant.
6763 static expression_t *parse_wide_character_constant(void)
6765 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6766 cnst->base.type = token.datatype;
6767 cnst->conste.v.wide_character = token.v.wide_string;
6769 if (cnst->conste.v.wide_character.size != 1) {
6771 errorf(HERE, "more than 1 character in character constant");
6772 } else if (warning.multichar) {
6773 warningf(HERE, "multi-character character constant");
6782 * Parse a float constant.
6784 static expression_t *parse_float_const(void)
6786 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6787 cnst->base.type = token.datatype;
6788 cnst->conste.v.float_value = token.v.floatvalue;
6795 static entity_t *create_implicit_function(symbol_t *symbol,
6796 const source_position_t *source_position)
6798 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6799 ntype->function.return_type = type_int;
6800 ntype->function.unspecified_parameters = true;
6801 ntype->function.linkage = LINKAGE_C;
6802 type_t *type = identify_new_type(ntype);
6804 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6805 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6806 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6807 entity->declaration.type = type;
6808 entity->declaration.implicit = true;
6809 entity->base.symbol = symbol;
6810 entity->base.source_position = *source_position;
6812 bool strict_prototypes_old = warning.strict_prototypes;
6813 warning.strict_prototypes = false;
6814 record_entity(entity, false);
6815 warning.strict_prototypes = strict_prototypes_old;
6821 * Creates a return_type (func)(argument_type) function type if not
6824 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6825 type_t *argument_type2)
6827 function_parameter_t *parameter2
6828 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6829 memset(parameter2, 0, sizeof(parameter2[0]));
6830 parameter2->type = argument_type2;
6832 function_parameter_t *parameter1
6833 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6834 memset(parameter1, 0, sizeof(parameter1[0]));
6835 parameter1->type = argument_type1;
6836 parameter1->next = parameter2;
6838 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6839 type->function.return_type = return_type;
6840 type->function.parameters = parameter1;
6842 return identify_new_type(type);
6846 * Creates a return_type (func)(argument_type) function type if not
6849 * @param return_type the return type
6850 * @param argument_type the argument type
6852 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6854 function_parameter_t *parameter
6855 = obstack_alloc(type_obst, sizeof(parameter[0]));
6856 memset(parameter, 0, sizeof(parameter[0]));
6857 parameter->type = argument_type;
6859 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6860 type->function.return_type = return_type;
6861 type->function.parameters = parameter;
6863 return identify_new_type(type);
6866 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6868 type_t *res = make_function_1_type(return_type, argument_type);
6869 res->function.variadic = 1;
6874 * Creates a return_type (func)(void) function type if not
6877 * @param return_type the return type
6879 static type_t *make_function_0_type(type_t *return_type)
6881 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6882 type->function.return_type = return_type;
6883 type->function.parameters = NULL;
6885 return identify_new_type(type);
6889 * Creates a NO_RETURN return_type (func)(void) function type if not
6892 * @param return_type the return type
6894 static type_t *make_function_0_type_noreturn(type_t *return_type)
6896 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6897 type->function.return_type = return_type;
6898 type->function.parameters = NULL;
6899 type->function.base.modifiers |= DM_NORETURN;
6902 return identify_new_type(type);
6906 * Performs automatic type cast as described in §6.3.2.1.
6908 * @param orig_type the original type
6910 static type_t *automatic_type_conversion(type_t *orig_type)
6912 type_t *type = skip_typeref(orig_type);
6913 if (is_type_array(type)) {
6914 array_type_t *array_type = &type->array;
6915 type_t *element_type = array_type->element_type;
6916 unsigned qualifiers = array_type->base.qualifiers;
6918 return make_pointer_type(element_type, qualifiers);
6921 if (is_type_function(type)) {
6922 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6929 * reverts the automatic casts of array to pointer types and function
6930 * to function-pointer types as defined §6.3.2.1
6932 type_t *revert_automatic_type_conversion(const expression_t *expression)
6934 switch (expression->kind) {
6935 case EXPR_REFERENCE: {
6936 entity_t *entity = expression->reference.entity;
6937 if (is_declaration(entity)) {
6938 return entity->declaration.type;
6939 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6940 return entity->enum_value.enum_type;
6942 panic("no declaration or enum in reference");
6947 entity_t *entity = expression->select.compound_entry;
6948 assert(is_declaration(entity));
6949 type_t *type = entity->declaration.type;
6950 return get_qualified_type(type,
6951 expression->base.type->base.qualifiers);
6954 case EXPR_UNARY_DEREFERENCE: {
6955 const expression_t *const value = expression->unary.value;
6956 type_t *const type = skip_typeref(value->base.type);
6957 if (!is_type_pointer(type))
6958 return type_error_type;
6959 return type->pointer.points_to;
6962 case EXPR_ARRAY_ACCESS: {
6963 const expression_t *array_ref = expression->array_access.array_ref;
6964 type_t *type_left = skip_typeref(array_ref->base.type);
6965 if (!is_type_pointer(type_left))
6966 return type_error_type;
6967 return type_left->pointer.points_to;
6970 case EXPR_STRING_LITERAL: {
6971 size_t size = expression->string.value.size;
6972 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6975 case EXPR_WIDE_STRING_LITERAL: {
6976 size_t size = expression->wide_string.value.size;
6977 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6980 case EXPR_COMPOUND_LITERAL:
6981 return expression->compound_literal.type;
6984 return expression->base.type;
6988 static expression_t *parse_reference(void)
6990 symbol_t *const symbol = token.v.symbol;
6992 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6994 if (entity == NULL) {
6995 if (!strict_mode && look_ahead(1)->type == '(') {
6996 /* an implicitly declared function */
6997 if (warning.error_implicit_function_declaration) {
6998 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6999 } else if (warning.implicit_function_declaration) {
7000 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7003 entity = create_implicit_function(symbol, HERE);
7005 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7006 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7012 if (is_declaration(entity)) {
7013 orig_type = entity->declaration.type;
7014 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7015 orig_type = entity->enum_value.enum_type;
7016 } else if (entity->kind == ENTITY_TYPEDEF) {
7017 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7020 return create_invalid_expression();
7022 panic("expected declaration or enum value in reference");
7025 /* we always do the auto-type conversions; the & and sizeof parser contains
7026 * code to revert this! */
7027 type_t *type = automatic_type_conversion(orig_type);
7029 expression_kind_t kind = EXPR_REFERENCE;
7030 if (entity->kind == ENTITY_ENUM_VALUE)
7031 kind = EXPR_REFERENCE_ENUM_VALUE;
7033 expression_t *expression = allocate_expression_zero(kind);
7034 expression->reference.entity = entity;
7035 expression->base.type = type;
7037 /* this declaration is used */
7038 if (is_declaration(entity)) {
7039 entity->declaration.used = true;
7042 if (entity->base.parent_scope != file_scope
7043 && entity->base.parent_scope->depth < current_function->parameters.depth
7044 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7045 if (entity->kind == ENTITY_VARIABLE) {
7046 /* access of a variable from an outer function */
7047 entity->variable.address_taken = true;
7048 } else if (entity->kind == ENTITY_PARAMETER) {
7049 entity->parameter.address_taken = true;
7051 current_function->need_closure = true;
7054 /* check for deprecated functions */
7055 if (warning.deprecated_declarations
7056 && is_declaration(entity)
7057 && entity->declaration.modifiers & DM_DEPRECATED) {
7058 declaration_t *declaration = &entity->declaration;
7060 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7061 "function" : "variable";
7063 if (declaration->deprecated_string != NULL) {
7064 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7065 prefix, entity->base.symbol, &entity->base.source_position,
7066 declaration->deprecated_string);
7068 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7069 entity->base.symbol, &entity->base.source_position);
7073 if (warning.init_self && entity == current_init_decl && !in_type_prop
7074 && entity->kind == ENTITY_VARIABLE) {
7075 current_init_decl = NULL;
7076 warningf(HERE, "variable '%#T' is initialized by itself",
7077 entity->declaration.type, entity->base.symbol);
7084 static bool semantic_cast(expression_t *cast)
7086 expression_t *expression = cast->unary.value;
7087 type_t *orig_dest_type = cast->base.type;
7088 type_t *orig_type_right = expression->base.type;
7089 type_t const *dst_type = skip_typeref(orig_dest_type);
7090 type_t const *src_type = skip_typeref(orig_type_right);
7091 source_position_t const *pos = &cast->base.source_position;
7093 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7094 if (dst_type == type_void)
7097 /* only integer and pointer can be casted to pointer */
7098 if (is_type_pointer(dst_type) &&
7099 !is_type_pointer(src_type) &&
7100 !is_type_integer(src_type) &&
7101 is_type_valid(src_type)) {
7102 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7106 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7107 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7111 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7112 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7116 if (warning.cast_qual &&
7117 is_type_pointer(src_type) &&
7118 is_type_pointer(dst_type)) {
7119 type_t *src = skip_typeref(src_type->pointer.points_to);
7120 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7121 unsigned missing_qualifiers =
7122 src->base.qualifiers & ~dst->base.qualifiers;
7123 if (missing_qualifiers != 0) {
7125 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7126 missing_qualifiers, orig_type_right);
7132 static expression_t *parse_compound_literal(type_t *type)
7134 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7136 parse_initializer_env_t env;
7139 env.must_be_constant = false;
7140 initializer_t *initializer = parse_initializer(&env);
7143 expression->compound_literal.initializer = initializer;
7144 expression->compound_literal.type = type;
7145 expression->base.type = automatic_type_conversion(type);
7151 * Parse a cast expression.
7153 static expression_t *parse_cast(void)
7155 add_anchor_token(')');
7157 source_position_t source_position = token.source_position;
7159 type_t *type = parse_typename();
7161 rem_anchor_token(')');
7162 expect(')', end_error);
7164 if (token.type == '{') {
7165 return parse_compound_literal(type);
7168 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7169 cast->base.source_position = source_position;
7171 expression_t *value = parse_sub_expression(PREC_CAST);
7172 cast->base.type = type;
7173 cast->unary.value = value;
7175 if (! semantic_cast(cast)) {
7176 /* TODO: record the error in the AST. else it is impossible to detect it */
7181 return create_invalid_expression();
7185 * Parse a statement expression.
7187 static expression_t *parse_statement_expression(void)
7189 add_anchor_token(')');
7191 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7193 statement_t *statement = parse_compound_statement(true);
7194 statement->compound.stmt_expr = true;
7195 expression->statement.statement = statement;
7197 /* find last statement and use its type */
7198 type_t *type = type_void;
7199 const statement_t *stmt = statement->compound.statements;
7201 while (stmt->base.next != NULL)
7202 stmt = stmt->base.next;
7204 if (stmt->kind == STATEMENT_EXPRESSION) {
7205 type = stmt->expression.expression->base.type;
7207 } else if (warning.other) {
7208 warningf(&expression->base.source_position, "empty statement expression ({})");
7210 expression->base.type = type;
7212 rem_anchor_token(')');
7213 expect(')', end_error);
7220 * Parse a parenthesized expression.
7222 static expression_t *parse_parenthesized_expression(void)
7226 switch (token.type) {
7228 /* gcc extension: a statement expression */
7229 return parse_statement_expression();
7233 return parse_cast();
7235 if (is_typedef_symbol(token.v.symbol)) {
7236 return parse_cast();
7240 add_anchor_token(')');
7241 expression_t *result = parse_expression();
7242 result->base.parenthesized = true;
7243 rem_anchor_token(')');
7244 expect(')', end_error);
7250 static expression_t *parse_function_keyword(void)
7254 if (current_function == NULL) {
7255 errorf(HERE, "'__func__' used outside of a function");
7258 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7259 expression->base.type = type_char_ptr;
7260 expression->funcname.kind = FUNCNAME_FUNCTION;
7267 static expression_t *parse_pretty_function_keyword(void)
7269 if (current_function == NULL) {
7270 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7273 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7274 expression->base.type = type_char_ptr;
7275 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7277 eat(T___PRETTY_FUNCTION__);
7282 static expression_t *parse_funcsig_keyword(void)
7284 if (current_function == NULL) {
7285 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7288 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7289 expression->base.type = type_char_ptr;
7290 expression->funcname.kind = FUNCNAME_FUNCSIG;
7297 static expression_t *parse_funcdname_keyword(void)
7299 if (current_function == NULL) {
7300 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7303 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7304 expression->base.type = type_char_ptr;
7305 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7307 eat(T___FUNCDNAME__);
7312 static designator_t *parse_designator(void)
7314 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7315 result->source_position = *HERE;
7317 if (token.type != T_IDENTIFIER) {
7318 parse_error_expected("while parsing member designator",
7319 T_IDENTIFIER, NULL);
7322 result->symbol = token.v.symbol;
7325 designator_t *last_designator = result;
7327 if (token.type == '.') {
7329 if (token.type != T_IDENTIFIER) {
7330 parse_error_expected("while parsing member designator",
7331 T_IDENTIFIER, NULL);
7334 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7335 designator->source_position = *HERE;
7336 designator->symbol = token.v.symbol;
7339 last_designator->next = designator;
7340 last_designator = designator;
7343 if (token.type == '[') {
7345 add_anchor_token(']');
7346 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7347 designator->source_position = *HERE;
7348 designator->array_index = parse_expression();
7349 rem_anchor_token(']');
7350 expect(']', end_error);
7351 if (designator->array_index == NULL) {
7355 last_designator->next = designator;
7356 last_designator = designator;
7368 * Parse the __builtin_offsetof() expression.
7370 static expression_t *parse_offsetof(void)
7372 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7373 expression->base.type = type_size_t;
7375 eat(T___builtin_offsetof);
7377 expect('(', end_error);
7378 add_anchor_token(',');
7379 type_t *type = parse_typename();
7380 rem_anchor_token(',');
7381 expect(',', end_error);
7382 add_anchor_token(')');
7383 designator_t *designator = parse_designator();
7384 rem_anchor_token(')');
7385 expect(')', end_error);
7387 expression->offsetofe.type = type;
7388 expression->offsetofe.designator = designator;
7391 memset(&path, 0, sizeof(path));
7392 path.top_type = type;
7393 path.path = NEW_ARR_F(type_path_entry_t, 0);
7395 descend_into_subtype(&path);
7397 if (!walk_designator(&path, designator, true)) {
7398 return create_invalid_expression();
7401 DEL_ARR_F(path.path);
7405 return create_invalid_expression();
7409 * Parses a _builtin_va_start() expression.
7411 static expression_t *parse_va_start(void)
7413 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7415 eat(T___builtin_va_start);
7417 expect('(', end_error);
7418 add_anchor_token(',');
7419 expression->va_starte.ap = parse_assignment_expression();
7420 rem_anchor_token(',');
7421 expect(',', end_error);
7422 expression_t *const expr = parse_assignment_expression();
7423 if (expr->kind == EXPR_REFERENCE) {
7424 entity_t *const entity = expr->reference.entity;
7425 if (entity->base.parent_scope != ¤t_function->parameters
7426 || entity->base.next != NULL
7427 || entity->kind != ENTITY_PARAMETER) {
7428 errorf(&expr->base.source_position,
7429 "second argument of 'va_start' must be last parameter of the current function");
7431 expression->va_starte.parameter = &entity->variable;
7433 expect(')', end_error);
7436 expect(')', end_error);
7438 return create_invalid_expression();
7442 * Parses a _builtin_va_arg() expression.
7444 static expression_t *parse_va_arg(void)
7446 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7448 eat(T___builtin_va_arg);
7450 expect('(', end_error);
7451 expression->va_arge.ap = parse_assignment_expression();
7452 expect(',', end_error);
7453 expression->base.type = parse_typename();
7454 expect(')', end_error);
7458 return create_invalid_expression();
7462 * Parses a __builtin_constant_p() expression.
7464 static expression_t *parse_builtin_constant(void)
7466 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7468 eat(T___builtin_constant_p);
7470 expect('(', end_error);
7471 add_anchor_token(')');
7472 expression->builtin_constant.value = parse_assignment_expression();
7473 rem_anchor_token(')');
7474 expect(')', end_error);
7475 expression->base.type = type_int;
7479 return create_invalid_expression();
7483 * Parses a __builtin_types_compatible_p() expression.
7485 static expression_t *parse_builtin_types_compatible(void)
7487 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7489 eat(T___builtin_types_compatible_p);
7491 expect('(', end_error);
7492 add_anchor_token(')');
7493 add_anchor_token(',');
7494 expression->builtin_types_compatible.left = parse_typename();
7495 rem_anchor_token(',');
7496 expect(',', end_error);
7497 expression->builtin_types_compatible.right = parse_typename();
7498 rem_anchor_token(')');
7499 expect(')', end_error);
7500 expression->base.type = type_int;
7504 return create_invalid_expression();
7508 * Parses a __builtin_is_*() compare expression.
7510 static expression_t *parse_compare_builtin(void)
7512 expression_t *expression;
7514 switch (token.type) {
7515 case T___builtin_isgreater:
7516 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7518 case T___builtin_isgreaterequal:
7519 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7521 case T___builtin_isless:
7522 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7524 case T___builtin_islessequal:
7525 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7527 case T___builtin_islessgreater:
7528 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7530 case T___builtin_isunordered:
7531 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7534 internal_errorf(HERE, "invalid compare builtin found");
7536 expression->base.source_position = *HERE;
7539 expect('(', end_error);
7540 expression->binary.left = parse_assignment_expression();
7541 expect(',', end_error);
7542 expression->binary.right = parse_assignment_expression();
7543 expect(')', end_error);
7545 type_t *const orig_type_left = expression->binary.left->base.type;
7546 type_t *const orig_type_right = expression->binary.right->base.type;
7548 type_t *const type_left = skip_typeref(orig_type_left);
7549 type_t *const type_right = skip_typeref(orig_type_right);
7550 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7551 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7552 type_error_incompatible("invalid operands in comparison",
7553 &expression->base.source_position, orig_type_left, orig_type_right);
7556 semantic_comparison(&expression->binary);
7561 return create_invalid_expression();
7566 * Parses a __builtin_expect(, end_error) expression.
7568 static expression_t *parse_builtin_expect(void, end_error)
7570 expression_t *expression
7571 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7573 eat(T___builtin_expect);
7575 expect('(', end_error);
7576 expression->binary.left = parse_assignment_expression();
7577 expect(',', end_error);
7578 expression->binary.right = parse_constant_expression();
7579 expect(')', end_error);
7581 expression->base.type = expression->binary.left->base.type;
7585 return create_invalid_expression();
7590 * Parses a MS assume() expression.
7592 static expression_t *parse_assume(void)
7594 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7598 expect('(', end_error);
7599 add_anchor_token(')');
7600 expression->unary.value = parse_assignment_expression();
7601 rem_anchor_token(')');
7602 expect(')', end_error);
7604 expression->base.type = type_void;
7607 return create_invalid_expression();
7611 * Return the declaration for a given label symbol or create a new one.
7613 * @param symbol the symbol of the label
7615 static label_t *get_label(symbol_t *symbol)
7618 assert(current_function != NULL);
7620 label = get_entity(symbol, NAMESPACE_LABEL);
7621 /* if we found a local label, we already created the declaration */
7622 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7623 if (label->base.parent_scope != current_scope) {
7624 assert(label->base.parent_scope->depth < current_scope->depth);
7625 current_function->goto_to_outer = true;
7627 return &label->label;
7630 label = get_entity(symbol, NAMESPACE_LABEL);
7631 /* if we found a label in the same function, then we already created the
7634 && label->base.parent_scope == ¤t_function->parameters) {
7635 return &label->label;
7638 /* otherwise we need to create a new one */
7639 label = allocate_entity_zero(ENTITY_LABEL);
7640 label->base.namespc = NAMESPACE_LABEL;
7641 label->base.symbol = symbol;
7645 return &label->label;
7649 * Parses a GNU && label address expression.
7651 static expression_t *parse_label_address(void)
7653 source_position_t source_position = token.source_position;
7655 if (token.type != T_IDENTIFIER) {
7656 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7659 symbol_t *symbol = token.v.symbol;
7662 label_t *label = get_label(symbol);
7664 label->address_taken = true;
7666 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7667 expression->base.source_position = source_position;
7669 /* label address is threaten as a void pointer */
7670 expression->base.type = type_void_ptr;
7671 expression->label_address.label = label;
7674 return create_invalid_expression();
7678 * Parse a microsoft __noop expression.
7680 static expression_t *parse_noop_expression(void)
7682 /* the result is a (int)0 */
7683 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7684 cnst->base.type = type_int;
7685 cnst->conste.v.int_value = 0;
7686 cnst->conste.is_ms_noop = true;
7690 if (token.type == '(') {
7691 /* parse arguments */
7693 add_anchor_token(')');
7694 add_anchor_token(',');
7696 if (token.type != ')') {
7698 (void)parse_assignment_expression();
7699 if (token.type != ',')
7705 rem_anchor_token(',');
7706 rem_anchor_token(')');
7707 expect(')', end_error);
7714 * Parses a primary expression.
7716 static expression_t *parse_primary_expression(void)
7718 switch (token.type) {
7719 case T_false: return parse_bool_const(false);
7720 case T_true: return parse_bool_const(true);
7721 case T_INTEGER: return parse_int_const();
7722 case T_CHARACTER_CONSTANT: return parse_character_constant();
7723 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7724 case T_FLOATINGPOINT: return parse_float_const();
7725 case T_STRING_LITERAL:
7726 case T_WIDE_STRING_LITERAL: return parse_string_const();
7727 case T_IDENTIFIER: return parse_reference();
7728 case T___FUNCTION__:
7729 case T___func__: return parse_function_keyword();
7730 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7731 case T___FUNCSIG__: return parse_funcsig_keyword();
7732 case T___FUNCDNAME__: return parse_funcdname_keyword();
7733 case T___builtin_offsetof: return parse_offsetof();
7734 case T___builtin_va_start: return parse_va_start();
7735 case T___builtin_va_arg: return parse_va_arg();
7736 case T___builtin_isgreater:
7737 case T___builtin_isgreaterequal:
7738 case T___builtin_isless:
7739 case T___builtin_islessequal:
7740 case T___builtin_islessgreater:
7741 case T___builtin_isunordered: return parse_compare_builtin();
7742 case T___builtin_constant_p: return parse_builtin_constant();
7743 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7744 case T__assume: return parse_assume();
7747 return parse_label_address();
7750 case '(': return parse_parenthesized_expression();
7751 case T___noop: return parse_noop_expression();
7754 errorf(HERE, "unexpected token %K, expected an expression", &token);
7755 return create_invalid_expression();
7759 * Check if the expression has the character type and issue a warning then.
7761 static void check_for_char_index_type(const expression_t *expression)
7763 type_t *const type = expression->base.type;
7764 const type_t *const base_type = skip_typeref(type);
7766 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7767 warning.char_subscripts) {
7768 warningf(&expression->base.source_position,
7769 "array subscript has type '%T'", type);
7773 static expression_t *parse_array_expression(expression_t *left)
7775 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7778 add_anchor_token(']');
7780 expression_t *inside = parse_expression();
7782 type_t *const orig_type_left = left->base.type;
7783 type_t *const orig_type_inside = inside->base.type;
7785 type_t *const type_left = skip_typeref(orig_type_left);
7786 type_t *const type_inside = skip_typeref(orig_type_inside);
7788 type_t *return_type;
7789 array_access_expression_t *array_access = &expression->array_access;
7790 if (is_type_pointer(type_left)) {
7791 return_type = type_left->pointer.points_to;
7792 array_access->array_ref = left;
7793 array_access->index = inside;
7794 check_for_char_index_type(inside);
7795 } else if (is_type_pointer(type_inside)) {
7796 return_type = type_inside->pointer.points_to;
7797 array_access->array_ref = inside;
7798 array_access->index = left;
7799 array_access->flipped = true;
7800 check_for_char_index_type(left);
7802 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7804 "array access on object with non-pointer types '%T', '%T'",
7805 orig_type_left, orig_type_inside);
7807 return_type = type_error_type;
7808 array_access->array_ref = left;
7809 array_access->index = inside;
7812 expression->base.type = automatic_type_conversion(return_type);
7814 rem_anchor_token(']');
7815 expect(']', end_error);
7820 static expression_t *parse_typeprop(expression_kind_t const kind)
7822 expression_t *tp_expression = allocate_expression_zero(kind);
7823 tp_expression->base.type = type_size_t;
7825 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7827 /* we only refer to a type property, mark this case */
7828 bool old = in_type_prop;
7829 in_type_prop = true;
7832 expression_t *expression;
7833 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7835 add_anchor_token(')');
7836 orig_type = parse_typename();
7837 rem_anchor_token(')');
7838 expect(')', end_error);
7840 if (token.type == '{') {
7841 /* It was not sizeof(type) after all. It is sizeof of an expression
7842 * starting with a compound literal */
7843 expression = parse_compound_literal(orig_type);
7844 goto typeprop_expression;
7847 expression = parse_sub_expression(PREC_UNARY);
7849 typeprop_expression:
7850 tp_expression->typeprop.tp_expression = expression;
7852 orig_type = revert_automatic_type_conversion(expression);
7853 expression->base.type = orig_type;
7856 tp_expression->typeprop.type = orig_type;
7857 type_t const* const type = skip_typeref(orig_type);
7858 char const* const wrong_type =
7859 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7860 is_type_incomplete(type) ? "incomplete" :
7861 type->kind == TYPE_FUNCTION ? "function designator" :
7862 type->kind == TYPE_BITFIELD ? "bitfield" :
7864 if (wrong_type != NULL) {
7865 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7866 errorf(&tp_expression->base.source_position,
7867 "operand of %s expression must not be of %s type '%T'",
7868 what, wrong_type, orig_type);
7873 return tp_expression;
7876 static expression_t *parse_sizeof(void)
7878 return parse_typeprop(EXPR_SIZEOF);
7881 static expression_t *parse_alignof(void)
7883 return parse_typeprop(EXPR_ALIGNOF);
7886 static expression_t *parse_select_expression(expression_t *compound)
7888 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7889 select->select.compound = compound;
7891 assert(token.type == '.' || token.type == T_MINUSGREATER);
7892 bool is_pointer = (token.type == T_MINUSGREATER);
7895 if (token.type != T_IDENTIFIER) {
7896 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7899 symbol_t *symbol = token.v.symbol;
7902 type_t *const orig_type = compound->base.type;
7903 type_t *const type = skip_typeref(orig_type);
7906 bool saw_error = false;
7907 if (is_type_pointer(type)) {
7910 "request for member '%Y' in something not a struct or union, but '%T'",
7914 type_left = skip_typeref(type->pointer.points_to);
7916 if (is_pointer && is_type_valid(type)) {
7917 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7924 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7925 type_left->kind == TYPE_COMPOUND_UNION) {
7926 compound_t *compound = type_left->compound.compound;
7928 if (!compound->complete) {
7929 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7931 goto create_error_entry;
7934 entry = find_compound_entry(compound, symbol);
7935 if (entry == NULL) {
7936 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7937 goto create_error_entry;
7940 if (is_type_valid(type_left) && !saw_error) {
7942 "request for member '%Y' in something not a struct or union, but '%T'",
7946 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7949 assert(is_declaration(entry));
7950 select->select.compound_entry = entry;
7952 type_t *entry_type = entry->declaration.type;
7954 = get_qualified_type(entry_type, type_left->base.qualifiers);
7956 /* we always do the auto-type conversions; the & and sizeof parser contains
7957 * code to revert this! */
7958 select->base.type = automatic_type_conversion(res_type);
7960 type_t *skipped = skip_typeref(res_type);
7961 if (skipped->kind == TYPE_BITFIELD) {
7962 select->base.type = skipped->bitfield.base_type;
7968 static void check_call_argument(const function_parameter_t *parameter,
7969 call_argument_t *argument, unsigned pos)
7971 type_t *expected_type = parameter->type;
7972 type_t *expected_type_skip = skip_typeref(expected_type);
7973 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7974 expression_t *arg_expr = argument->expression;
7975 type_t *arg_type = skip_typeref(arg_expr->base.type);
7977 /* handle transparent union gnu extension */
7978 if (is_type_union(expected_type_skip)
7979 && (expected_type_skip->base.modifiers
7980 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7981 compound_t *union_decl = expected_type_skip->compound.compound;
7982 type_t *best_type = NULL;
7983 entity_t *entry = union_decl->members.entities;
7984 for ( ; entry != NULL; entry = entry->base.next) {
7985 assert(is_declaration(entry));
7986 type_t *decl_type = entry->declaration.type;
7987 error = semantic_assign(decl_type, arg_expr);
7988 if (error == ASSIGN_ERROR_INCOMPATIBLE
7989 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7992 if (error == ASSIGN_SUCCESS) {
7993 best_type = decl_type;
7994 } else if (best_type == NULL) {
7995 best_type = decl_type;
7999 if (best_type != NULL) {
8000 expected_type = best_type;
8004 error = semantic_assign(expected_type, arg_expr);
8005 argument->expression = create_implicit_cast(argument->expression,
8008 if (error != ASSIGN_SUCCESS) {
8009 /* report exact scope in error messages (like "in argument 3") */
8011 snprintf(buf, sizeof(buf), "call argument %u", pos);
8012 report_assign_error(error, expected_type, arg_expr, buf,
8013 &arg_expr->base.source_position);
8014 } else if (warning.traditional || warning.conversion) {
8015 type_t *const promoted_type = get_default_promoted_type(arg_type);
8016 if (!types_compatible(expected_type_skip, promoted_type) &&
8017 !types_compatible(expected_type_skip, type_void_ptr) &&
8018 !types_compatible(type_void_ptr, promoted_type)) {
8019 /* Deliberately show the skipped types in this warning */
8020 warningf(&arg_expr->base.source_position,
8021 "passing call argument %u as '%T' rather than '%T' due to prototype",
8022 pos, expected_type_skip, promoted_type);
8028 * Handle the semantic restrictions of builtin calls
8030 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8031 switch (call->function->reference.entity->function.btk) {
8032 case bk_gnu_builtin_return_address:
8033 case bk_gnu_builtin_frame_address: {
8034 /* argument must be constant */
8035 call_argument_t *argument = call->arguments;
8037 if (! is_constant_expression(argument->expression)) {
8038 errorf(&call->base.source_position,
8039 "argument of '%Y' must be a constant expression",
8040 call->function->reference.entity->base.symbol);
8044 case bk_gnu_builtin_prefetch: {
8045 /* second and third argument must be constant if existent */
8046 call_argument_t *rw = call->arguments->next;
8047 call_argument_t *locality = NULL;
8050 if (! is_constant_expression(rw->expression)) {
8051 errorf(&call->base.source_position,
8052 "second argument of '%Y' must be a constant expression",
8053 call->function->reference.entity->base.symbol);
8055 locality = rw->next;
8057 if (locality != NULL) {
8058 if (! is_constant_expression(locality->expression)) {
8059 errorf(&call->base.source_position,
8060 "third argument of '%Y' must be a constant expression",
8061 call->function->reference.entity->base.symbol);
8063 locality = rw->next;
8073 * Parse a call expression, ie. expression '( ... )'.
8075 * @param expression the function address
8077 static expression_t *parse_call_expression(expression_t *expression)
8079 expression_t *result = allocate_expression_zero(EXPR_CALL);
8080 call_expression_t *call = &result->call;
8081 call->function = expression;
8083 type_t *const orig_type = expression->base.type;
8084 type_t *const type = skip_typeref(orig_type);
8086 function_type_t *function_type = NULL;
8087 if (is_type_pointer(type)) {
8088 type_t *const to_type = skip_typeref(type->pointer.points_to);
8090 if (is_type_function(to_type)) {
8091 function_type = &to_type->function;
8092 call->base.type = function_type->return_type;
8096 if (function_type == NULL && is_type_valid(type)) {
8097 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8100 /* parse arguments */
8102 add_anchor_token(')');
8103 add_anchor_token(',');
8105 if (token.type != ')') {
8106 call_argument_t *last_argument = NULL;
8109 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8111 argument->expression = parse_assignment_expression();
8112 if (last_argument == NULL) {
8113 call->arguments = argument;
8115 last_argument->next = argument;
8117 last_argument = argument;
8119 if (token.type != ',')
8124 rem_anchor_token(',');
8125 rem_anchor_token(')');
8126 expect(')', end_error);
8128 if (function_type == NULL)
8131 function_parameter_t *parameter = function_type->parameters;
8132 call_argument_t *argument = call->arguments;
8133 if (!function_type->unspecified_parameters) {
8134 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8135 parameter = parameter->next, argument = argument->next) {
8136 check_call_argument(parameter, argument, ++pos);
8139 if (parameter != NULL) {
8140 errorf(HERE, "too few arguments to function '%E'", expression);
8141 } else if (argument != NULL && !function_type->variadic) {
8142 errorf(HERE, "too many arguments to function '%E'", expression);
8146 /* do default promotion */
8147 for (; argument != NULL; argument = argument->next) {
8148 type_t *type = argument->expression->base.type;
8150 type = get_default_promoted_type(type);
8152 argument->expression
8153 = create_implicit_cast(argument->expression, type);
8156 check_format(&result->call);
8158 if (warning.aggregate_return &&
8159 is_type_compound(skip_typeref(function_type->return_type))) {
8160 warningf(&result->base.source_position,
8161 "function call has aggregate value");
8164 if (call->function->kind == EXPR_REFERENCE) {
8165 reference_expression_t *reference = &call->function->reference;
8166 if (reference->entity->kind == ENTITY_FUNCTION &&
8167 reference->entity->function.btk != bk_none)
8168 handle_builtin_argument_restrictions(call);
8175 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8177 static bool same_compound_type(const type_t *type1, const type_t *type2)
8180 is_type_compound(type1) &&
8181 type1->kind == type2->kind &&
8182 type1->compound.compound == type2->compound.compound;
8185 static expression_t const *get_reference_address(expression_t const *expr)
8187 bool regular_take_address = true;
8189 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8190 expr = expr->unary.value;
8192 regular_take_address = false;
8195 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8198 expr = expr->unary.value;
8201 if (expr->kind != EXPR_REFERENCE)
8204 /* special case for functions which are automatically converted to a
8205 * pointer to function without an extra TAKE_ADDRESS operation */
8206 if (!regular_take_address &&
8207 expr->reference.entity->kind != ENTITY_FUNCTION) {
8214 static void warn_reference_address_as_bool(expression_t const* expr)
8216 if (!warning.address)
8219 expr = get_reference_address(expr);
8221 warningf(&expr->base.source_position,
8222 "the address of '%Y' will always evaluate as 'true'",
8223 expr->reference.entity->base.symbol);
8227 static void warn_assignment_in_condition(const expression_t *const expr)
8229 if (!warning.parentheses)
8231 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8233 if (expr->base.parenthesized)
8235 warningf(&expr->base.source_position,
8236 "suggest parentheses around assignment used as truth value");
8239 static void semantic_condition(expression_t const *const expr,
8240 char const *const context)
8242 type_t *const type = skip_typeref(expr->base.type);
8243 if (is_type_scalar(type)) {
8244 warn_reference_address_as_bool(expr);
8245 warn_assignment_in_condition(expr);
8246 } else if (is_type_valid(type)) {
8247 errorf(&expr->base.source_position,
8248 "%s must have scalar type", context);
8253 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8255 * @param expression the conditional expression
8257 static expression_t *parse_conditional_expression(expression_t *expression)
8259 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8261 conditional_expression_t *conditional = &result->conditional;
8262 conditional->condition = expression;
8265 add_anchor_token(':');
8267 /* §6.5.15:2 The first operand shall have scalar type. */
8268 semantic_condition(expression, "condition of conditional operator");
8270 expression_t *true_expression = expression;
8271 bool gnu_cond = false;
8272 if (GNU_MODE && token.type == ':') {
8275 true_expression = parse_expression();
8277 rem_anchor_token(':');
8278 expect(':', end_error);
8280 expression_t *false_expression =
8281 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8283 type_t *const orig_true_type = true_expression->base.type;
8284 type_t *const orig_false_type = false_expression->base.type;
8285 type_t *const true_type = skip_typeref(orig_true_type);
8286 type_t *const false_type = skip_typeref(orig_false_type);
8289 type_t *result_type;
8290 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8291 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8292 /* ISO/IEC 14882:1998(E) §5.16:2 */
8293 if (true_expression->kind == EXPR_UNARY_THROW) {
8294 result_type = false_type;
8295 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8296 result_type = true_type;
8298 if (warning.other && (
8299 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8300 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8302 warningf(&conditional->base.source_position,
8303 "ISO C forbids conditional expression with only one void side");
8305 result_type = type_void;
8307 } else if (is_type_arithmetic(true_type)
8308 && is_type_arithmetic(false_type)) {
8309 result_type = semantic_arithmetic(true_type, false_type);
8311 true_expression = create_implicit_cast(true_expression, result_type);
8312 false_expression = create_implicit_cast(false_expression, result_type);
8314 conditional->true_expression = true_expression;
8315 conditional->false_expression = false_expression;
8316 conditional->base.type = result_type;
8317 } else if (same_compound_type(true_type, false_type)) {
8318 /* just take 1 of the 2 types */
8319 result_type = true_type;
8320 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8321 type_t *pointer_type;
8323 expression_t *other_expression;
8324 if (is_type_pointer(true_type) &&
8325 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8326 pointer_type = true_type;
8327 other_type = false_type;
8328 other_expression = false_expression;
8330 pointer_type = false_type;
8331 other_type = true_type;
8332 other_expression = true_expression;
8335 if (is_null_pointer_constant(other_expression)) {
8336 result_type = pointer_type;
8337 } else if (is_type_pointer(other_type)) {
8338 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8339 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8342 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8343 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8345 } else if (types_compatible(get_unqualified_type(to1),
8346 get_unqualified_type(to2))) {
8349 if (warning.other) {
8350 warningf(&conditional->base.source_position,
8351 "pointer types '%T' and '%T' in conditional expression are incompatible",
8352 true_type, false_type);
8357 type_t *const type =
8358 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8359 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8360 } else if (is_type_integer(other_type)) {
8361 if (warning.other) {
8362 warningf(&conditional->base.source_position,
8363 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8365 result_type = pointer_type;
8367 if (is_type_valid(other_type)) {
8368 type_error_incompatible("while parsing conditional",
8369 &expression->base.source_position, true_type, false_type);
8371 result_type = type_error_type;
8374 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8375 type_error_incompatible("while parsing conditional",
8376 &conditional->base.source_position, true_type,
8379 result_type = type_error_type;
8382 conditional->true_expression
8383 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8384 conditional->false_expression
8385 = create_implicit_cast(false_expression, result_type);
8386 conditional->base.type = result_type;
8391 * Parse an extension expression.
8393 static expression_t *parse_extension(void)
8395 eat(T___extension__);
8397 bool old_gcc_extension = in_gcc_extension;
8398 in_gcc_extension = true;
8399 expression_t *expression = parse_sub_expression(PREC_UNARY);
8400 in_gcc_extension = old_gcc_extension;
8405 * Parse a __builtin_classify_type() expression.
8407 static expression_t *parse_builtin_classify_type(void)
8409 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8410 result->base.type = type_int;
8412 eat(T___builtin_classify_type);
8414 expect('(', end_error);
8415 add_anchor_token(')');
8416 expression_t *expression = parse_expression();
8417 rem_anchor_token(')');
8418 expect(')', end_error);
8419 result->classify_type.type_expression = expression;
8423 return create_invalid_expression();
8427 * Parse a delete expression
8428 * ISO/IEC 14882:1998(E) §5.3.5
8430 static expression_t *parse_delete(void)
8432 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8433 result->base.type = type_void;
8437 if (token.type == '[') {
8439 result->kind = EXPR_UNARY_DELETE_ARRAY;
8440 expect(']', end_error);
8444 expression_t *const value = parse_sub_expression(PREC_CAST);
8445 result->unary.value = value;
8447 type_t *const type = skip_typeref(value->base.type);
8448 if (!is_type_pointer(type)) {
8449 if (is_type_valid(type)) {
8450 errorf(&value->base.source_position,
8451 "operand of delete must have pointer type");
8453 } else if (warning.other &&
8454 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8455 warningf(&value->base.source_position,
8456 "deleting 'void*' is undefined");
8463 * Parse a throw expression
8464 * ISO/IEC 14882:1998(E) §15:1
8466 static expression_t *parse_throw(void)
8468 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8469 result->base.type = type_void;
8473 expression_t *value = NULL;
8474 switch (token.type) {
8476 value = parse_assignment_expression();
8477 /* ISO/IEC 14882:1998(E) §15.1:3 */
8478 type_t *const orig_type = value->base.type;
8479 type_t *const type = skip_typeref(orig_type);
8480 if (is_type_incomplete(type)) {
8481 errorf(&value->base.source_position,
8482 "cannot throw object of incomplete type '%T'", orig_type);
8483 } else if (is_type_pointer(type)) {
8484 type_t *const points_to = skip_typeref(type->pointer.points_to);
8485 if (is_type_incomplete(points_to) &&
8486 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8487 errorf(&value->base.source_position,
8488 "cannot throw pointer to incomplete type '%T'", orig_type);
8496 result->unary.value = value;
8501 static bool check_pointer_arithmetic(const source_position_t *source_position,
8502 type_t *pointer_type,
8503 type_t *orig_pointer_type)
8505 type_t *points_to = pointer_type->pointer.points_to;
8506 points_to = skip_typeref(points_to);
8508 if (is_type_incomplete(points_to)) {
8509 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8510 errorf(source_position,
8511 "arithmetic with pointer to incomplete type '%T' not allowed",
8514 } else if (warning.pointer_arith) {
8515 warningf(source_position,
8516 "pointer of type '%T' used in arithmetic",
8519 } else if (is_type_function(points_to)) {
8521 errorf(source_position,
8522 "arithmetic with pointer to function type '%T' not allowed",
8525 } else if (warning.pointer_arith) {
8526 warningf(source_position,
8527 "pointer to a function '%T' used in arithmetic",
8534 static bool is_lvalue(const expression_t *expression)
8536 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8537 switch (expression->kind) {
8538 case EXPR_ARRAY_ACCESS:
8539 case EXPR_COMPOUND_LITERAL:
8540 case EXPR_REFERENCE:
8542 case EXPR_UNARY_DEREFERENCE:
8546 type_t *type = skip_typeref(expression->base.type);
8548 /* ISO/IEC 14882:1998(E) §3.10:3 */
8549 is_type_reference(type) ||
8550 /* Claim it is an lvalue, if the type is invalid. There was a parse
8551 * error before, which maybe prevented properly recognizing it as
8553 !is_type_valid(type);
8558 static void semantic_incdec(unary_expression_t *expression)
8560 type_t *const orig_type = expression->value->base.type;
8561 type_t *const type = skip_typeref(orig_type);
8562 if (is_type_pointer(type)) {
8563 if (!check_pointer_arithmetic(&expression->base.source_position,
8567 } else if (!is_type_real(type) && is_type_valid(type)) {
8568 /* TODO: improve error message */
8569 errorf(&expression->base.source_position,
8570 "operation needs an arithmetic or pointer type");
8573 if (!is_lvalue(expression->value)) {
8574 /* TODO: improve error message */
8575 errorf(&expression->base.source_position, "lvalue required as operand");
8577 expression->base.type = orig_type;
8580 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8582 type_t *const orig_type = expression->value->base.type;
8583 type_t *const type = skip_typeref(orig_type);
8584 if (!is_type_arithmetic(type)) {
8585 if (is_type_valid(type)) {
8586 /* TODO: improve error message */
8587 errorf(&expression->base.source_position,
8588 "operation needs an arithmetic type");
8593 expression->base.type = orig_type;
8596 static void semantic_unexpr_plus(unary_expression_t *expression)
8598 semantic_unexpr_arithmetic(expression);
8599 if (warning.traditional)
8600 warningf(&expression->base.source_position,
8601 "traditional C rejects the unary plus operator");
8604 static void semantic_not(unary_expression_t *expression)
8606 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8607 semantic_condition(expression->value, "operand of !");
8608 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8611 static void semantic_unexpr_integer(unary_expression_t *expression)
8613 type_t *const orig_type = expression->value->base.type;
8614 type_t *const type = skip_typeref(orig_type);
8615 if (!is_type_integer(type)) {
8616 if (is_type_valid(type)) {
8617 errorf(&expression->base.source_position,
8618 "operand of ~ must be of integer type");
8623 expression->base.type = orig_type;
8626 static void semantic_dereference(unary_expression_t *expression)
8628 type_t *const orig_type = expression->value->base.type;
8629 type_t *const type = skip_typeref(orig_type);
8630 if (!is_type_pointer(type)) {
8631 if (is_type_valid(type)) {
8632 errorf(&expression->base.source_position,
8633 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8638 type_t *result_type = type->pointer.points_to;
8639 result_type = automatic_type_conversion(result_type);
8640 expression->base.type = result_type;
8644 * Record that an address is taken (expression represents an lvalue).
8646 * @param expression the expression
8647 * @param may_be_register if true, the expression might be an register
8649 static void set_address_taken(expression_t *expression, bool may_be_register)
8651 if (expression->kind != EXPR_REFERENCE)
8654 entity_t *const entity = expression->reference.entity;
8656 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8659 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8660 && !may_be_register) {
8661 errorf(&expression->base.source_position,
8662 "address of register %s '%Y' requested",
8663 get_entity_kind_name(entity->kind), entity->base.symbol);
8666 if (entity->kind == ENTITY_VARIABLE) {
8667 entity->variable.address_taken = true;
8669 assert(entity->kind == ENTITY_PARAMETER);
8670 entity->parameter.address_taken = true;
8675 * Check the semantic of the address taken expression.
8677 static void semantic_take_addr(unary_expression_t *expression)
8679 expression_t *value = expression->value;
8680 value->base.type = revert_automatic_type_conversion(value);
8682 type_t *orig_type = value->base.type;
8683 type_t *type = skip_typeref(orig_type);
8684 if (!is_type_valid(type))
8688 if (!is_lvalue(value)) {
8689 errorf(&expression->base.source_position, "'&' requires an lvalue");
8691 if (type->kind == TYPE_BITFIELD) {
8692 errorf(&expression->base.source_position,
8693 "'&' not allowed on object with bitfield type '%T'",
8697 set_address_taken(value, false);
8699 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8702 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8703 static expression_t *parse_##unexpression_type(void) \
8705 expression_t *unary_expression \
8706 = allocate_expression_zero(unexpression_type); \
8708 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8710 sfunc(&unary_expression->unary); \
8712 return unary_expression; \
8715 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8716 semantic_unexpr_arithmetic)
8717 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8718 semantic_unexpr_plus)
8719 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8721 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8722 semantic_dereference)
8723 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8725 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8726 semantic_unexpr_integer)
8727 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8729 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8732 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8734 static expression_t *parse_##unexpression_type(expression_t *left) \
8736 expression_t *unary_expression \
8737 = allocate_expression_zero(unexpression_type); \
8739 unary_expression->unary.value = left; \
8741 sfunc(&unary_expression->unary); \
8743 return unary_expression; \
8746 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8747 EXPR_UNARY_POSTFIX_INCREMENT,
8749 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8750 EXPR_UNARY_POSTFIX_DECREMENT,
8753 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8755 /* TODO: handle complex + imaginary types */
8757 type_left = get_unqualified_type(type_left);
8758 type_right = get_unqualified_type(type_right);
8760 /* §6.3.1.8 Usual arithmetic conversions */
8761 if (type_left == type_long_double || type_right == type_long_double) {
8762 return type_long_double;
8763 } else if (type_left == type_double || type_right == type_double) {
8765 } else if (type_left == type_float || type_right == type_float) {
8769 type_left = promote_integer(type_left);
8770 type_right = promote_integer(type_right);
8772 if (type_left == type_right)
8775 bool const signed_left = is_type_signed(type_left);
8776 bool const signed_right = is_type_signed(type_right);
8777 int const rank_left = get_rank(type_left);
8778 int const rank_right = get_rank(type_right);
8780 if (signed_left == signed_right)
8781 return rank_left >= rank_right ? type_left : type_right;
8790 u_rank = rank_right;
8791 u_type = type_right;
8793 s_rank = rank_right;
8794 s_type = type_right;
8799 if (u_rank >= s_rank)
8802 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8804 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8805 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8809 case ATOMIC_TYPE_INT: return type_unsigned_int;
8810 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8811 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8813 default: panic("invalid atomic type");
8818 * Check the semantic restrictions for a binary expression.
8820 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8822 expression_t *const left = expression->left;
8823 expression_t *const right = expression->right;
8824 type_t *const orig_type_left = left->base.type;
8825 type_t *const orig_type_right = right->base.type;
8826 type_t *const type_left = skip_typeref(orig_type_left);
8827 type_t *const type_right = skip_typeref(orig_type_right);
8829 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8830 /* TODO: improve error message */
8831 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8832 errorf(&expression->base.source_position,
8833 "operation needs arithmetic types");
8838 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8839 expression->left = create_implicit_cast(left, arithmetic_type);
8840 expression->right = create_implicit_cast(right, arithmetic_type);
8841 expression->base.type = arithmetic_type;
8844 static void warn_div_by_zero(binary_expression_t const *const expression)
8846 if (!warning.div_by_zero ||
8847 !is_type_integer(expression->base.type))
8850 expression_t const *const right = expression->right;
8851 /* The type of the right operand can be different for /= */
8852 if (is_type_integer(right->base.type) &&
8853 is_constant_expression(right) &&
8854 fold_constant(right) == 0) {
8855 warningf(&expression->base.source_position, "division by zero");
8860 * Check the semantic restrictions for a div/mod expression.
8862 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8864 semantic_binexpr_arithmetic(expression);
8865 warn_div_by_zero(expression);
8868 static void warn_addsub_in_shift(const expression_t *const expr)
8870 if (expr->base.parenthesized)
8874 switch (expr->kind) {
8875 case EXPR_BINARY_ADD: op = '+'; break;
8876 case EXPR_BINARY_SUB: op = '-'; break;
8880 warningf(&expr->base.source_position,
8881 "suggest parentheses around '%c' inside shift", op);
8884 static void semantic_shift_op(binary_expression_t *expression)
8886 expression_t *const left = expression->left;
8887 expression_t *const right = expression->right;
8888 type_t *const orig_type_left = left->base.type;
8889 type_t *const orig_type_right = right->base.type;
8890 type_t * type_left = skip_typeref(orig_type_left);
8891 type_t * type_right = skip_typeref(orig_type_right);
8893 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8894 /* TODO: improve error message */
8895 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8896 errorf(&expression->base.source_position,
8897 "operands of shift operation must have integer types");
8902 if (warning.parentheses) {
8903 warn_addsub_in_shift(left);
8904 warn_addsub_in_shift(right);
8907 type_left = promote_integer(type_left);
8908 type_right = promote_integer(type_right);
8910 expression->left = create_implicit_cast(left, type_left);
8911 expression->right = create_implicit_cast(right, type_right);
8912 expression->base.type = type_left;
8915 static void semantic_add(binary_expression_t *expression)
8917 expression_t *const left = expression->left;
8918 expression_t *const right = expression->right;
8919 type_t *const orig_type_left = left->base.type;
8920 type_t *const orig_type_right = right->base.type;
8921 type_t *const type_left = skip_typeref(orig_type_left);
8922 type_t *const type_right = skip_typeref(orig_type_right);
8925 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8926 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8927 expression->left = create_implicit_cast(left, arithmetic_type);
8928 expression->right = create_implicit_cast(right, arithmetic_type);
8929 expression->base.type = arithmetic_type;
8930 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8931 check_pointer_arithmetic(&expression->base.source_position,
8932 type_left, orig_type_left);
8933 expression->base.type = type_left;
8934 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8935 check_pointer_arithmetic(&expression->base.source_position,
8936 type_right, orig_type_right);
8937 expression->base.type = type_right;
8938 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8939 errorf(&expression->base.source_position,
8940 "invalid operands to binary + ('%T', '%T')",
8941 orig_type_left, orig_type_right);
8945 static void semantic_sub(binary_expression_t *expression)
8947 expression_t *const left = expression->left;
8948 expression_t *const right = expression->right;
8949 type_t *const orig_type_left = left->base.type;
8950 type_t *const orig_type_right = right->base.type;
8951 type_t *const type_left = skip_typeref(orig_type_left);
8952 type_t *const type_right = skip_typeref(orig_type_right);
8953 source_position_t const *const pos = &expression->base.source_position;
8956 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8957 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8958 expression->left = create_implicit_cast(left, arithmetic_type);
8959 expression->right = create_implicit_cast(right, arithmetic_type);
8960 expression->base.type = arithmetic_type;
8961 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8962 check_pointer_arithmetic(&expression->base.source_position,
8963 type_left, orig_type_left);
8964 expression->base.type = type_left;
8965 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8966 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8967 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8968 if (!types_compatible(unqual_left, unqual_right)) {
8970 "subtracting pointers to incompatible types '%T' and '%T'",
8971 orig_type_left, orig_type_right);
8972 } else if (!is_type_object(unqual_left)) {
8973 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8974 errorf(pos, "subtracting pointers to non-object types '%T'",
8976 } else if (warning.other) {
8977 warningf(pos, "subtracting pointers to void");
8980 expression->base.type = type_ptrdiff_t;
8981 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8982 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8983 orig_type_left, orig_type_right);
8987 static void warn_string_literal_address(expression_t const* expr)
8989 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8990 expr = expr->unary.value;
8991 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8993 expr = expr->unary.value;
8996 if (expr->kind == EXPR_STRING_LITERAL ||
8997 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8998 warningf(&expr->base.source_position,
8999 "comparison with string literal results in unspecified behaviour");
9003 static void warn_comparison_in_comparison(const expression_t *const expr)
9005 if (expr->base.parenthesized)
9007 switch (expr->base.kind) {
9008 case EXPR_BINARY_LESS:
9009 case EXPR_BINARY_GREATER:
9010 case EXPR_BINARY_LESSEQUAL:
9011 case EXPR_BINARY_GREATEREQUAL:
9012 case EXPR_BINARY_NOTEQUAL:
9013 case EXPR_BINARY_EQUAL:
9014 warningf(&expr->base.source_position,
9015 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9022 static bool maybe_negative(expression_t const *const expr)
9025 !is_constant_expression(expr) ||
9026 fold_constant(expr) < 0;
9030 * Check the semantics of comparison expressions.
9032 * @param expression The expression to check.
9034 static void semantic_comparison(binary_expression_t *expression)
9036 expression_t *left = expression->left;
9037 expression_t *right = expression->right;
9039 if (warning.address) {
9040 warn_string_literal_address(left);
9041 warn_string_literal_address(right);
9043 expression_t const* const func_left = get_reference_address(left);
9044 if (func_left != NULL && is_null_pointer_constant(right)) {
9045 warningf(&expression->base.source_position,
9046 "the address of '%Y' will never be NULL",
9047 func_left->reference.entity->base.symbol);
9050 expression_t const* const func_right = get_reference_address(right);
9051 if (func_right != NULL && is_null_pointer_constant(right)) {
9052 warningf(&expression->base.source_position,
9053 "the address of '%Y' will never be NULL",
9054 func_right->reference.entity->base.symbol);
9058 if (warning.parentheses) {
9059 warn_comparison_in_comparison(left);
9060 warn_comparison_in_comparison(right);
9063 type_t *orig_type_left = left->base.type;
9064 type_t *orig_type_right = right->base.type;
9065 type_t *type_left = skip_typeref(orig_type_left);
9066 type_t *type_right = skip_typeref(orig_type_right);
9068 /* TODO non-arithmetic types */
9069 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9070 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9072 /* test for signed vs unsigned compares */
9073 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9074 bool const signed_left = is_type_signed(type_left);
9075 bool const signed_right = is_type_signed(type_right);
9076 if (signed_left != signed_right) {
9077 /* FIXME long long needs better const folding magic */
9078 /* TODO check whether constant value can be represented by other type */
9079 if ((signed_left && maybe_negative(left)) ||
9080 (signed_right && maybe_negative(right))) {
9081 warningf(&expression->base.source_position,
9082 "comparison between signed and unsigned");
9087 expression->left = create_implicit_cast(left, arithmetic_type);
9088 expression->right = create_implicit_cast(right, arithmetic_type);
9089 expression->base.type = arithmetic_type;
9090 if (warning.float_equal &&
9091 (expression->base.kind == EXPR_BINARY_EQUAL ||
9092 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9093 is_type_float(arithmetic_type)) {
9094 warningf(&expression->base.source_position,
9095 "comparing floating point with == or != is unsafe");
9097 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9098 /* TODO check compatibility */
9099 } else if (is_type_pointer(type_left)) {
9100 expression->right = create_implicit_cast(right, type_left);
9101 } else if (is_type_pointer(type_right)) {
9102 expression->left = create_implicit_cast(left, type_right);
9103 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9104 type_error_incompatible("invalid operands in comparison",
9105 &expression->base.source_position,
9106 type_left, type_right);
9108 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9112 * Checks if a compound type has constant fields.
9114 static bool has_const_fields(const compound_type_t *type)
9116 compound_t *compound = type->compound;
9117 entity_t *entry = compound->members.entities;
9119 for (; entry != NULL; entry = entry->base.next) {
9120 if (!is_declaration(entry))
9123 const type_t *decl_type = skip_typeref(entry->declaration.type);
9124 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9131 static bool is_valid_assignment_lhs(expression_t const* const left)
9133 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9134 type_t *const type_left = skip_typeref(orig_type_left);
9136 if (!is_lvalue(left)) {
9137 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9142 if (left->kind == EXPR_REFERENCE
9143 && left->reference.entity->kind == ENTITY_FUNCTION) {
9144 errorf(HERE, "cannot assign to function '%E'", left);
9148 if (is_type_array(type_left)) {
9149 errorf(HERE, "cannot assign to array '%E'", left);
9152 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9153 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9157 if (is_type_incomplete(type_left)) {
9158 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9159 left, orig_type_left);
9162 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9163 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9164 left, orig_type_left);
9171 static void semantic_arithmetic_assign(binary_expression_t *expression)
9173 expression_t *left = expression->left;
9174 expression_t *right = expression->right;
9175 type_t *orig_type_left = left->base.type;
9176 type_t *orig_type_right = right->base.type;
9178 if (!is_valid_assignment_lhs(left))
9181 type_t *type_left = skip_typeref(orig_type_left);
9182 type_t *type_right = skip_typeref(orig_type_right);
9184 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9185 /* TODO: improve error message */
9186 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9187 errorf(&expression->base.source_position,
9188 "operation needs arithmetic types");
9193 /* combined instructions are tricky. We can't create an implicit cast on
9194 * the left side, because we need the uncasted form for the store.
9195 * The ast2firm pass has to know that left_type must be right_type
9196 * for the arithmetic operation and create a cast by itself */
9197 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9198 expression->right = create_implicit_cast(right, arithmetic_type);
9199 expression->base.type = type_left;
9202 static void semantic_divmod_assign(binary_expression_t *expression)
9204 semantic_arithmetic_assign(expression);
9205 warn_div_by_zero(expression);
9208 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9210 expression_t *const left = expression->left;
9211 expression_t *const right = expression->right;
9212 type_t *const orig_type_left = left->base.type;
9213 type_t *const orig_type_right = right->base.type;
9214 type_t *const type_left = skip_typeref(orig_type_left);
9215 type_t *const type_right = skip_typeref(orig_type_right);
9217 if (!is_valid_assignment_lhs(left))
9220 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9221 /* combined instructions are tricky. We can't create an implicit cast on
9222 * the left side, because we need the uncasted form for the store.
9223 * The ast2firm pass has to know that left_type must be right_type
9224 * for the arithmetic operation and create a cast by itself */
9225 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9226 expression->right = create_implicit_cast(right, arithmetic_type);
9227 expression->base.type = type_left;
9228 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9229 check_pointer_arithmetic(&expression->base.source_position,
9230 type_left, orig_type_left);
9231 expression->base.type = type_left;
9232 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9233 errorf(&expression->base.source_position,
9234 "incompatible types '%T' and '%T' in assignment",
9235 orig_type_left, orig_type_right);
9239 static void warn_logical_and_within_or(const expression_t *const expr)
9241 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9243 if (expr->base.parenthesized)
9245 warningf(&expr->base.source_position,
9246 "suggest parentheses around && within ||");
9250 * Check the semantic restrictions of a logical expression.
9252 static void semantic_logical_op(binary_expression_t *expression)
9254 /* §6.5.13:2 Each of the operands shall have scalar type.
9255 * §6.5.14:2 Each of the operands shall have scalar type. */
9256 semantic_condition(expression->left, "left operand of logical operator");
9257 semantic_condition(expression->right, "right operand of logical operator");
9258 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9259 warning.parentheses) {
9260 warn_logical_and_within_or(expression->left);
9261 warn_logical_and_within_or(expression->right);
9263 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9267 * Check the semantic restrictions of a binary assign expression.
9269 static void semantic_binexpr_assign(binary_expression_t *expression)
9271 expression_t *left = expression->left;
9272 type_t *orig_type_left = left->base.type;
9274 if (!is_valid_assignment_lhs(left))
9277 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9278 report_assign_error(error, orig_type_left, expression->right,
9279 "assignment", &left->base.source_position);
9280 expression->right = create_implicit_cast(expression->right, orig_type_left);
9281 expression->base.type = orig_type_left;
9285 * Determine if the outermost operation (or parts thereof) of the given
9286 * expression has no effect in order to generate a warning about this fact.
9287 * Therefore in some cases this only examines some of the operands of the
9288 * expression (see comments in the function and examples below).
9290 * f() + 23; // warning, because + has no effect
9291 * x || f(); // no warning, because x controls execution of f()
9292 * x ? y : f(); // warning, because y has no effect
9293 * (void)x; // no warning to be able to suppress the warning
9294 * This function can NOT be used for an "expression has definitely no effect"-
9296 static bool expression_has_effect(const expression_t *const expr)
9298 switch (expr->kind) {
9299 case EXPR_UNKNOWN: break;
9300 case EXPR_INVALID: return true; /* do NOT warn */
9301 case EXPR_REFERENCE: return false;
9302 case EXPR_REFERENCE_ENUM_VALUE: return false;
9303 /* suppress the warning for microsoft __noop operations */
9304 case EXPR_CONST: return expr->conste.is_ms_noop;
9305 case EXPR_CHARACTER_CONSTANT: return false;
9306 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9307 case EXPR_STRING_LITERAL: return false;
9308 case EXPR_WIDE_STRING_LITERAL: return false;
9309 case EXPR_LABEL_ADDRESS: return false;
9312 const call_expression_t *const call = &expr->call;
9313 if (call->function->kind != EXPR_REFERENCE)
9316 switch (call->function->reference.entity->function.btk) {
9317 /* FIXME: which builtins have no effect? */
9318 default: return true;
9322 /* Generate the warning if either the left or right hand side of a
9323 * conditional expression has no effect */
9324 case EXPR_CONDITIONAL: {
9325 conditional_expression_t const *const cond = &expr->conditional;
9326 expression_t const *const t = cond->true_expression;
9328 (t == NULL || expression_has_effect(t)) &&
9329 expression_has_effect(cond->false_expression);
9332 case EXPR_SELECT: return false;
9333 case EXPR_ARRAY_ACCESS: return false;
9334 case EXPR_SIZEOF: return false;
9335 case EXPR_CLASSIFY_TYPE: return false;
9336 case EXPR_ALIGNOF: return false;
9338 case EXPR_FUNCNAME: return false;
9339 case EXPR_BUILTIN_CONSTANT_P: return false;
9340 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9341 case EXPR_OFFSETOF: return false;
9342 case EXPR_VA_START: return true;
9343 case EXPR_VA_ARG: return true;
9344 case EXPR_STATEMENT: return true; // TODO
9345 case EXPR_COMPOUND_LITERAL: return false;
9347 case EXPR_UNARY_NEGATE: return false;
9348 case EXPR_UNARY_PLUS: return false;
9349 case EXPR_UNARY_BITWISE_NEGATE: return false;
9350 case EXPR_UNARY_NOT: return false;
9351 case EXPR_UNARY_DEREFERENCE: return false;
9352 case EXPR_UNARY_TAKE_ADDRESS: return false;
9353 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9354 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9355 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9356 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9358 /* Treat void casts as if they have an effect in order to being able to
9359 * suppress the warning */
9360 case EXPR_UNARY_CAST: {
9361 type_t *const type = skip_typeref(expr->base.type);
9362 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9365 case EXPR_UNARY_CAST_IMPLICIT: return true;
9366 case EXPR_UNARY_ASSUME: return true;
9367 case EXPR_UNARY_DELETE: return true;
9368 case EXPR_UNARY_DELETE_ARRAY: return true;
9369 case EXPR_UNARY_THROW: return true;
9371 case EXPR_BINARY_ADD: return false;
9372 case EXPR_BINARY_SUB: return false;
9373 case EXPR_BINARY_MUL: return false;
9374 case EXPR_BINARY_DIV: return false;
9375 case EXPR_BINARY_MOD: return false;
9376 case EXPR_BINARY_EQUAL: return false;
9377 case EXPR_BINARY_NOTEQUAL: return false;
9378 case EXPR_BINARY_LESS: return false;
9379 case EXPR_BINARY_LESSEQUAL: return false;
9380 case EXPR_BINARY_GREATER: return false;
9381 case EXPR_BINARY_GREATEREQUAL: return false;
9382 case EXPR_BINARY_BITWISE_AND: return false;
9383 case EXPR_BINARY_BITWISE_OR: return false;
9384 case EXPR_BINARY_BITWISE_XOR: return false;
9385 case EXPR_BINARY_SHIFTLEFT: return false;
9386 case EXPR_BINARY_SHIFTRIGHT: return false;
9387 case EXPR_BINARY_ASSIGN: return true;
9388 case EXPR_BINARY_MUL_ASSIGN: return true;
9389 case EXPR_BINARY_DIV_ASSIGN: return true;
9390 case EXPR_BINARY_MOD_ASSIGN: return true;
9391 case EXPR_BINARY_ADD_ASSIGN: return true;
9392 case EXPR_BINARY_SUB_ASSIGN: return true;
9393 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9394 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9395 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9396 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9397 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9399 /* Only examine the right hand side of && and ||, because the left hand
9400 * side already has the effect of controlling the execution of the right
9402 case EXPR_BINARY_LOGICAL_AND:
9403 case EXPR_BINARY_LOGICAL_OR:
9404 /* Only examine the right hand side of a comma expression, because the left
9405 * hand side has a separate warning */
9406 case EXPR_BINARY_COMMA:
9407 return expression_has_effect(expr->binary.right);
9409 case EXPR_BINARY_ISGREATER: return false;
9410 case EXPR_BINARY_ISGREATEREQUAL: return false;
9411 case EXPR_BINARY_ISLESS: return false;
9412 case EXPR_BINARY_ISLESSEQUAL: return false;
9413 case EXPR_BINARY_ISLESSGREATER: return false;
9414 case EXPR_BINARY_ISUNORDERED: return false;
9417 internal_errorf(HERE, "unexpected expression");
9420 static void semantic_comma(binary_expression_t *expression)
9422 if (warning.unused_value) {
9423 const expression_t *const left = expression->left;
9424 if (!expression_has_effect(left)) {
9425 warningf(&left->base.source_position,
9426 "left-hand operand of comma expression has no effect");
9429 expression->base.type = expression->right->base.type;
9433 * @param prec_r precedence of the right operand
9435 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9436 static expression_t *parse_##binexpression_type(expression_t *left) \
9438 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9439 binexpr->binary.left = left; \
9442 expression_t *right = parse_sub_expression(prec_r); \
9444 binexpr->binary.right = right; \
9445 sfunc(&binexpr->binary); \
9450 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9451 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9452 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9453 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9454 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9455 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9456 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9457 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9458 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9459 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9460 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9461 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9462 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9463 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9464 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9465 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9466 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9467 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9468 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9469 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9470 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9471 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9472 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9473 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9474 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9475 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9476 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9477 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9478 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9479 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9482 static expression_t *parse_sub_expression(precedence_t precedence)
9484 if (token.type < 0) {
9485 return expected_expression_error();
9488 expression_parser_function_t *parser
9489 = &expression_parsers[token.type];
9490 source_position_t source_position = token.source_position;
9493 if (parser->parser != NULL) {
9494 left = parser->parser();
9496 left = parse_primary_expression();
9498 assert(left != NULL);
9499 left->base.source_position = source_position;
9502 if (token.type < 0) {
9503 return expected_expression_error();
9506 parser = &expression_parsers[token.type];
9507 if (parser->infix_parser == NULL)
9509 if (parser->infix_precedence < precedence)
9512 left = parser->infix_parser(left);
9514 assert(left != NULL);
9515 assert(left->kind != EXPR_UNKNOWN);
9516 left->base.source_position = source_position;
9523 * Parse an expression.
9525 static expression_t *parse_expression(void)
9527 return parse_sub_expression(PREC_EXPRESSION);
9531 * Register a parser for a prefix-like operator.
9533 * @param parser the parser function
9534 * @param token_type the token type of the prefix token
9536 static void register_expression_parser(parse_expression_function parser,
9539 expression_parser_function_t *entry = &expression_parsers[token_type];
9541 if (entry->parser != NULL) {
9542 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9543 panic("trying to register multiple expression parsers for a token");
9545 entry->parser = parser;
9549 * Register a parser for an infix operator with given precedence.
9551 * @param parser the parser function
9552 * @param token_type the token type of the infix operator
9553 * @param precedence the precedence of the operator
9555 static void register_infix_parser(parse_expression_infix_function parser,
9556 int token_type, precedence_t precedence)
9558 expression_parser_function_t *entry = &expression_parsers[token_type];
9560 if (entry->infix_parser != NULL) {
9561 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9562 panic("trying to register multiple infix expression parsers for a "
9565 entry->infix_parser = parser;
9566 entry->infix_precedence = precedence;
9570 * Initialize the expression parsers.
9572 static void init_expression_parsers(void)
9574 memset(&expression_parsers, 0, sizeof(expression_parsers));
9576 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9577 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9578 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9579 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9580 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9581 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9582 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9583 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9584 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9585 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9586 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9587 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9588 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9589 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9590 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9591 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9592 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9593 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9594 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9595 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9596 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9597 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9598 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9599 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9600 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9601 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9602 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9603 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9604 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9605 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9606 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9607 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9608 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9609 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9610 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9611 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9612 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9614 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9615 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9616 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9617 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9618 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9619 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9620 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9621 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9622 register_expression_parser(parse_sizeof, T_sizeof);
9623 register_expression_parser(parse_alignof, T___alignof__);
9624 register_expression_parser(parse_extension, T___extension__);
9625 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9626 register_expression_parser(parse_delete, T_delete);
9627 register_expression_parser(parse_throw, T_throw);
9631 * Parse a asm statement arguments specification.
9633 static asm_argument_t *parse_asm_arguments(bool is_out)
9635 asm_argument_t *result = NULL;
9636 asm_argument_t **anchor = &result;
9638 while (token.type == T_STRING_LITERAL || token.type == '[') {
9639 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9640 memset(argument, 0, sizeof(argument[0]));
9642 if (token.type == '[') {
9644 if (token.type != T_IDENTIFIER) {
9645 parse_error_expected("while parsing asm argument",
9646 T_IDENTIFIER, NULL);
9649 argument->symbol = token.v.symbol;
9651 expect(']', end_error);
9654 argument->constraints = parse_string_literals();
9655 expect('(', end_error);
9656 add_anchor_token(')');
9657 expression_t *expression = parse_expression();
9658 rem_anchor_token(')');
9660 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9661 * change size or type representation (e.g. int -> long is ok, but
9662 * int -> float is not) */
9663 if (expression->kind == EXPR_UNARY_CAST) {
9664 type_t *const type = expression->base.type;
9665 type_kind_t const kind = type->kind;
9666 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9669 if (kind == TYPE_ATOMIC) {
9670 atomic_type_kind_t const akind = type->atomic.akind;
9671 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9672 size = get_atomic_type_size(akind);
9674 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9675 size = get_atomic_type_size(get_intptr_kind());
9679 expression_t *const value = expression->unary.value;
9680 type_t *const value_type = value->base.type;
9681 type_kind_t const value_kind = value_type->kind;
9683 unsigned value_flags;
9684 unsigned value_size;
9685 if (value_kind == TYPE_ATOMIC) {
9686 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9687 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9688 value_size = get_atomic_type_size(value_akind);
9689 } else if (value_kind == TYPE_POINTER) {
9690 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9691 value_size = get_atomic_type_size(get_intptr_kind());
9696 if (value_flags != flags || value_size != size)
9700 } while (expression->kind == EXPR_UNARY_CAST);
9704 if (!is_lvalue(expression)) {
9705 errorf(&expression->base.source_position,
9706 "asm output argument is not an lvalue");
9709 if (argument->constraints.begin[0] == '+')
9710 mark_vars_read(expression, NULL);
9712 mark_vars_read(expression, NULL);
9714 argument->expression = expression;
9715 expect(')', end_error);
9717 set_address_taken(expression, true);
9720 anchor = &argument->next;
9722 if (token.type != ',')
9733 * Parse a asm statement clobber specification.
9735 static asm_clobber_t *parse_asm_clobbers(void)
9737 asm_clobber_t *result = NULL;
9738 asm_clobber_t *last = NULL;
9740 while (token.type == T_STRING_LITERAL) {
9741 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9742 clobber->clobber = parse_string_literals();
9745 last->next = clobber;
9751 if (token.type != ',')
9760 * Parse an asm statement.
9762 static statement_t *parse_asm_statement(void)
9764 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9765 asm_statement_t *asm_statement = &statement->asms;
9769 if (token.type == T_volatile) {
9771 asm_statement->is_volatile = true;
9774 expect('(', end_error);
9775 add_anchor_token(')');
9776 add_anchor_token(':');
9777 asm_statement->asm_text = parse_string_literals();
9779 if (token.type != ':') {
9780 rem_anchor_token(':');
9785 asm_statement->outputs = parse_asm_arguments(true);
9786 if (token.type != ':') {
9787 rem_anchor_token(':');
9792 asm_statement->inputs = parse_asm_arguments(false);
9793 if (token.type != ':') {
9794 rem_anchor_token(':');
9797 rem_anchor_token(':');
9800 asm_statement->clobbers = parse_asm_clobbers();
9803 rem_anchor_token(')');
9804 expect(')', end_error);
9805 expect(';', end_error);
9807 if (asm_statement->outputs == NULL) {
9808 /* GCC: An 'asm' instruction without any output operands will be treated
9809 * identically to a volatile 'asm' instruction. */
9810 asm_statement->is_volatile = true;
9815 return create_invalid_statement();
9819 * Parse a case statement.
9821 static statement_t *parse_case_statement(void)
9823 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9824 source_position_t *const pos = &statement->base.source_position;
9828 expression_t *const expression = parse_expression();
9829 statement->case_label.expression = expression;
9830 if (!is_constant_expression(expression)) {
9831 /* This check does not prevent the error message in all cases of an
9832 * prior error while parsing the expression. At least it catches the
9833 * common case of a mistyped enum entry. */
9834 if (is_type_valid(skip_typeref(expression->base.type))) {
9835 errorf(pos, "case label does not reduce to an integer constant");
9837 statement->case_label.is_bad = true;
9839 long const val = fold_constant(expression);
9840 statement->case_label.first_case = val;
9841 statement->case_label.last_case = val;
9845 if (token.type == T_DOTDOTDOT) {
9847 expression_t *const end_range = parse_expression();
9848 statement->case_label.end_range = end_range;
9849 if (!is_constant_expression(end_range)) {
9850 /* This check does not prevent the error message in all cases of an
9851 * prior error while parsing the expression. At least it catches the
9852 * common case of a mistyped enum entry. */
9853 if (is_type_valid(skip_typeref(end_range->base.type))) {
9854 errorf(pos, "case range does not reduce to an integer constant");
9856 statement->case_label.is_bad = true;
9858 long const val = fold_constant(end_range);
9859 statement->case_label.last_case = val;
9861 if (warning.other && val < statement->case_label.first_case) {
9862 statement->case_label.is_empty_range = true;
9863 warningf(pos, "empty range specified");
9869 PUSH_PARENT(statement);
9871 expect(':', end_error);
9874 if (current_switch != NULL) {
9875 if (! statement->case_label.is_bad) {
9876 /* Check for duplicate case values */
9877 case_label_statement_t *c = &statement->case_label;
9878 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9879 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9882 if (c->last_case < l->first_case || c->first_case > l->last_case)
9885 errorf(pos, "duplicate case value (previously used %P)",
9886 &l->base.source_position);
9890 /* link all cases into the switch statement */
9891 if (current_switch->last_case == NULL) {
9892 current_switch->first_case = &statement->case_label;
9894 current_switch->last_case->next = &statement->case_label;
9896 current_switch->last_case = &statement->case_label;
9898 errorf(pos, "case label not within a switch statement");
9901 statement_t *const inner_stmt = parse_statement();
9902 statement->case_label.statement = inner_stmt;
9903 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9904 errorf(&inner_stmt->base.source_position, "declaration after case label");
9912 * Parse a default statement.
9914 static statement_t *parse_default_statement(void)
9916 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9920 PUSH_PARENT(statement);
9922 expect(':', end_error);
9923 if (current_switch != NULL) {
9924 const case_label_statement_t *def_label = current_switch->default_label;
9925 if (def_label != NULL) {
9926 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9927 &def_label->base.source_position);
9929 current_switch->default_label = &statement->case_label;
9931 /* link all cases into the switch statement */
9932 if (current_switch->last_case == NULL) {
9933 current_switch->first_case = &statement->case_label;
9935 current_switch->last_case->next = &statement->case_label;
9937 current_switch->last_case = &statement->case_label;
9940 errorf(&statement->base.source_position,
9941 "'default' label not within a switch statement");
9944 statement_t *const inner_stmt = parse_statement();
9945 statement->case_label.statement = inner_stmt;
9946 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9947 errorf(&inner_stmt->base.source_position, "declaration after default label");
9954 return create_invalid_statement();
9958 * Parse a label statement.
9960 static statement_t *parse_label_statement(void)
9962 assert(token.type == T_IDENTIFIER);
9963 symbol_t *symbol = token.v.symbol;
9964 label_t *label = get_label(symbol);
9966 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9967 statement->label.label = label;
9971 PUSH_PARENT(statement);
9973 /* if statement is already set then the label is defined twice,
9974 * otherwise it was just mentioned in a goto/local label declaration so far
9976 if (label->statement != NULL) {
9977 errorf(HERE, "duplicate label '%Y' (declared %P)",
9978 symbol, &label->base.source_position);
9980 label->base.source_position = token.source_position;
9981 label->statement = statement;
9986 if (token.type == '}') {
9987 /* TODO only warn? */
9988 if (warning.other && false) {
9989 warningf(HERE, "label at end of compound statement");
9990 statement->label.statement = create_empty_statement();
9992 errorf(HERE, "label at end of compound statement");
9993 statement->label.statement = create_invalid_statement();
9995 } else if (token.type == ';') {
9996 /* Eat an empty statement here, to avoid the warning about an empty
9997 * statement after a label. label:; is commonly used to have a label
9998 * before a closing brace. */
9999 statement->label.statement = create_empty_statement();
10002 statement_t *const inner_stmt = parse_statement();
10003 statement->label.statement = inner_stmt;
10004 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10005 errorf(&inner_stmt->base.source_position, "declaration after label");
10009 /* remember the labels in a list for later checking */
10010 *label_anchor = &statement->label;
10011 label_anchor = &statement->label.next;
10018 * Parse an if statement.
10020 static statement_t *parse_if(void)
10022 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10026 PUSH_PARENT(statement);
10028 add_anchor_token('{');
10030 expect('(', end_error);
10031 add_anchor_token(')');
10032 expression_t *const expr = parse_expression();
10033 statement->ifs.condition = expr;
10034 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10036 semantic_condition(expr, "condition of 'if'-statment");
10037 mark_vars_read(expr, NULL);
10038 rem_anchor_token(')');
10039 expect(')', end_error);
10042 rem_anchor_token('{');
10044 add_anchor_token(T_else);
10045 statement_t *const true_stmt = parse_statement();
10046 statement->ifs.true_statement = true_stmt;
10047 rem_anchor_token(T_else);
10049 if (token.type == T_else) {
10051 statement->ifs.false_statement = parse_statement();
10052 } else if (warning.parentheses &&
10053 true_stmt->kind == STATEMENT_IF &&
10054 true_stmt->ifs.false_statement != NULL) {
10055 warningf(&true_stmt->base.source_position,
10056 "suggest explicit braces to avoid ambiguous 'else'");
10064 * Check that all enums are handled in a switch.
10066 * @param statement the switch statement to check
10068 static void check_enum_cases(const switch_statement_t *statement)
10070 const type_t *type = skip_typeref(statement->expression->base.type);
10071 if (! is_type_enum(type))
10073 const enum_type_t *enumt = &type->enumt;
10075 /* if we have a default, no warnings */
10076 if (statement->default_label != NULL)
10079 /* FIXME: calculation of value should be done while parsing */
10080 /* TODO: quadratic algorithm here. Change to an n log n one */
10081 long last_value = -1;
10082 const entity_t *entry = enumt->enume->base.next;
10083 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10084 entry = entry->base.next) {
10085 const expression_t *expression = entry->enum_value.value;
10086 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10087 bool found = false;
10088 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10089 if (l->expression == NULL)
10091 if (l->first_case <= value && value <= l->last_case) {
10097 warningf(&statement->base.source_position,
10098 "enumeration value '%Y' not handled in switch",
10099 entry->base.symbol);
10101 last_value = value;
10106 * Parse a switch statement.
10108 static statement_t *parse_switch(void)
10110 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10114 PUSH_PARENT(statement);
10116 expect('(', end_error);
10117 add_anchor_token(')');
10118 expression_t *const expr = parse_expression();
10119 mark_vars_read(expr, NULL);
10120 type_t * type = skip_typeref(expr->base.type);
10121 if (is_type_integer(type)) {
10122 type = promote_integer(type);
10123 if (warning.traditional) {
10124 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10125 warningf(&expr->base.source_position,
10126 "'%T' switch expression not converted to '%T' in ISO C",
10130 } else if (is_type_valid(type)) {
10131 errorf(&expr->base.source_position,
10132 "switch quantity is not an integer, but '%T'", type);
10133 type = type_error_type;
10135 statement->switchs.expression = create_implicit_cast(expr, type);
10136 expect(')', end_error);
10137 rem_anchor_token(')');
10139 switch_statement_t *rem = current_switch;
10140 current_switch = &statement->switchs;
10141 statement->switchs.body = parse_statement();
10142 current_switch = rem;
10144 if (warning.switch_default &&
10145 statement->switchs.default_label == NULL) {
10146 warningf(&statement->base.source_position, "switch has no default case");
10148 if (warning.switch_enum)
10149 check_enum_cases(&statement->switchs);
10155 return create_invalid_statement();
10158 static statement_t *parse_loop_body(statement_t *const loop)
10160 statement_t *const rem = current_loop;
10161 current_loop = loop;
10163 statement_t *const body = parse_statement();
10165 current_loop = rem;
10170 * Parse a while statement.
10172 static statement_t *parse_while(void)
10174 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10178 PUSH_PARENT(statement);
10180 expect('(', end_error);
10181 add_anchor_token(')');
10182 expression_t *const cond = parse_expression();
10183 statement->whiles.condition = cond;
10184 /* §6.8.5:2 The controlling expression of an iteration statement shall
10185 * have scalar type. */
10186 semantic_condition(cond, "condition of 'while'-statement");
10187 mark_vars_read(cond, NULL);
10188 rem_anchor_token(')');
10189 expect(')', end_error);
10191 statement->whiles.body = parse_loop_body(statement);
10197 return create_invalid_statement();
10201 * Parse a do statement.
10203 static statement_t *parse_do(void)
10205 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10209 PUSH_PARENT(statement);
10211 add_anchor_token(T_while);
10212 statement->do_while.body = parse_loop_body(statement);
10213 rem_anchor_token(T_while);
10215 expect(T_while, end_error);
10216 expect('(', end_error);
10217 add_anchor_token(')');
10218 expression_t *const cond = parse_expression();
10219 statement->do_while.condition = cond;
10220 /* §6.8.5:2 The controlling expression of an iteration statement shall
10221 * have scalar type. */
10222 semantic_condition(cond, "condition of 'do-while'-statement");
10223 mark_vars_read(cond, NULL);
10224 rem_anchor_token(')');
10225 expect(')', end_error);
10226 expect(';', end_error);
10232 return create_invalid_statement();
10236 * Parse a for statement.
10238 static statement_t *parse_for(void)
10240 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10244 expect('(', end_error1);
10245 add_anchor_token(')');
10247 PUSH_PARENT(statement);
10249 size_t const top = environment_top();
10250 scope_t *old_scope = scope_push(&statement->fors.scope);
10252 if (token.type == ';') {
10254 } else if (is_declaration_specifier(&token, false)) {
10255 parse_declaration(record_entity, DECL_FLAGS_NONE);
10257 add_anchor_token(';');
10258 expression_t *const init = parse_expression();
10259 statement->fors.initialisation = init;
10260 mark_vars_read(init, ENT_ANY);
10261 if (warning.unused_value && !expression_has_effect(init)) {
10262 warningf(&init->base.source_position,
10263 "initialisation of 'for'-statement has no effect");
10265 rem_anchor_token(';');
10266 expect(';', end_error2);
10269 if (token.type != ';') {
10270 add_anchor_token(';');
10271 expression_t *const cond = parse_expression();
10272 statement->fors.condition = cond;
10273 /* §6.8.5:2 The controlling expression of an iteration statement
10274 * shall have scalar type. */
10275 semantic_condition(cond, "condition of 'for'-statement");
10276 mark_vars_read(cond, NULL);
10277 rem_anchor_token(';');
10279 expect(';', end_error2);
10280 if (token.type != ')') {
10281 expression_t *const step = parse_expression();
10282 statement->fors.step = step;
10283 mark_vars_read(step, ENT_ANY);
10284 if (warning.unused_value && !expression_has_effect(step)) {
10285 warningf(&step->base.source_position,
10286 "step of 'for'-statement has no effect");
10289 expect(')', end_error2);
10290 rem_anchor_token(')');
10291 statement->fors.body = parse_loop_body(statement);
10293 assert(current_scope == &statement->fors.scope);
10294 scope_pop(old_scope);
10295 environment_pop_to(top);
10302 rem_anchor_token(')');
10303 assert(current_scope == &statement->fors.scope);
10304 scope_pop(old_scope);
10305 environment_pop_to(top);
10309 return create_invalid_statement();
10313 * Parse a goto statement.
10315 static statement_t *parse_goto(void)
10317 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10320 if (GNU_MODE && token.type == '*') {
10322 expression_t *expression = parse_expression();
10323 mark_vars_read(expression, NULL);
10325 /* Argh: although documentation says the expression must be of type void*,
10326 * gcc accepts anything that can be casted into void* without error */
10327 type_t *type = expression->base.type;
10329 if (type != type_error_type) {
10330 if (!is_type_pointer(type) && !is_type_integer(type)) {
10331 errorf(&expression->base.source_position,
10332 "cannot convert to a pointer type");
10333 } else if (warning.other && type != type_void_ptr) {
10334 warningf(&expression->base.source_position,
10335 "type of computed goto expression should be 'void*' not '%T'", type);
10337 expression = create_implicit_cast(expression, type_void_ptr);
10340 statement->gotos.expression = expression;
10342 if (token.type != T_IDENTIFIER) {
10344 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10346 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10347 eat_until_anchor();
10350 symbol_t *symbol = token.v.symbol;
10353 statement->gotos.label = get_label(symbol);
10356 /* remember the goto's in a list for later checking */
10357 *goto_anchor = &statement->gotos;
10358 goto_anchor = &statement->gotos.next;
10360 expect(';', end_error);
10364 return create_invalid_statement();
10368 * Parse a continue statement.
10370 static statement_t *parse_continue(void)
10372 if (current_loop == NULL) {
10373 errorf(HERE, "continue statement not within loop");
10376 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10379 expect(';', end_error);
10386 * Parse a break statement.
10388 static statement_t *parse_break(void)
10390 if (current_switch == NULL && current_loop == NULL) {
10391 errorf(HERE, "break statement not within loop or switch");
10394 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10397 expect(';', end_error);
10404 * Parse a __leave statement.
10406 static statement_t *parse_leave_statement(void)
10408 if (current_try == NULL) {
10409 errorf(HERE, "__leave statement not within __try");
10412 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10415 expect(';', end_error);
10422 * Check if a given entity represents a local variable.
10424 static bool is_local_variable(const entity_t *entity)
10426 if (entity->kind != ENTITY_VARIABLE)
10429 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10430 case STORAGE_CLASS_AUTO:
10431 case STORAGE_CLASS_REGISTER: {
10432 const type_t *type = skip_typeref(entity->declaration.type);
10433 if (is_type_function(type)) {
10445 * Check if a given expression represents a local variable.
10447 static bool expression_is_local_variable(const expression_t *expression)
10449 if (expression->base.kind != EXPR_REFERENCE) {
10452 const entity_t *entity = expression->reference.entity;
10453 return is_local_variable(entity);
10457 * Check if a given expression represents a local variable and
10458 * return its declaration then, else return NULL.
10460 entity_t *expression_is_variable(const expression_t *expression)
10462 if (expression->base.kind != EXPR_REFERENCE) {
10465 entity_t *entity = expression->reference.entity;
10466 if (entity->kind != ENTITY_VARIABLE)
10473 * Parse a return statement.
10475 static statement_t *parse_return(void)
10479 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10481 expression_t *return_value = NULL;
10482 if (token.type != ';') {
10483 return_value = parse_expression();
10484 mark_vars_read(return_value, NULL);
10487 const type_t *const func_type = skip_typeref(current_function->base.type);
10488 assert(is_type_function(func_type));
10489 type_t *const return_type = skip_typeref(func_type->function.return_type);
10491 source_position_t const *const pos = &statement->base.source_position;
10492 if (return_value != NULL) {
10493 type_t *return_value_type = skip_typeref(return_value->base.type);
10495 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10496 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10497 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10498 /* Only warn in C mode, because GCC does the same */
10499 if (c_mode & _CXX || strict_mode) {
10501 "'return' with a value, in function returning 'void'");
10502 } else if (warning.other) {
10504 "'return' with a value, in function returning 'void'");
10506 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10507 /* Only warn in C mode, because GCC does the same */
10510 "'return' with expression in function return 'void'");
10511 } else if (warning.other) {
10513 "'return' with expression in function return 'void'");
10517 assign_error_t error = semantic_assign(return_type, return_value);
10518 report_assign_error(error, return_type, return_value, "'return'",
10521 return_value = create_implicit_cast(return_value, return_type);
10522 /* check for returning address of a local var */
10523 if (warning.other && return_value != NULL
10524 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10525 const expression_t *expression = return_value->unary.value;
10526 if (expression_is_local_variable(expression)) {
10527 warningf(pos, "function returns address of local variable");
10530 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10531 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10532 if (c_mode & _CXX || strict_mode) {
10534 "'return' without value, in function returning non-void");
10537 "'return' without value, in function returning non-void");
10540 statement->returns.value = return_value;
10542 expect(';', end_error);
10549 * Parse a declaration statement.
10551 static statement_t *parse_declaration_statement(void)
10553 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10555 entity_t *before = current_scope->last_entity;
10557 parse_external_declaration();
10559 parse_declaration(record_entity, DECL_FLAGS_NONE);
10562 declaration_statement_t *const decl = &statement->declaration;
10563 entity_t *const begin =
10564 before != NULL ? before->base.next : current_scope->entities;
10565 decl->declarations_begin = begin;
10566 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10572 * Parse an expression statement, ie. expr ';'.
10574 static statement_t *parse_expression_statement(void)
10576 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10578 expression_t *const expr = parse_expression();
10579 statement->expression.expression = expr;
10580 mark_vars_read(expr, ENT_ANY);
10582 expect(';', end_error);
10589 * Parse a microsoft __try { } __finally { } or
10590 * __try{ } __except() { }
10592 static statement_t *parse_ms_try_statment(void)
10594 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10597 PUSH_PARENT(statement);
10599 ms_try_statement_t *rem = current_try;
10600 current_try = &statement->ms_try;
10601 statement->ms_try.try_statement = parse_compound_statement(false);
10606 if (token.type == T___except) {
10608 expect('(', end_error);
10609 add_anchor_token(')');
10610 expression_t *const expr = parse_expression();
10611 mark_vars_read(expr, NULL);
10612 type_t * type = skip_typeref(expr->base.type);
10613 if (is_type_integer(type)) {
10614 type = promote_integer(type);
10615 } else if (is_type_valid(type)) {
10616 errorf(&expr->base.source_position,
10617 "__expect expression is not an integer, but '%T'", type);
10618 type = type_error_type;
10620 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10621 rem_anchor_token(')');
10622 expect(')', end_error);
10623 statement->ms_try.final_statement = parse_compound_statement(false);
10624 } else if (token.type == T__finally) {
10626 statement->ms_try.final_statement = parse_compound_statement(false);
10628 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10629 return create_invalid_statement();
10633 return create_invalid_statement();
10636 static statement_t *parse_empty_statement(void)
10638 if (warning.empty_statement) {
10639 warningf(HERE, "statement is empty");
10641 statement_t *const statement = create_empty_statement();
10646 static statement_t *parse_local_label_declaration(void)
10648 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10652 entity_t *begin = NULL, *end = NULL;
10655 if (token.type != T_IDENTIFIER) {
10656 parse_error_expected("while parsing local label declaration",
10657 T_IDENTIFIER, NULL);
10660 symbol_t *symbol = token.v.symbol;
10661 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10662 if (entity != NULL && entity->base.parent_scope == current_scope) {
10663 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10664 symbol, &entity->base.source_position);
10666 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10668 entity->base.parent_scope = current_scope;
10669 entity->base.namespc = NAMESPACE_LABEL;
10670 entity->base.source_position = token.source_position;
10671 entity->base.symbol = symbol;
10674 end->base.next = entity;
10679 environment_push(entity);
10683 if (token.type != ',')
10689 statement->declaration.declarations_begin = begin;
10690 statement->declaration.declarations_end = end;
10694 static void parse_namespace_definition(void)
10698 entity_t *entity = NULL;
10699 symbol_t *symbol = NULL;
10701 if (token.type == T_IDENTIFIER) {
10702 symbol = token.v.symbol;
10705 entity = get_entity(symbol, NAMESPACE_NORMAL);
10706 if (entity != NULL &&
10707 entity->kind != ENTITY_NAMESPACE &&
10708 entity->base.parent_scope == current_scope) {
10709 if (!is_error_entity(entity)) {
10710 error_redefined_as_different_kind(&token.source_position,
10711 entity, ENTITY_NAMESPACE);
10717 if (entity == NULL) {
10718 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10719 entity->base.symbol = symbol;
10720 entity->base.source_position = token.source_position;
10721 entity->base.namespc = NAMESPACE_NORMAL;
10722 entity->base.parent_scope = current_scope;
10725 if (token.type == '=') {
10726 /* TODO: parse namespace alias */
10727 panic("namespace alias definition not supported yet");
10730 environment_push(entity);
10731 append_entity(current_scope, entity);
10733 size_t const top = environment_top();
10734 scope_t *old_scope = scope_push(&entity->namespacee.members);
10736 expect('{', end_error);
10738 expect('}', end_error);
10741 assert(current_scope == &entity->namespacee.members);
10742 scope_pop(old_scope);
10743 environment_pop_to(top);
10747 * Parse a statement.
10748 * There's also parse_statement() which additionally checks for
10749 * "statement has no effect" warnings
10751 static statement_t *intern_parse_statement(void)
10753 statement_t *statement = NULL;
10755 /* declaration or statement */
10756 add_anchor_token(';');
10757 switch (token.type) {
10758 case T_IDENTIFIER: {
10759 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10760 if (la1_type == ':') {
10761 statement = parse_label_statement();
10762 } else if (is_typedef_symbol(token.v.symbol)) {
10763 statement = parse_declaration_statement();
10765 /* it's an identifier, the grammar says this must be an
10766 * expression statement. However it is common that users mistype
10767 * declaration types, so we guess a bit here to improve robustness
10768 * for incorrect programs */
10769 switch (la1_type) {
10772 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10773 goto expression_statment;
10778 statement = parse_declaration_statement();
10782 expression_statment:
10783 statement = parse_expression_statement();
10790 case T___extension__:
10791 /* This can be a prefix to a declaration or an expression statement.
10792 * We simply eat it now and parse the rest with tail recursion. */
10795 } while (token.type == T___extension__);
10796 bool old_gcc_extension = in_gcc_extension;
10797 in_gcc_extension = true;
10798 statement = intern_parse_statement();
10799 in_gcc_extension = old_gcc_extension;
10803 statement = parse_declaration_statement();
10807 statement = parse_local_label_declaration();
10810 case ';': statement = parse_empty_statement(); break;
10811 case '{': statement = parse_compound_statement(false); break;
10812 case T___leave: statement = parse_leave_statement(); break;
10813 case T___try: statement = parse_ms_try_statment(); break;
10814 case T_asm: statement = parse_asm_statement(); break;
10815 case T_break: statement = parse_break(); break;
10816 case T_case: statement = parse_case_statement(); break;
10817 case T_continue: statement = parse_continue(); break;
10818 case T_default: statement = parse_default_statement(); break;
10819 case T_do: statement = parse_do(); break;
10820 case T_for: statement = parse_for(); break;
10821 case T_goto: statement = parse_goto(); break;
10822 case T_if: statement = parse_if(); break;
10823 case T_return: statement = parse_return(); break;
10824 case T_switch: statement = parse_switch(); break;
10825 case T_while: statement = parse_while(); break;
10828 statement = parse_expression_statement();
10832 errorf(HERE, "unexpected token %K while parsing statement", &token);
10833 statement = create_invalid_statement();
10838 rem_anchor_token(';');
10840 assert(statement != NULL
10841 && statement->base.source_position.input_name != NULL);
10847 * parse a statement and emits "statement has no effect" warning if needed
10848 * (This is really a wrapper around intern_parse_statement with check for 1
10849 * single warning. It is needed, because for statement expressions we have
10850 * to avoid the warning on the last statement)
10852 static statement_t *parse_statement(void)
10854 statement_t *statement = intern_parse_statement();
10856 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10857 expression_t *expression = statement->expression.expression;
10858 if (!expression_has_effect(expression)) {
10859 warningf(&expression->base.source_position,
10860 "statement has no effect");
10868 * Parse a compound statement.
10870 static statement_t *parse_compound_statement(bool inside_expression_statement)
10872 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10874 PUSH_PARENT(statement);
10877 add_anchor_token('}');
10878 /* tokens, which can start a statement */
10879 /* TODO MS, __builtin_FOO */
10880 add_anchor_token('!');
10881 add_anchor_token('&');
10882 add_anchor_token('(');
10883 add_anchor_token('*');
10884 add_anchor_token('+');
10885 add_anchor_token('-');
10886 add_anchor_token('{');
10887 add_anchor_token('~');
10888 add_anchor_token(T_CHARACTER_CONSTANT);
10889 add_anchor_token(T_COLONCOLON);
10890 add_anchor_token(T_FLOATINGPOINT);
10891 add_anchor_token(T_IDENTIFIER);
10892 add_anchor_token(T_INTEGER);
10893 add_anchor_token(T_MINUSMINUS);
10894 add_anchor_token(T_PLUSPLUS);
10895 add_anchor_token(T_STRING_LITERAL);
10896 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10897 add_anchor_token(T_WIDE_STRING_LITERAL);
10898 add_anchor_token(T__Bool);
10899 add_anchor_token(T__Complex);
10900 add_anchor_token(T__Imaginary);
10901 add_anchor_token(T___FUNCTION__);
10902 add_anchor_token(T___PRETTY_FUNCTION__);
10903 add_anchor_token(T___alignof__);
10904 add_anchor_token(T___attribute__);
10905 add_anchor_token(T___builtin_va_start);
10906 add_anchor_token(T___extension__);
10907 add_anchor_token(T___func__);
10908 add_anchor_token(T___imag__);
10909 add_anchor_token(T___label__);
10910 add_anchor_token(T___real__);
10911 add_anchor_token(T___thread);
10912 add_anchor_token(T_asm);
10913 add_anchor_token(T_auto);
10914 add_anchor_token(T_bool);
10915 add_anchor_token(T_break);
10916 add_anchor_token(T_case);
10917 add_anchor_token(T_char);
10918 add_anchor_token(T_class);
10919 add_anchor_token(T_const);
10920 add_anchor_token(T_const_cast);
10921 add_anchor_token(T_continue);
10922 add_anchor_token(T_default);
10923 add_anchor_token(T_delete);
10924 add_anchor_token(T_double);
10925 add_anchor_token(T_do);
10926 add_anchor_token(T_dynamic_cast);
10927 add_anchor_token(T_enum);
10928 add_anchor_token(T_extern);
10929 add_anchor_token(T_false);
10930 add_anchor_token(T_float);
10931 add_anchor_token(T_for);
10932 add_anchor_token(T_goto);
10933 add_anchor_token(T_if);
10934 add_anchor_token(T_inline);
10935 add_anchor_token(T_int);
10936 add_anchor_token(T_long);
10937 add_anchor_token(T_new);
10938 add_anchor_token(T_operator);
10939 add_anchor_token(T_register);
10940 add_anchor_token(T_reinterpret_cast);
10941 add_anchor_token(T_restrict);
10942 add_anchor_token(T_return);
10943 add_anchor_token(T_short);
10944 add_anchor_token(T_signed);
10945 add_anchor_token(T_sizeof);
10946 add_anchor_token(T_static);
10947 add_anchor_token(T_static_cast);
10948 add_anchor_token(T_struct);
10949 add_anchor_token(T_switch);
10950 add_anchor_token(T_template);
10951 add_anchor_token(T_this);
10952 add_anchor_token(T_throw);
10953 add_anchor_token(T_true);
10954 add_anchor_token(T_try);
10955 add_anchor_token(T_typedef);
10956 add_anchor_token(T_typeid);
10957 add_anchor_token(T_typename);
10958 add_anchor_token(T_typeof);
10959 add_anchor_token(T_union);
10960 add_anchor_token(T_unsigned);
10961 add_anchor_token(T_using);
10962 add_anchor_token(T_void);
10963 add_anchor_token(T_volatile);
10964 add_anchor_token(T_wchar_t);
10965 add_anchor_token(T_while);
10967 size_t const top = environment_top();
10968 scope_t *old_scope = scope_push(&statement->compound.scope);
10970 statement_t **anchor = &statement->compound.statements;
10971 bool only_decls_so_far = true;
10972 while (token.type != '}') {
10973 if (token.type == T_EOF) {
10974 errorf(&statement->base.source_position,
10975 "EOF while parsing compound statement");
10978 statement_t *sub_statement = intern_parse_statement();
10979 if (is_invalid_statement(sub_statement)) {
10980 /* an error occurred. if we are at an anchor, return */
10986 if (warning.declaration_after_statement) {
10987 if (sub_statement->kind != STATEMENT_DECLARATION) {
10988 only_decls_so_far = false;
10989 } else if (!only_decls_so_far) {
10990 warningf(&sub_statement->base.source_position,
10991 "ISO C90 forbids mixed declarations and code");
10995 *anchor = sub_statement;
10997 while (sub_statement->base.next != NULL)
10998 sub_statement = sub_statement->base.next;
11000 anchor = &sub_statement->base.next;
11004 /* look over all statements again to produce no effect warnings */
11005 if (warning.unused_value) {
11006 statement_t *sub_statement = statement->compound.statements;
11007 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11008 if (sub_statement->kind != STATEMENT_EXPRESSION)
11010 /* don't emit a warning for the last expression in an expression
11011 * statement as it has always an effect */
11012 if (inside_expression_statement && sub_statement->base.next == NULL)
11015 expression_t *expression = sub_statement->expression.expression;
11016 if (!expression_has_effect(expression)) {
11017 warningf(&expression->base.source_position,
11018 "statement has no effect");
11024 rem_anchor_token(T_while);
11025 rem_anchor_token(T_wchar_t);
11026 rem_anchor_token(T_volatile);
11027 rem_anchor_token(T_void);
11028 rem_anchor_token(T_using);
11029 rem_anchor_token(T_unsigned);
11030 rem_anchor_token(T_union);
11031 rem_anchor_token(T_typeof);
11032 rem_anchor_token(T_typename);
11033 rem_anchor_token(T_typeid);
11034 rem_anchor_token(T_typedef);
11035 rem_anchor_token(T_try);
11036 rem_anchor_token(T_true);
11037 rem_anchor_token(T_throw);
11038 rem_anchor_token(T_this);
11039 rem_anchor_token(T_template);
11040 rem_anchor_token(T_switch);
11041 rem_anchor_token(T_struct);
11042 rem_anchor_token(T_static_cast);
11043 rem_anchor_token(T_static);
11044 rem_anchor_token(T_sizeof);
11045 rem_anchor_token(T_signed);
11046 rem_anchor_token(T_short);
11047 rem_anchor_token(T_return);
11048 rem_anchor_token(T_restrict);
11049 rem_anchor_token(T_reinterpret_cast);
11050 rem_anchor_token(T_register);
11051 rem_anchor_token(T_operator);
11052 rem_anchor_token(T_new);
11053 rem_anchor_token(T_long);
11054 rem_anchor_token(T_int);
11055 rem_anchor_token(T_inline);
11056 rem_anchor_token(T_if);
11057 rem_anchor_token(T_goto);
11058 rem_anchor_token(T_for);
11059 rem_anchor_token(T_float);
11060 rem_anchor_token(T_false);
11061 rem_anchor_token(T_extern);
11062 rem_anchor_token(T_enum);
11063 rem_anchor_token(T_dynamic_cast);
11064 rem_anchor_token(T_do);
11065 rem_anchor_token(T_double);
11066 rem_anchor_token(T_delete);
11067 rem_anchor_token(T_default);
11068 rem_anchor_token(T_continue);
11069 rem_anchor_token(T_const_cast);
11070 rem_anchor_token(T_const);
11071 rem_anchor_token(T_class);
11072 rem_anchor_token(T_char);
11073 rem_anchor_token(T_case);
11074 rem_anchor_token(T_break);
11075 rem_anchor_token(T_bool);
11076 rem_anchor_token(T_auto);
11077 rem_anchor_token(T_asm);
11078 rem_anchor_token(T___thread);
11079 rem_anchor_token(T___real__);
11080 rem_anchor_token(T___label__);
11081 rem_anchor_token(T___imag__);
11082 rem_anchor_token(T___func__);
11083 rem_anchor_token(T___extension__);
11084 rem_anchor_token(T___builtin_va_start);
11085 rem_anchor_token(T___attribute__);
11086 rem_anchor_token(T___alignof__);
11087 rem_anchor_token(T___PRETTY_FUNCTION__);
11088 rem_anchor_token(T___FUNCTION__);
11089 rem_anchor_token(T__Imaginary);
11090 rem_anchor_token(T__Complex);
11091 rem_anchor_token(T__Bool);
11092 rem_anchor_token(T_WIDE_STRING_LITERAL);
11093 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11094 rem_anchor_token(T_STRING_LITERAL);
11095 rem_anchor_token(T_PLUSPLUS);
11096 rem_anchor_token(T_MINUSMINUS);
11097 rem_anchor_token(T_INTEGER);
11098 rem_anchor_token(T_IDENTIFIER);
11099 rem_anchor_token(T_FLOATINGPOINT);
11100 rem_anchor_token(T_COLONCOLON);
11101 rem_anchor_token(T_CHARACTER_CONSTANT);
11102 rem_anchor_token('~');
11103 rem_anchor_token('{');
11104 rem_anchor_token('-');
11105 rem_anchor_token('+');
11106 rem_anchor_token('*');
11107 rem_anchor_token('(');
11108 rem_anchor_token('&');
11109 rem_anchor_token('!');
11110 rem_anchor_token('}');
11111 assert(current_scope == &statement->compound.scope);
11112 scope_pop(old_scope);
11113 environment_pop_to(top);
11120 * Check for unused global static functions and variables
11122 static void check_unused_globals(void)
11124 if (!warning.unused_function && !warning.unused_variable)
11127 for (const entity_t *entity = file_scope->entities; entity != NULL;
11128 entity = entity->base.next) {
11129 if (!is_declaration(entity))
11132 const declaration_t *declaration = &entity->declaration;
11133 if (declaration->used ||
11134 declaration->modifiers & DM_UNUSED ||
11135 declaration->modifiers & DM_USED ||
11136 declaration->storage_class != STORAGE_CLASS_STATIC)
11139 type_t *const type = declaration->type;
11141 if (entity->kind == ENTITY_FUNCTION) {
11142 /* inhibit warning for static inline functions */
11143 if (entity->function.is_inline)
11146 s = entity->function.statement != NULL ? "defined" : "declared";
11151 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11152 type, declaration->base.symbol, s);
11156 static void parse_global_asm(void)
11158 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11161 expect('(', end_error);
11163 statement->asms.asm_text = parse_string_literals();
11164 statement->base.next = unit->global_asm;
11165 unit->global_asm = statement;
11167 expect(')', end_error);
11168 expect(';', end_error);
11173 static void parse_linkage_specification(void)
11176 assert(token.type == T_STRING_LITERAL);
11178 const char *linkage = parse_string_literals().begin;
11180 linkage_kind_t old_linkage = current_linkage;
11181 linkage_kind_t new_linkage;
11182 if (strcmp(linkage, "C") == 0) {
11183 new_linkage = LINKAGE_C;
11184 } else if (strcmp(linkage, "C++") == 0) {
11185 new_linkage = LINKAGE_CXX;
11187 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11188 new_linkage = LINKAGE_INVALID;
11190 current_linkage = new_linkage;
11192 if (token.type == '{') {
11195 expect('}', end_error);
11201 assert(current_linkage == new_linkage);
11202 current_linkage = old_linkage;
11205 static void parse_external(void)
11207 switch (token.type) {
11208 DECLARATION_START_NO_EXTERN
11210 case T___extension__:
11211 /* tokens below are for implicit int */
11212 case '&': /* & x; -> int& x; (and error later, because C++ has no
11214 case '*': /* * x; -> int* x; */
11215 case '(': /* (x); -> int (x); */
11216 parse_external_declaration();
11220 if (look_ahead(1)->type == T_STRING_LITERAL) {
11221 parse_linkage_specification();
11223 parse_external_declaration();
11228 parse_global_asm();
11232 parse_namespace_definition();
11236 if (!strict_mode) {
11238 warningf(HERE, "stray ';' outside of function");
11245 errorf(HERE, "stray %K outside of function", &token);
11246 if (token.type == '(' || token.type == '{' || token.type == '[')
11247 eat_until_matching_token(token.type);
11253 static void parse_externals(void)
11255 add_anchor_token('}');
11256 add_anchor_token(T_EOF);
11259 unsigned char token_anchor_copy[T_LAST_TOKEN];
11260 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11263 while (token.type != T_EOF && token.type != '}') {
11265 bool anchor_leak = false;
11266 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11267 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11269 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11270 anchor_leak = true;
11273 if (in_gcc_extension) {
11274 errorf(HERE, "Leaked __extension__");
11275 anchor_leak = true;
11285 rem_anchor_token(T_EOF);
11286 rem_anchor_token('}');
11290 * Parse a translation unit.
11292 static void parse_translation_unit(void)
11294 add_anchor_token(T_EOF);
11299 if (token.type == T_EOF)
11302 errorf(HERE, "stray %K outside of function", &token);
11303 if (token.type == '(' || token.type == '{' || token.type == '[')
11304 eat_until_matching_token(token.type);
11312 * @return the translation unit or NULL if errors occurred.
11314 void start_parsing(void)
11316 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11317 label_stack = NEW_ARR_F(stack_entry_t, 0);
11318 diagnostic_count = 0;
11322 type_set_output(stderr);
11323 ast_set_output(stderr);
11325 assert(unit == NULL);
11326 unit = allocate_ast_zero(sizeof(unit[0]));
11328 assert(file_scope == NULL);
11329 file_scope = &unit->scope;
11331 assert(current_scope == NULL);
11332 scope_push(&unit->scope);
11334 create_gnu_builtins();
11336 create_microsoft_intrinsics();
11339 translation_unit_t *finish_parsing(void)
11341 assert(current_scope == &unit->scope);
11344 assert(file_scope == &unit->scope);
11345 check_unused_globals();
11348 DEL_ARR_F(environment_stack);
11349 DEL_ARR_F(label_stack);
11351 translation_unit_t *result = unit;
11356 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11357 * are given length one. */
11358 static void complete_incomplete_arrays(void)
11360 size_t n = ARR_LEN(incomplete_arrays);
11361 for (size_t i = 0; i != n; ++i) {
11362 declaration_t *const decl = incomplete_arrays[i];
11363 type_t *const orig_type = decl->type;
11364 type_t *const type = skip_typeref(orig_type);
11366 if (!is_type_incomplete(type))
11369 if (warning.other) {
11370 warningf(&decl->base.source_position,
11371 "array '%#T' assumed to have one element",
11372 orig_type, decl->base.symbol);
11375 type_t *const new_type = duplicate_type(type);
11376 new_type->array.size_constant = true;
11377 new_type->array.has_implicit_size = true;
11378 new_type->array.size = 1;
11380 type_t *const result = identify_new_type(new_type);
11382 decl->type = result;
11388 lookahead_bufpos = 0;
11389 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11392 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11393 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11394 parse_translation_unit();
11395 complete_incomplete_arrays();
11396 DEL_ARR_F(incomplete_arrays);
11397 incomplete_arrays = NULL;
11401 * create a builtin function.
11403 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
11405 symbol_t *symbol = symbol_table_insert(name);
11406 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
11407 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
11408 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
11409 entity->declaration.type = function_type;
11410 entity->declaration.implicit = true;
11411 entity->base.symbol = symbol;
11412 entity->base.source_position = builtin_source_position;
11414 entity->function.btk = kind;
11416 record_entity(entity, /*is_definition=*/false);
11422 * Create predefined gnu builtins.
11424 static void create_gnu_builtins(void)
11426 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11428 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
11429 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
11430 GNU_BUILTIN(inf, make_function_0_type(type_double));
11431 GNU_BUILTIN(inff, make_function_0_type(type_float));
11432 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11433 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11434 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11435 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11436 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11437 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11438 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11439 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11440 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11441 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11442 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11443 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11444 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11445 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11446 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11452 * Create predefined MS intrinsics.
11454 static void create_microsoft_intrinsics(void)
11456 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11458 /* intrinsics for all architectures */
11459 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11460 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11461 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11462 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11463 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11464 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11465 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11467 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11468 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11469 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11472 MS_BUILTIN(_enable, make_function_0_type(type_void));
11473 MS_BUILTIN(_disable, make_function_0_type(type_void));
11474 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11475 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11476 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11477 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11478 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11479 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11480 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11481 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11482 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11483 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11484 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11486 if (machine_size <= 32) {
11487 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11488 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11490 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11491 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11498 * Initialize the parser.
11500 void init_parser(void)
11502 sym_anonymous = symbol_table_insert("<anonymous>");
11504 if (c_mode & _MS) {
11505 /* add predefined symbols for extended-decl-modifier */
11506 sym_align = symbol_table_insert("align");
11507 sym_allocate = symbol_table_insert("allocate");
11508 sym_dllimport = symbol_table_insert("dllimport");
11509 sym_dllexport = symbol_table_insert("dllexport");
11510 sym_naked = symbol_table_insert("naked");
11511 sym_noinline = symbol_table_insert("noinline");
11512 sym_returns_twice = symbol_table_insert("returns_twice");
11513 sym_noreturn = symbol_table_insert("noreturn");
11514 sym_nothrow = symbol_table_insert("nothrow");
11515 sym_novtable = symbol_table_insert("novtable");
11516 sym_property = symbol_table_insert("property");
11517 sym_get = symbol_table_insert("get");
11518 sym_put = symbol_table_insert("put");
11519 sym_selectany = symbol_table_insert("selectany");
11520 sym_thread = symbol_table_insert("thread");
11521 sym_uuid = symbol_table_insert("uuid");
11522 sym_deprecated = symbol_table_insert("deprecated");
11523 sym_restrict = symbol_table_insert("restrict");
11524 sym_noalias = symbol_table_insert("noalias");
11526 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11528 init_expression_parsers();
11529 obstack_init(&temp_obst);
11531 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11532 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11536 * Terminate the parser.
11538 void exit_parser(void)
11540 obstack_free(&temp_obst, NULL);