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"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
108 /** The current token. */
109 static token_t token;
110 /** The lookahead ring-buffer. */
111 static token_t lookahead_buffer[MAX_LOOKAHEAD];
112 /** Position of the next token in the lookahead buffer. */
113 static int lookahead_bufpos;
114 static stack_entry_t *environment_stack = NULL;
115 static stack_entry_t *label_stack = NULL;
116 static stack_entry_t *local_label_stack = NULL;
117 /** The global file scope. */
118 static scope_t *global_scope = NULL;
119 /** The current scope. */
120 static scope_t *scope = NULL;
121 static declaration_t *last_declaration = NULL;
122 /** Point to the current function declaration if inside a function. */
123 static declaration_t *current_function = NULL;
124 static declaration_t *current_init_decl = NULL;
125 static switch_statement_t *current_switch = NULL;
126 static statement_t *current_loop = NULL;
127 static statement_t *current_parent = NULL;
128 static ms_try_statement_t *current_try = NULL;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t *goto_last = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t *label_last = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
142 #define PUSH_PARENT(stmt) \
143 statement_t *const prev_parent = current_parent; \
144 current_parent = (stmt);
145 #define POP_PARENT ((void)(current_parent = prev_parent))
147 static source_position_t null_position = { NULL, 0 };
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_noreturn = NULL;
160 static const symbol_t *sym_nothrow = NULL;
161 static const symbol_t *sym_novtable = NULL;
162 static const symbol_t *sym_property = NULL;
163 static const symbol_t *sym_get = NULL;
164 static const symbol_t *sym_put = NULL;
165 static const symbol_t *sym_selectany = NULL;
166 static const symbol_t *sym_thread = NULL;
167 static const symbol_t *sym_uuid = NULL;
168 static const symbol_t *sym_deprecated = NULL;
169 static const symbol_t *sym_restrict = NULL;
170 static const symbol_t *sym_noalias = NULL;
172 /** The token anchor set */
173 static unsigned char token_anchor_set[T_LAST_TOKEN];
175 /** The current source position. */
176 #define HERE (&token.source_position)
178 /** true if we are in GCC mode. */
179 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
181 static type_t *type_valist;
183 static statement_t *parse_compound_statement(bool inside_expression_statement);
184 static statement_t *parse_statement(void);
186 static expression_t *parse_sub_expression(unsigned precedence);
187 static expression_t *parse_expression(void);
188 static type_t *parse_typename(void);
190 static void parse_compound_type_entries(declaration_t *compound_declaration);
191 static declaration_t *parse_declarator(
192 const declaration_specifiers_t *specifiers, bool may_be_abstract);
193 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
195 static void semantic_comparison(binary_expression_t *expression);
197 #define STORAGE_CLASSES \
205 #define TYPE_QUALIFIERS \
210 case T__forceinline: \
211 case T___attribute__:
213 #ifdef PROVIDE_COMPLEX
214 #define COMPLEX_SPECIFIERS \
216 #define IMAGINARY_SPECIFIERS \
219 #define COMPLEX_SPECIFIERS
220 #define IMAGINARY_SPECIFIERS
223 #define TYPE_SPECIFIERS \
238 case T___builtin_va_list: \
243 #define DECLARATION_START \
248 #define TYPENAME_START \
253 * Allocate an AST node with given size and
254 * initialize all fields with zero.
256 static void *allocate_ast_zero(size_t size)
258 void *res = allocate_ast(size);
259 memset(res, 0, size);
263 static declaration_t *allocate_declaration_zero(void)
265 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
266 declaration->type = type_error_type;
267 declaration->alignment = 0;
272 * Returns the size of a statement node.
274 * @param kind the statement kind
276 static size_t get_statement_struct_size(statement_kind_t kind)
278 static const size_t sizes[] = {
279 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
280 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
281 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
282 [STATEMENT_RETURN] = sizeof(return_statement_t),
283 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
284 [STATEMENT_IF] = sizeof(if_statement_t),
285 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
286 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
287 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
288 [STATEMENT_BREAK] = sizeof(statement_base_t),
289 [STATEMENT_GOTO] = sizeof(goto_statement_t),
290 [STATEMENT_LABEL] = sizeof(label_statement_t),
291 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
292 [STATEMENT_WHILE] = sizeof(while_statement_t),
293 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
294 [STATEMENT_FOR] = sizeof(for_statement_t),
295 [STATEMENT_ASM] = sizeof(asm_statement_t),
296 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
297 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
299 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
300 assert(sizes[kind] != 0);
305 * Returns the size of an expression node.
307 * @param kind the expression kind
309 static size_t get_expression_struct_size(expression_kind_t kind)
311 static const size_t sizes[] = {
312 [EXPR_INVALID] = sizeof(expression_base_t),
313 [EXPR_REFERENCE] = sizeof(reference_expression_t),
314 [EXPR_CONST] = sizeof(const_expression_t),
315 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
316 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
317 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
318 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
319 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
320 [EXPR_CALL] = sizeof(call_expression_t),
321 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
322 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
323 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
324 [EXPR_SELECT] = sizeof(select_expression_t),
325 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
326 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
327 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
328 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
329 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
330 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
331 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
332 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
333 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
334 [EXPR_VA_START] = sizeof(va_start_expression_t),
335 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
336 [EXPR_STATEMENT] = sizeof(statement_expression_t),
337 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
339 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
340 return sizes[EXPR_UNARY_FIRST];
342 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
343 return sizes[EXPR_BINARY_FIRST];
345 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
346 assert(sizes[kind] != 0);
351 * Allocate a statement node of given kind and initialize all
354 static statement_t *allocate_statement_zero(statement_kind_t kind)
356 size_t size = get_statement_struct_size(kind);
357 statement_t *res = allocate_ast_zero(size);
359 res->base.kind = kind;
360 res->base.parent = current_parent;
365 * Allocate an expression node of given kind and initialize all
368 static expression_t *allocate_expression_zero(expression_kind_t kind)
370 size_t size = get_expression_struct_size(kind);
371 expression_t *res = allocate_ast_zero(size);
373 res->base.kind = kind;
374 res->base.type = type_error_type;
379 * Creates a new invalid expression.
381 static expression_t *create_invalid_expression(void)
383 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
384 expression->base.source_position = token.source_position;
389 * Creates a new invalid statement.
391 static statement_t *create_invalid_statement(void)
393 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
394 statement->base.source_position = token.source_position;
399 * Allocate a new empty statement.
401 static statement_t *create_empty_statement(void)
403 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
404 statement->base.source_position = token.source_position;
409 * Returns the size of a type node.
411 * @param kind the type kind
413 static size_t get_type_struct_size(type_kind_t kind)
415 static const size_t sizes[] = {
416 [TYPE_ATOMIC] = sizeof(atomic_type_t),
417 [TYPE_COMPLEX] = sizeof(complex_type_t),
418 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
419 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
420 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
421 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
422 [TYPE_ENUM] = sizeof(enum_type_t),
423 [TYPE_FUNCTION] = sizeof(function_type_t),
424 [TYPE_POINTER] = sizeof(pointer_type_t),
425 [TYPE_ARRAY] = sizeof(array_type_t),
426 [TYPE_BUILTIN] = sizeof(builtin_type_t),
427 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
428 [TYPE_TYPEOF] = sizeof(typeof_type_t),
430 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
431 assert(kind <= TYPE_TYPEOF);
432 assert(sizes[kind] != 0);
437 * Allocate a type node of given kind and initialize all
440 * @param kind type kind to allocate
441 * @param source_position the source position of the type definition
443 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
445 size_t size = get_type_struct_size(kind);
446 type_t *res = obstack_alloc(type_obst, size);
447 memset(res, 0, size);
449 res->base.kind = kind;
450 res->base.source_position = *source_position;
455 * Returns the size of an initializer node.
457 * @param kind the initializer kind
459 static size_t get_initializer_size(initializer_kind_t kind)
461 static const size_t sizes[] = {
462 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
463 [INITIALIZER_STRING] = sizeof(initializer_string_t),
464 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
465 [INITIALIZER_LIST] = sizeof(initializer_list_t),
466 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
468 assert(kind < sizeof(sizes) / sizeof(*sizes));
469 assert(sizes[kind] != 0);
474 * Allocate an initializer node of given kind and initialize all
477 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
479 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
486 * Free a type from the type obstack.
488 static void free_type(void *type)
490 obstack_free(type_obst, type);
494 * Returns the index of the top element of the environment stack.
496 static size_t environment_top(void)
498 return ARR_LEN(environment_stack);
502 * Returns the index of the top element of the global label stack.
504 static size_t label_top(void)
506 return ARR_LEN(label_stack);
510 * Returns the index of the top element of the local label stack.
512 static size_t local_label_top(void)
514 return ARR_LEN(local_label_stack);
518 * Return the next token.
520 static inline void next_token(void)
522 token = lookahead_buffer[lookahead_bufpos];
523 lookahead_buffer[lookahead_bufpos] = lexer_token;
526 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
529 print_token(stderr, &token);
530 fprintf(stderr, "\n");
535 * Return the next token with a given lookahead.
537 static inline const token_t *look_ahead(int num)
539 assert(num > 0 && num <= MAX_LOOKAHEAD);
540 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
541 return &lookahead_buffer[pos];
545 * Adds a token to the token anchor set (a multi-set).
547 static void add_anchor_token(int token_type)
549 assert(0 <= token_type && token_type < T_LAST_TOKEN);
550 ++token_anchor_set[token_type];
553 static int save_and_reset_anchor_state(int token_type)
555 assert(0 <= token_type && token_type < T_LAST_TOKEN);
556 int count = token_anchor_set[token_type];
557 token_anchor_set[token_type] = 0;
561 static void restore_anchor_state(int token_type, int count)
563 assert(0 <= token_type && token_type < T_LAST_TOKEN);
564 token_anchor_set[token_type] = count;
568 * Remove a token from the token anchor set (a multi-set).
570 static void rem_anchor_token(int token_type)
572 assert(0 <= token_type && token_type < T_LAST_TOKEN);
573 assert(token_anchor_set[token_type] != 0);
574 --token_anchor_set[token_type];
577 static bool at_anchor(void)
581 return token_anchor_set[token.type];
585 * Eat tokens until a matching token is found.
587 static void eat_until_matching_token(int type)
591 case '(': end_token = ')'; break;
592 case '{': end_token = '}'; break;
593 case '[': end_token = ']'; break;
594 default: end_token = type; break;
597 unsigned parenthesis_count = 0;
598 unsigned brace_count = 0;
599 unsigned bracket_count = 0;
600 while (token.type != end_token ||
601 parenthesis_count != 0 ||
603 bracket_count != 0) {
604 switch (token.type) {
606 case '(': ++parenthesis_count; break;
607 case '{': ++brace_count; break;
608 case '[': ++bracket_count; break;
611 if (parenthesis_count > 0)
621 if (bracket_count > 0)
624 if (token.type == end_token &&
625 parenthesis_count == 0 &&
639 * Eat input tokens until an anchor is found.
641 static void eat_until_anchor(void)
643 if (token.type == T_EOF)
645 while (token_anchor_set[token.type] == 0) {
646 if (token.type == '(' || token.type == '{' || token.type == '[')
647 eat_until_matching_token(token.type);
648 if (token.type == T_EOF)
654 static void eat_block(void)
656 eat_until_matching_token('{');
657 if (token.type == '}')
661 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
664 * Report a parse error because an expected token was not found.
667 #if defined __GNUC__ && __GNUC__ >= 4
668 __attribute__((sentinel))
670 void parse_error_expected(const char *message, ...)
672 if (message != NULL) {
673 errorf(HERE, "%s", message);
676 va_start(ap, message);
677 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
682 * Report a type error.
684 static void type_error(const char *msg, const source_position_t *source_position,
687 errorf(source_position, "%s, but found type '%T'", msg, type);
691 * Report an incompatible type.
693 static void type_error_incompatible(const char *msg,
694 const source_position_t *source_position, type_t *type1, type_t *type2)
696 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
701 * Expect the the current token is the expected token.
702 * If not, generate an error, eat the current statement,
703 * and goto the end_error label.
705 #define expect(expected) \
707 if (UNLIKELY(token.type != (expected))) { \
708 parse_error_expected(NULL, (expected), NULL); \
709 add_anchor_token(expected); \
710 eat_until_anchor(); \
711 if (token.type == expected) \
713 rem_anchor_token(expected); \
719 static void scope_push(scope_t *new_scope)
722 scope->last_declaration = last_declaration;
723 new_scope->depth = scope->depth + 1;
725 new_scope->parent = scope;
728 last_declaration = new_scope->last_declaration;
731 static void scope_pop(void)
733 scope->last_declaration = last_declaration;
734 scope = scope->parent;
735 last_declaration = scope->last_declaration;
739 * Search a symbol in a given namespace and returns its declaration or
740 * NULL if this symbol was not found.
742 static declaration_t *get_declaration(const symbol_t *const symbol,
743 const namespace_t namespc)
745 declaration_t *declaration = symbol->declaration;
746 for( ; declaration != NULL; declaration = declaration->symbol_next) {
747 if (declaration->namespc == namespc)
755 * pushs an environment_entry on the environment stack and links the
756 * corresponding symbol to the new entry
758 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
760 symbol_t *symbol = declaration->symbol;
761 namespace_t namespc = (namespace_t) declaration->namespc;
763 /* replace/add declaration into declaration list of the symbol */
764 declaration_t **anchor;
766 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
771 /* replace an entry? */
772 if (iter->namespc == namespc) {
773 declaration->symbol_next = iter->symbol_next;
777 *anchor = declaration;
779 /* remember old declaration */
781 entry.symbol = symbol;
782 entry.old_declaration = iter;
783 entry.namespc = (unsigned short) namespc;
784 ARR_APP1(stack_entry_t, *stack_ptr, entry);
788 * Push a declaration on the environment stack.
790 * @param declaration the declaration
792 static void environment_push(declaration_t *declaration)
794 assert(declaration->source_position.input_name != NULL);
795 assert(declaration->parent_scope != NULL);
796 stack_push(&environment_stack, declaration);
800 * Push a declaration on the global label stack.
802 * @param declaration the declaration
804 static void label_push(declaration_t *declaration)
806 declaration->parent_scope = ¤t_function->scope;
807 stack_push(&label_stack, declaration);
811 * Push a declaration of the local label stack.
813 * @param declaration the declaration
815 static void local_label_push(declaration_t *declaration)
817 assert(declaration->parent_scope != NULL);
818 stack_push(&local_label_stack, declaration);
822 * pops symbols from the environment stack until @p new_top is the top element
824 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
826 stack_entry_t *stack = *stack_ptr;
827 size_t top = ARR_LEN(stack);
830 assert(new_top <= top);
834 for(i = top; i > new_top; --i) {
835 stack_entry_t *entry = &stack[i - 1];
837 declaration_t *old_declaration = entry->old_declaration;
838 symbol_t *symbol = entry->symbol;
839 namespace_t namespc = (namespace_t)entry->namespc;
841 /* replace/remove declaration */
842 declaration_t *declaration = symbol->declaration;
843 assert(declaration != NULL);
844 if (declaration->namespc == namespc) {
845 if (old_declaration == NULL) {
846 symbol->declaration = declaration->symbol_next;
848 symbol->declaration = old_declaration;
851 declaration_t *iter_last = declaration;
852 declaration_t *iter = declaration->symbol_next;
853 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
854 /* replace an entry? */
855 if (iter->namespc == namespc) {
856 assert(iter_last != NULL);
857 iter_last->symbol_next = old_declaration;
858 if (old_declaration != NULL) {
859 old_declaration->symbol_next = iter->symbol_next;
864 assert(iter != NULL);
868 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
872 * Pop all entries from the environment stack until the new_top
875 * @param new_top the new stack top
877 static void environment_pop_to(size_t new_top)
879 stack_pop_to(&environment_stack, new_top);
883 * Pop all entries from the global label stack until the new_top
886 * @param new_top the new stack top
888 static void label_pop_to(size_t new_top)
890 stack_pop_to(&label_stack, new_top);
894 * Pop all entries from the local label stack until the new_top
897 * @param new_top the new stack top
899 static void local_label_pop_to(size_t new_top)
901 stack_pop_to(&local_label_stack, new_top);
905 static int get_akind_rank(atomic_type_kind_t akind)
910 static int get_rank(const type_t *type)
912 assert(!is_typeref(type));
913 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
914 * and esp. footnote 108). However we can't fold constants (yet), so we
915 * can't decide whether unsigned int is possible, while int always works.
916 * (unsigned int would be preferable when possible... for stuff like
917 * struct { enum { ... } bla : 4; } ) */
918 if (type->kind == TYPE_ENUM)
919 return get_akind_rank(ATOMIC_TYPE_INT);
921 assert(type->kind == TYPE_ATOMIC);
922 return get_akind_rank(type->atomic.akind);
925 static type_t *promote_integer(type_t *type)
927 if (type->kind == TYPE_BITFIELD)
928 type = type->bitfield.base_type;
930 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
937 * Create a cast expression.
939 * @param expression the expression to cast
940 * @param dest_type the destination type
942 static expression_t *create_cast_expression(expression_t *expression,
945 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
947 cast->unary.value = expression;
948 cast->base.type = dest_type;
954 * Check if a given expression represents the 0 pointer constant.
956 static bool is_null_pointer_constant(const expression_t *expression)
958 /* skip void* cast */
959 if (expression->kind == EXPR_UNARY_CAST
960 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
961 expression = expression->unary.value;
964 /* TODO: not correct yet, should be any constant integer expression
965 * which evaluates to 0 */
966 if (expression->kind != EXPR_CONST)
969 type_t *const type = skip_typeref(expression->base.type);
970 if (!is_type_integer(type))
973 return expression->conste.v.int_value == 0;
977 * Create an implicit cast expression.
979 * @param expression the expression to cast
980 * @param dest_type the destination type
982 static expression_t *create_implicit_cast(expression_t *expression,
985 type_t *const source_type = expression->base.type;
987 if (source_type == dest_type)
990 return create_cast_expression(expression, dest_type);
993 typedef enum assign_error_t {
995 ASSIGN_ERROR_INCOMPATIBLE,
996 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
997 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
998 ASSIGN_WARNING_POINTER_FROM_INT,
999 ASSIGN_WARNING_INT_FROM_POINTER
1002 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1003 const expression_t *const right,
1004 const char *context,
1005 const source_position_t *source_position)
1007 type_t *const orig_type_right = right->base.type;
1008 type_t *const type_left = skip_typeref(orig_type_left);
1009 type_t *const type_right = skip_typeref(orig_type_right);
1012 case ASSIGN_SUCCESS:
1014 case ASSIGN_ERROR_INCOMPATIBLE:
1015 errorf(source_position,
1016 "destination type '%T' in %s is incompatible with type '%T'",
1017 orig_type_left, context, orig_type_right);
1020 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1021 type_t *points_to_left
1022 = skip_typeref(type_left->pointer.points_to);
1023 type_t *points_to_right
1024 = skip_typeref(type_right->pointer.points_to);
1026 /* the left type has all qualifiers from the right type */
1027 unsigned missing_qualifiers
1028 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1029 warningf(source_position,
1030 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1031 orig_type_left, context, orig_type_right, missing_qualifiers);
1035 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1036 warningf(source_position,
1037 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1038 orig_type_left, context, right, orig_type_right);
1041 case ASSIGN_WARNING_POINTER_FROM_INT:
1042 warningf(source_position,
1043 "%s makes pointer '%T' from integer '%T' without a cast",
1044 context, orig_type_left, orig_type_right);
1047 case ASSIGN_WARNING_INT_FROM_POINTER:
1048 warningf(source_position,
1049 "%s makes integer '%T' from pointer '%T' without a cast",
1050 context, orig_type_left, orig_type_right);
1054 panic("invalid error value");
1058 /** Implements the rules from § 6.5.16.1 */
1059 static assign_error_t semantic_assign(type_t *orig_type_left,
1060 const expression_t *const right)
1062 type_t *const orig_type_right = right->base.type;
1063 type_t *const type_left = skip_typeref(orig_type_left);
1064 type_t *const type_right = skip_typeref(orig_type_right);
1066 if (is_type_pointer(type_left)) {
1067 if (is_null_pointer_constant(right)) {
1068 return ASSIGN_SUCCESS;
1069 } else if (is_type_pointer(type_right)) {
1070 type_t *points_to_left
1071 = skip_typeref(type_left->pointer.points_to);
1072 type_t *points_to_right
1073 = skip_typeref(type_right->pointer.points_to);
1074 assign_error_t res = ASSIGN_SUCCESS;
1076 /* the left type has all qualifiers from the right type */
1077 unsigned missing_qualifiers
1078 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1079 if (missing_qualifiers != 0) {
1080 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1083 points_to_left = get_unqualified_type(points_to_left);
1084 points_to_right = get_unqualified_type(points_to_right);
1086 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1087 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1091 if (!types_compatible(points_to_left, points_to_right)) {
1092 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1096 } else if (is_type_integer(type_right)) {
1097 return ASSIGN_WARNING_POINTER_FROM_INT;
1099 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1100 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1101 && is_type_pointer(type_right))) {
1102 return ASSIGN_SUCCESS;
1103 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1104 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1105 type_t *const unqual_type_left = get_unqualified_type(type_left);
1106 type_t *const unqual_type_right = get_unqualified_type(type_right);
1107 if (types_compatible(unqual_type_left, unqual_type_right)) {
1108 return ASSIGN_SUCCESS;
1110 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1111 return ASSIGN_WARNING_INT_FROM_POINTER;
1114 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1115 return ASSIGN_SUCCESS;
1117 return ASSIGN_ERROR_INCOMPATIBLE;
1120 static expression_t *parse_constant_expression(void)
1122 /* start parsing at precedence 7 (conditional expression) */
1123 expression_t *result = parse_sub_expression(7);
1125 if (!is_constant_expression(result)) {
1126 errorf(&result->base.source_position,
1127 "expression '%E' is not constant\n", result);
1133 static expression_t *parse_assignment_expression(void)
1135 /* start parsing at precedence 2 (assignment expression) */
1136 return parse_sub_expression(2);
1139 static type_t *make_global_typedef(const char *name, type_t *type)
1141 symbol_t *const symbol = symbol_table_insert(name);
1143 declaration_t *const declaration = allocate_declaration_zero();
1144 declaration->namespc = NAMESPACE_NORMAL;
1145 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1146 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1147 declaration->type = type;
1148 declaration->symbol = symbol;
1149 declaration->source_position = builtin_source_position;
1150 declaration->implicit = true;
1152 record_declaration(declaration, false);
1154 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1155 typedef_type->typedeft.declaration = declaration;
1157 return typedef_type;
1160 static string_t parse_string_literals(void)
1162 assert(token.type == T_STRING_LITERAL);
1163 string_t result = token.v.string;
1167 while (token.type == T_STRING_LITERAL) {
1168 result = concat_strings(&result, &token.v.string);
1175 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1176 [GNU_AK_CONST] = "const",
1177 [GNU_AK_VOLATILE] = "volatile",
1178 [GNU_AK_CDECL] = "cdecl",
1179 [GNU_AK_STDCALL] = "stdcall",
1180 [GNU_AK_FASTCALL] = "fastcall",
1181 [GNU_AK_DEPRECATED] = "deprecated",
1182 [GNU_AK_NOINLINE] = "noinline",
1183 [GNU_AK_NORETURN] = "noreturn",
1184 [GNU_AK_NAKED] = "naked",
1185 [GNU_AK_PURE] = "pure",
1186 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1187 [GNU_AK_MALLOC] = "malloc",
1188 [GNU_AK_WEAK] = "weak",
1189 [GNU_AK_CONSTRUCTOR] = "constructor",
1190 [GNU_AK_DESTRUCTOR] = "destructor",
1191 [GNU_AK_NOTHROW] = "nothrow",
1192 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1193 [GNU_AK_COMMON] = "common",
1194 [GNU_AK_NOCOMMON] = "nocommon",
1195 [GNU_AK_PACKED] = "packed",
1196 [GNU_AK_SHARED] = "shared",
1197 [GNU_AK_NOTSHARED] = "notshared",
1198 [GNU_AK_USED] = "used",
1199 [GNU_AK_UNUSED] = "unused",
1200 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1201 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1202 [GNU_AK_LONGCALL] = "longcall",
1203 [GNU_AK_SHORTCALL] = "shortcall",
1204 [GNU_AK_LONG_CALL] = "long_call",
1205 [GNU_AK_SHORT_CALL] = "short_call",
1206 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1207 [GNU_AK_INTERRUPT] = "interrupt",
1208 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1209 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1210 [GNU_AK_NESTING] = "nesting",
1211 [GNU_AK_NEAR] = "near",
1212 [GNU_AK_FAR] = "far",
1213 [GNU_AK_SIGNAL] = "signal",
1214 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1215 [GNU_AK_TINY_DATA] = "tiny_data",
1216 [GNU_AK_SAVEALL] = "saveall",
1217 [GNU_AK_FLATTEN] = "flatten",
1218 [GNU_AK_SSEREGPARM] = "sseregparm",
1219 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1220 [GNU_AK_RETURN_TWICE] = "return_twice",
1221 [GNU_AK_MAY_ALIAS] = "may_alias",
1222 [GNU_AK_MS_STRUCT] = "ms_struct",
1223 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1224 [GNU_AK_DLLIMPORT] = "dllimport",
1225 [GNU_AK_DLLEXPORT] = "dllexport",
1226 [GNU_AK_ALIGNED] = "aligned",
1227 [GNU_AK_ALIAS] = "alias",
1228 [GNU_AK_SECTION] = "section",
1229 [GNU_AK_FORMAT] = "format",
1230 [GNU_AK_FORMAT_ARG] = "format_arg",
1231 [GNU_AK_WEAKREF] = "weakref",
1232 [GNU_AK_NONNULL] = "nonnull",
1233 [GNU_AK_TLS_MODEL] = "tls_model",
1234 [GNU_AK_VISIBILITY] = "visibility",
1235 [GNU_AK_REGPARM] = "regparm",
1236 [GNU_AK_MODE] = "mode",
1237 [GNU_AK_MODEL] = "model",
1238 [GNU_AK_TRAP_EXIT] = "trap_exit",
1239 [GNU_AK_SP_SWITCH] = "sp_switch",
1240 [GNU_AK_SENTINEL] = "sentinel"
1244 * compare two string, ignoring double underscores on the second.
1246 static int strcmp_underscore(const char *s1, const char *s2)
1248 if (s2[0] == '_' && s2[1] == '_') {
1249 size_t len2 = strlen(s2);
1250 size_t len1 = strlen(s1);
1251 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1252 return strncmp(s1, s2+2, len2-4);
1256 return strcmp(s1, s2);
1260 * Allocate a new gnu temporal attribute.
1262 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1264 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1265 attribute->kind = kind;
1266 attribute->next = NULL;
1267 attribute->invalid = false;
1268 attribute->have_arguments = false;
1274 * parse one constant expression argument.
1276 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1278 expression_t *expression;
1279 add_anchor_token(')');
1280 expression = parse_constant_expression();
1281 rem_anchor_token(')');
1283 attribute->u.argument = fold_constant(expression);
1286 attribute->invalid = true;
1290 * parse a list of constant expressions arguments.
1292 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1294 argument_list_t **list = &attribute->u.arguments;
1295 argument_list_t *entry;
1296 expression_t *expression;
1297 add_anchor_token(')');
1298 add_anchor_token(',');
1300 expression = parse_constant_expression();
1301 entry = obstack_alloc(&temp_obst, sizeof(entry));
1302 entry->argument = fold_constant(expression);
1305 list = &entry->next;
1306 if (token.type != ',')
1310 rem_anchor_token(',');
1311 rem_anchor_token(')');
1315 attribute->invalid = true;
1319 * parse one string literal argument.
1321 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1324 add_anchor_token('(');
1325 if (token.type != T_STRING_LITERAL) {
1326 parse_error_expected("while parsing attribute directive",
1327 T_STRING_LITERAL, NULL);
1330 *string = parse_string_literals();
1331 rem_anchor_token('(');
1335 attribute->invalid = true;
1339 * parse one tls model.
1341 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1343 static const char *const tls_models[] = {
1349 string_t string = { NULL, 0 };
1350 parse_gnu_attribute_string_arg(attribute, &string);
1351 if (string.begin != NULL) {
1352 for(size_t i = 0; i < 4; ++i) {
1353 if (strcmp(tls_models[i], string.begin) == 0) {
1354 attribute->u.value = i;
1358 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1360 attribute->invalid = true;
1364 * parse one tls model.
1366 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1368 static const char *const visibilities[] = {
1374 string_t string = { NULL, 0 };
1375 parse_gnu_attribute_string_arg(attribute, &string);
1376 if (string.begin != NULL) {
1377 for(size_t i = 0; i < 4; ++i) {
1378 if (strcmp(visibilities[i], string.begin) == 0) {
1379 attribute->u.value = i;
1383 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1385 attribute->invalid = true;
1389 * parse one (code) model.
1391 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1393 static const char *const visibilities[] = {
1398 string_t string = { NULL, 0 };
1399 parse_gnu_attribute_string_arg(attribute, &string);
1400 if (string.begin != NULL) {
1401 for(int i = 0; i < 3; ++i) {
1402 if (strcmp(visibilities[i], string.begin) == 0) {
1403 attribute->u.value = i;
1407 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1409 attribute->invalid = true;
1412 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1414 /* TODO: find out what is allowed here... */
1416 /* at least: byte, word, pointer, list of machine modes
1417 * __XXX___ is interpreted as XXX */
1418 add_anchor_token(')');
1420 if (token.type != T_IDENTIFIER) {
1421 expect(T_IDENTIFIER);
1424 /* This isn't really correct, the backend should provide a list of machine
1425 * specific modes (according to gcc philosophy that is...) */
1426 const char *symbol_str = token.v.symbol->string;
1427 if (strcmp_underscore("QI", symbol_str) == 0 ||
1428 strcmp_underscore("byte", symbol_str) == 0) {
1429 attribute->u.akind = ATOMIC_TYPE_CHAR;
1430 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1431 attribute->u.akind = ATOMIC_TYPE_SHORT;
1432 } else if (strcmp_underscore("SI", symbol_str) == 0
1433 || strcmp_underscore("word", symbol_str) == 0
1434 || strcmp_underscore("pointer", symbol_str) == 0) {
1435 attribute->u.akind = ATOMIC_TYPE_INT;
1436 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1437 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1439 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1440 attribute->invalid = true;
1444 rem_anchor_token(')');
1448 attribute->invalid = true;
1452 * parse one interrupt argument.
1454 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1456 static const char *const interrupts[] = {
1463 string_t string = { NULL, 0 };
1464 parse_gnu_attribute_string_arg(attribute, &string);
1465 if (string.begin != NULL) {
1466 for(size_t i = 0; i < 5; ++i) {
1467 if (strcmp(interrupts[i], string.begin) == 0) {
1468 attribute->u.value = i;
1472 errorf(HERE, "'%s' is not an interrupt", string.begin);
1474 attribute->invalid = true;
1478 * parse ( identifier, const expression, const expression )
1480 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1482 static const char *const format_names[] = {
1490 if (token.type != T_IDENTIFIER) {
1491 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1494 const char *name = token.v.symbol->string;
1495 for(i = 0; i < 4; ++i) {
1496 if (strcmp_underscore(format_names[i], name) == 0)
1500 if (warning.attribute)
1501 warningf(HERE, "'%s' is an unrecognized format function type", name);
1506 add_anchor_token(')');
1507 add_anchor_token(',');
1508 parse_constant_expression();
1509 rem_anchor_token(',');
1510 rem_anchor_token(')');
1513 add_anchor_token(')');
1514 parse_constant_expression();
1515 rem_anchor_token(')');
1519 attribute->u.value = true;
1522 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1524 if (!attribute->have_arguments)
1527 /* should have no arguments */
1528 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1529 eat_until_matching_token('(');
1530 /* we have already consumed '(', so we stop before ')', eat it */
1532 attribute->invalid = true;
1536 * Parse one GNU attribute.
1538 * Note that attribute names can be specified WITH or WITHOUT
1539 * double underscores, ie const or __const__.
1541 * The following attributes are parsed without arguments
1566 * no_instrument_function
1567 * warn_unused_result
1584 * externally_visible
1592 * The following attributes are parsed with arguments
1593 * aligned( const expression )
1594 * alias( string literal )
1595 * section( string literal )
1596 * format( identifier, const expression, const expression )
1597 * format_arg( const expression )
1598 * tls_model( string literal )
1599 * visibility( string literal )
1600 * regparm( const expression )
1601 * model( string leteral )
1602 * trap_exit( const expression )
1603 * sp_switch( string literal )
1605 * The following attributes might have arguments
1606 * weak_ref( string literal )
1607 * non_null( const expression // ',' )
1608 * interrupt( string literal )
1609 * sentinel( constant expression )
1611 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1613 gnu_attribute_t *head = *attributes;
1614 gnu_attribute_t *last = *attributes;
1615 decl_modifiers_t modifiers = 0;
1616 gnu_attribute_t *attribute;
1618 eat(T___attribute__);
1622 if (token.type != ')') {
1623 /* find the end of the list */
1625 while (last->next != NULL)
1629 /* non-empty attribute list */
1632 if (token.type == T_const) {
1634 } else if (token.type == T_volatile) {
1636 } else if (token.type == T_cdecl) {
1637 /* __attribute__((cdecl)), WITH ms mode */
1639 } else if (token.type == T_IDENTIFIER) {
1640 const symbol_t *sym = token.v.symbol;
1643 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1650 for(i = 0; i < GNU_AK_LAST; ++i) {
1651 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1654 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1657 if (kind == GNU_AK_LAST) {
1658 if (warning.attribute)
1659 warningf(HERE, "'%s' attribute directive ignored", name);
1661 /* skip possible arguments */
1662 if (token.type == '(') {
1663 eat_until_matching_token(')');
1666 /* check for arguments */
1667 attribute = allocate_gnu_attribute(kind);
1668 if (token.type == '(') {
1670 if (token.type == ')') {
1671 /* empty args are allowed */
1674 attribute->have_arguments = true;
1679 case GNU_AK_VOLATILE:
1684 case GNU_AK_NOCOMMON:
1686 case GNU_AK_NOTSHARED:
1687 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1688 case GNU_AK_WARN_UNUSED_RESULT:
1689 case GNU_AK_LONGCALL:
1690 case GNU_AK_SHORTCALL:
1691 case GNU_AK_LONG_CALL:
1692 case GNU_AK_SHORT_CALL:
1693 case GNU_AK_FUNCTION_VECTOR:
1694 case GNU_AK_INTERRUPT_HANDLER:
1695 case GNU_AK_NMI_HANDLER:
1696 case GNU_AK_NESTING:
1700 case GNU_AK_EIGTHBIT_DATA:
1701 case GNU_AK_TINY_DATA:
1702 case GNU_AK_SAVEALL:
1703 case GNU_AK_FLATTEN:
1704 case GNU_AK_SSEREGPARM:
1705 case GNU_AK_EXTERNALLY_VISIBLE:
1706 case GNU_AK_RETURN_TWICE:
1707 case GNU_AK_MAY_ALIAS:
1708 case GNU_AK_MS_STRUCT:
1709 case GNU_AK_GCC_STRUCT:
1712 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1713 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1714 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1715 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1716 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1717 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1718 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1719 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1720 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1721 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1722 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1723 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1724 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1725 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1726 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1727 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1728 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1730 case GNU_AK_ALIGNED:
1731 /* __align__ may be used without an argument */
1732 if (attribute->have_arguments) {
1733 parse_gnu_attribute_const_arg(attribute);
1737 case GNU_AK_FORMAT_ARG:
1738 case GNU_AK_REGPARM:
1739 case GNU_AK_TRAP_EXIT:
1740 if (!attribute->have_arguments) {
1741 /* should have arguments */
1742 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1743 attribute->invalid = true;
1745 parse_gnu_attribute_const_arg(attribute);
1748 case GNU_AK_SECTION:
1749 case GNU_AK_SP_SWITCH:
1750 if (!attribute->have_arguments) {
1751 /* should have arguments */
1752 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1753 attribute->invalid = true;
1755 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1758 if (!attribute->have_arguments) {
1759 /* should have arguments */
1760 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1761 attribute->invalid = true;
1763 parse_gnu_attribute_format_args(attribute);
1765 case GNU_AK_WEAKREF:
1766 /* may have one string argument */
1767 if (attribute->have_arguments)
1768 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1770 case GNU_AK_NONNULL:
1771 if (attribute->have_arguments)
1772 parse_gnu_attribute_const_arg_list(attribute);
1774 case GNU_AK_TLS_MODEL:
1775 if (!attribute->have_arguments) {
1776 /* should have arguments */
1777 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1779 parse_gnu_attribute_tls_model_arg(attribute);
1781 case GNU_AK_VISIBILITY:
1782 if (!attribute->have_arguments) {
1783 /* should have arguments */
1784 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1786 parse_gnu_attribute_visibility_arg(attribute);
1789 if (!attribute->have_arguments) {
1790 /* should have arguments */
1791 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1793 parse_gnu_attribute_model_arg(attribute);
1797 if (!attribute->have_arguments) {
1798 /* should have arguments */
1799 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1801 parse_gnu_attribute_mode_arg(attribute);
1804 case GNU_AK_INTERRUPT:
1805 /* may have one string argument */
1806 if (attribute->have_arguments)
1807 parse_gnu_attribute_interrupt_arg(attribute);
1809 case GNU_AK_SENTINEL:
1810 /* may have one string argument */
1811 if (attribute->have_arguments)
1812 parse_gnu_attribute_const_arg(attribute);
1815 /* already handled */
1819 check_no_argument(attribute, name);
1822 if (attribute != NULL) {
1824 last->next = attribute;
1827 head = last = attribute;
1831 if (token.type != ',')
1845 * Parse GNU attributes.
1847 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1849 decl_modifiers_t modifiers = 0;
1852 switch(token.type) {
1853 case T___attribute__:
1854 modifiers |= parse_gnu_attribute(attributes);
1860 if (token.type != T_STRING_LITERAL) {
1861 parse_error_expected("while parsing assembler attribute",
1862 T_STRING_LITERAL, NULL);
1863 eat_until_matching_token('(');
1866 parse_string_literals();
1871 case T_cdecl: modifiers |= DM_CDECL; break;
1872 case T__fastcall: modifiers |= DM_FASTCALL; break;
1873 case T__stdcall: modifiers |= DM_STDCALL; break;
1876 /* TODO record modifier */
1877 warningf(HERE, "Ignoring declaration modifier %K", &token);
1881 default: return modifiers;
1888 static designator_t *parse_designation(void)
1890 designator_t *result = NULL;
1891 designator_t *last = NULL;
1894 designator_t *designator;
1895 switch(token.type) {
1897 designator = allocate_ast_zero(sizeof(designator[0]));
1898 designator->source_position = token.source_position;
1900 add_anchor_token(']');
1901 designator->array_index = parse_constant_expression();
1902 rem_anchor_token(']');
1906 designator = allocate_ast_zero(sizeof(designator[0]));
1907 designator->source_position = token.source_position;
1909 if (token.type != T_IDENTIFIER) {
1910 parse_error_expected("while parsing designator",
1911 T_IDENTIFIER, NULL);
1914 designator->symbol = token.v.symbol;
1922 assert(designator != NULL);
1924 last->next = designator;
1926 result = designator;
1934 static initializer_t *initializer_from_string(array_type_t *type,
1935 const string_t *const string)
1937 /* TODO: check len vs. size of array type */
1940 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1941 initializer->string.string = *string;
1946 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1947 wide_string_t *const string)
1949 /* TODO: check len vs. size of array type */
1952 initializer_t *const initializer =
1953 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1954 initializer->wide_string.string = *string;
1960 * Build an initializer from a given expression.
1962 static initializer_t *initializer_from_expression(type_t *orig_type,
1963 expression_t *expression)
1965 /* TODO check that expression is a constant expression */
1967 /* § 6.7.8.14/15 char array may be initialized by string literals */
1968 type_t *type = skip_typeref(orig_type);
1969 type_t *expr_type_orig = expression->base.type;
1970 type_t *expr_type = skip_typeref(expr_type_orig);
1971 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1972 array_type_t *const array_type = &type->array;
1973 type_t *const element_type = skip_typeref(array_type->element_type);
1975 if (element_type->kind == TYPE_ATOMIC) {
1976 atomic_type_kind_t akind = element_type->atomic.akind;
1977 switch (expression->kind) {
1978 case EXPR_STRING_LITERAL:
1979 if (akind == ATOMIC_TYPE_CHAR
1980 || akind == ATOMIC_TYPE_SCHAR
1981 || akind == ATOMIC_TYPE_UCHAR) {
1982 return initializer_from_string(array_type,
1983 &expression->string.value);
1986 case EXPR_WIDE_STRING_LITERAL: {
1987 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1988 if (get_unqualified_type(element_type) == bare_wchar_type) {
1989 return initializer_from_wide_string(array_type,
1990 &expression->wide_string.value);
2000 assign_error_t error = semantic_assign(type, expression);
2001 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2003 report_assign_error(error, type, expression, "initializer",
2004 &expression->base.source_position);
2006 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2007 result->value.value = create_implicit_cast(expression, type);
2013 * Checks if a given expression can be used as an constant initializer.
2015 static bool is_initializer_constant(const expression_t *expression)
2017 return is_constant_expression(expression)
2018 || is_address_constant(expression);
2022 * Parses an scalar initializer.
2024 * § 6.7.8.11; eat {} without warning
2026 static initializer_t *parse_scalar_initializer(type_t *type,
2027 bool must_be_constant)
2029 /* there might be extra {} hierarchies */
2031 if (token.type == '{') {
2032 warningf(HERE, "extra curly braces around scalar initializer");
2036 } while (token.type == '{');
2039 expression_t *expression = parse_assignment_expression();
2040 if (must_be_constant && !is_initializer_constant(expression)) {
2041 errorf(&expression->base.source_position,
2042 "Initialisation expression '%E' is not constant\n",
2046 initializer_t *initializer = initializer_from_expression(type, expression);
2048 if (initializer == NULL) {
2049 errorf(&expression->base.source_position,
2050 "expression '%E' (type '%T') doesn't match expected type '%T'",
2051 expression, expression->base.type, type);
2056 bool additional_warning_displayed = false;
2057 while (braces > 0) {
2058 if (token.type == ',') {
2061 if (token.type != '}') {
2062 if (!additional_warning_displayed) {
2063 warningf(HERE, "additional elements in scalar initializer");
2064 additional_warning_displayed = true;
2075 * An entry in the type path.
2077 typedef struct type_path_entry_t type_path_entry_t;
2078 struct type_path_entry_t {
2079 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2081 size_t index; /**< For array types: the current index. */
2082 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2087 * A type path expression a position inside compound or array types.
2089 typedef struct type_path_t type_path_t;
2090 struct type_path_t {
2091 type_path_entry_t *path; /**< An flexible array containing the current path. */
2092 type_t *top_type; /**< type of the element the path points */
2093 size_t max_index; /**< largest index in outermost array */
2097 * Prints a type path for debugging.
2099 static __attribute__((unused)) void debug_print_type_path(
2100 const type_path_t *path)
2102 size_t len = ARR_LEN(path->path);
2104 for(size_t i = 0; i < len; ++i) {
2105 const type_path_entry_t *entry = & path->path[i];
2107 type_t *type = skip_typeref(entry->type);
2108 if (is_type_compound(type)) {
2109 /* in gcc mode structs can have no members */
2110 if (entry->v.compound_entry == NULL) {
2114 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2115 } else if (is_type_array(type)) {
2116 fprintf(stderr, "[%zu]", entry->v.index);
2118 fprintf(stderr, "-INVALID-");
2121 if (path->top_type != NULL) {
2122 fprintf(stderr, " (");
2123 print_type(path->top_type);
2124 fprintf(stderr, ")");
2129 * Return the top type path entry, ie. in a path
2130 * (type).a.b returns the b.
2132 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2134 size_t len = ARR_LEN(path->path);
2136 return &path->path[len-1];
2140 * Enlarge the type path by an (empty) element.
2142 static type_path_entry_t *append_to_type_path(type_path_t *path)
2144 size_t len = ARR_LEN(path->path);
2145 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2147 type_path_entry_t *result = & path->path[len];
2148 memset(result, 0, sizeof(result[0]));
2153 * Descending into a sub-type. Enter the scope of the current
2156 static void descend_into_subtype(type_path_t *path)
2158 type_t *orig_top_type = path->top_type;
2159 type_t *top_type = skip_typeref(orig_top_type);
2161 type_path_entry_t *top = append_to_type_path(path);
2162 top->type = top_type;
2164 if (is_type_compound(top_type)) {
2165 declaration_t *declaration = top_type->compound.declaration;
2166 declaration_t *entry = declaration->scope.declarations;
2167 top->v.compound_entry = entry;
2169 if (entry != NULL) {
2170 path->top_type = entry->type;
2172 path->top_type = NULL;
2174 } else if (is_type_array(top_type)) {
2176 path->top_type = top_type->array.element_type;
2178 assert(!is_type_valid(top_type));
2183 * Pop an entry from the given type path, ie. returning from
2184 * (type).a.b to (type).a
2186 static void ascend_from_subtype(type_path_t *path)
2188 type_path_entry_t *top = get_type_path_top(path);
2190 path->top_type = top->type;
2192 size_t len = ARR_LEN(path->path);
2193 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2197 * Pop entries from the given type path until the given
2198 * path level is reached.
2200 static void ascend_to(type_path_t *path, size_t top_path_level)
2202 size_t len = ARR_LEN(path->path);
2204 while (len > top_path_level) {
2205 ascend_from_subtype(path);
2206 len = ARR_LEN(path->path);
2210 static bool walk_designator(type_path_t *path, const designator_t *designator,
2211 bool used_in_offsetof)
2213 for( ; designator != NULL; designator = designator->next) {
2214 type_path_entry_t *top = get_type_path_top(path);
2215 type_t *orig_type = top->type;
2217 type_t *type = skip_typeref(orig_type);
2219 if (designator->symbol != NULL) {
2220 symbol_t *symbol = designator->symbol;
2221 if (!is_type_compound(type)) {
2222 if (is_type_valid(type)) {
2223 errorf(&designator->source_position,
2224 "'.%Y' designator used for non-compound type '%T'",
2230 declaration_t *declaration = type->compound.declaration;
2231 declaration_t *iter = declaration->scope.declarations;
2232 for( ; iter != NULL; iter = iter->next) {
2233 if (iter->symbol == symbol) {
2238 errorf(&designator->source_position,
2239 "'%T' has no member named '%Y'", orig_type, symbol);
2242 if (used_in_offsetof) {
2243 type_t *real_type = skip_typeref(iter->type);
2244 if (real_type->kind == TYPE_BITFIELD) {
2245 errorf(&designator->source_position,
2246 "offsetof designator '%Y' may not specify bitfield",
2252 top->type = orig_type;
2253 top->v.compound_entry = iter;
2254 orig_type = iter->type;
2256 expression_t *array_index = designator->array_index;
2257 assert(designator->array_index != NULL);
2259 if (!is_type_array(type)) {
2260 if (is_type_valid(type)) {
2261 errorf(&designator->source_position,
2262 "[%E] designator used for non-array type '%T'",
2263 array_index, orig_type);
2267 if (!is_type_valid(array_index->base.type)) {
2271 long index = fold_constant(array_index);
2272 if (!used_in_offsetof) {
2274 errorf(&designator->source_position,
2275 "array index [%E] must be positive", array_index);
2278 if (type->array.size_constant == true) {
2279 long array_size = type->array.size;
2280 if (index >= array_size) {
2281 errorf(&designator->source_position,
2282 "designator [%E] (%d) exceeds array size %d",
2283 array_index, index, array_size);
2289 top->type = orig_type;
2290 top->v.index = (size_t) index;
2291 orig_type = type->array.element_type;
2293 path->top_type = orig_type;
2295 if (designator->next != NULL) {
2296 descend_into_subtype(path);
2305 static void advance_current_object(type_path_t *path, size_t top_path_level)
2307 type_path_entry_t *top = get_type_path_top(path);
2309 type_t *type = skip_typeref(top->type);
2310 if (is_type_union(type)) {
2311 /* in unions only the first element is initialized */
2312 top->v.compound_entry = NULL;
2313 } else if (is_type_struct(type)) {
2314 declaration_t *entry = top->v.compound_entry;
2316 entry = entry->next;
2317 top->v.compound_entry = entry;
2318 if (entry != NULL) {
2319 path->top_type = entry->type;
2323 assert(is_type_array(type));
2327 if (!type->array.size_constant || top->v.index < type->array.size) {
2332 /* we're past the last member of the current sub-aggregate, try if we
2333 * can ascend in the type hierarchy and continue with another subobject */
2334 size_t len = ARR_LEN(path->path);
2336 if (len > top_path_level) {
2337 ascend_from_subtype(path);
2338 advance_current_object(path, top_path_level);
2340 path->top_type = NULL;
2345 * skip until token is found.
2347 static void skip_until(int type)
2349 while (token.type != type) {
2350 if (token.type == T_EOF)
2357 * skip any {...} blocks until a closing bracket is reached.
2359 static void skip_initializers(void)
2361 if (token.type == '{')
2364 while (token.type != '}') {
2365 if (token.type == T_EOF)
2367 if (token.type == '{') {
2375 static initializer_t *create_empty_initializer(void)
2377 static initializer_t empty_initializer
2378 = { .list = { { INITIALIZER_LIST }, 0 } };
2379 return &empty_initializer;
2383 * Parse a part of an initialiser for a struct or union,
2385 static initializer_t *parse_sub_initializer(type_path_t *path,
2386 type_t *outer_type, size_t top_path_level,
2387 parse_initializer_env_t *env)
2389 if (token.type == '}') {
2390 /* empty initializer */
2391 return create_empty_initializer();
2394 type_t *orig_type = path->top_type;
2395 type_t *type = NULL;
2397 if (orig_type == NULL) {
2398 /* We are initializing an empty compound. */
2400 type = skip_typeref(orig_type);
2402 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2403 * initializers in this case. */
2404 if (!is_type_valid(type)) {
2405 skip_initializers();
2406 return create_empty_initializer();
2410 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2413 designator_t *designator = NULL;
2414 if (token.type == '.' || token.type == '[') {
2415 designator = parse_designation();
2416 goto finish_designator;
2417 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2418 /* GNU-style designator ("identifier: value") */
2419 designator = allocate_ast_zero(sizeof(designator[0]));
2420 designator->source_position = token.source_position;
2421 designator->symbol = token.v.symbol;
2426 /* reset path to toplevel, evaluate designator from there */
2427 ascend_to(path, top_path_level);
2428 if (!walk_designator(path, designator, false)) {
2429 /* can't continue after designation error */
2433 initializer_t *designator_initializer
2434 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2435 designator_initializer->designator.designator = designator;
2436 ARR_APP1(initializer_t*, initializers, designator_initializer);
2438 orig_type = path->top_type;
2439 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2444 if (token.type == '{') {
2445 if (type != NULL && is_type_scalar(type)) {
2446 sub = parse_scalar_initializer(type, env->must_be_constant);
2450 if (env->declaration != NULL) {
2451 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2452 env->declaration->symbol);
2454 errorf(HERE, "extra brace group at end of initializer");
2457 descend_into_subtype(path);
2459 add_anchor_token('}');
2460 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2462 rem_anchor_token('}');
2465 ascend_from_subtype(path);
2469 goto error_parse_next;
2473 /* must be an expression */
2474 expression_t *expression = parse_assignment_expression();
2476 if (env->must_be_constant && !is_initializer_constant(expression)) {
2477 errorf(&expression->base.source_position,
2478 "Initialisation expression '%E' is not constant\n",
2483 /* we are already outside, ... */
2484 if (is_type_compound(outer_type) &&
2485 !outer_type->compound.declaration->init.complete) {
2486 goto error_parse_next;
2491 /* handle { "string" } special case */
2492 if ((expression->kind == EXPR_STRING_LITERAL
2493 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2494 && outer_type != NULL) {
2495 sub = initializer_from_expression(outer_type, expression);
2497 if (token.type == ',') {
2500 if (token.type != '}') {
2501 warningf(HERE, "excessive elements in initializer for type '%T'",
2504 /* TODO: eat , ... */
2509 /* descend into subtypes until expression matches type */
2511 orig_type = path->top_type;
2512 type = skip_typeref(orig_type);
2514 sub = initializer_from_expression(orig_type, expression);
2518 if (!is_type_valid(type)) {
2521 if (is_type_scalar(type)) {
2522 errorf(&expression->base.source_position,
2523 "expression '%E' doesn't match expected type '%T'",
2524 expression, orig_type);
2528 descend_into_subtype(path);
2532 /* update largest index of top array */
2533 const type_path_entry_t *first = &path->path[0];
2534 type_t *first_type = first->type;
2535 first_type = skip_typeref(first_type);
2536 if (is_type_array(first_type)) {
2537 size_t index = first->v.index;
2538 if (index > path->max_index)
2539 path->max_index = index;
2543 /* append to initializers list */
2544 ARR_APP1(initializer_t*, initializers, sub);
2547 if (env->declaration != NULL)
2548 warningf(HERE, "excess elements in struct initializer for '%Y'",
2549 env->declaration->symbol);
2551 warningf(HERE, "excess elements in struct initializer");
2555 if (token.type == '}') {
2559 if (token.type == '}') {
2564 /* advance to the next declaration if we are not at the end */
2565 advance_current_object(path, top_path_level);
2566 orig_type = path->top_type;
2567 if (orig_type != NULL)
2568 type = skip_typeref(orig_type);
2574 size_t len = ARR_LEN(initializers);
2575 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2576 initializer_t *result = allocate_ast_zero(size);
2577 result->kind = INITIALIZER_LIST;
2578 result->list.len = len;
2579 memcpy(&result->list.initializers, initializers,
2580 len * sizeof(initializers[0]));
2582 DEL_ARR_F(initializers);
2583 ascend_to(path, top_path_level+1);
2588 skip_initializers();
2589 DEL_ARR_F(initializers);
2590 ascend_to(path, top_path_level+1);
2595 * Parses an initializer. Parsers either a compound literal
2596 * (env->declaration == NULL) or an initializer of a declaration.
2598 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2600 type_t *type = skip_typeref(env->type);
2601 initializer_t *result = NULL;
2604 if (is_type_scalar(type)) {
2605 result = parse_scalar_initializer(type, env->must_be_constant);
2606 } else if (token.type == '{') {
2610 memset(&path, 0, sizeof(path));
2611 path.top_type = env->type;
2612 path.path = NEW_ARR_F(type_path_entry_t, 0);
2614 descend_into_subtype(&path);
2616 add_anchor_token('}');
2617 result = parse_sub_initializer(&path, env->type, 1, env);
2618 rem_anchor_token('}');
2620 max_index = path.max_index;
2621 DEL_ARR_F(path.path);
2625 /* parse_scalar_initializer() also works in this case: we simply
2626 * have an expression without {} around it */
2627 result = parse_scalar_initializer(type, env->must_be_constant);
2630 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2631 * the array type size */
2632 if (is_type_array(type) && type->array.size_expression == NULL
2633 && result != NULL) {
2635 switch (result->kind) {
2636 case INITIALIZER_LIST:
2637 size = max_index + 1;
2640 case INITIALIZER_STRING:
2641 size = result->string.string.size;
2644 case INITIALIZER_WIDE_STRING:
2645 size = result->wide_string.string.size;
2648 case INITIALIZER_DESIGNATOR:
2649 case INITIALIZER_VALUE:
2650 /* can happen for parse errors */
2655 internal_errorf(HERE, "invalid initializer type");
2658 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2659 cnst->base.type = type_size_t;
2660 cnst->conste.v.int_value = size;
2662 type_t *new_type = duplicate_type(type);
2664 new_type->array.size_expression = cnst;
2665 new_type->array.size_constant = true;
2666 new_type->array.size = size;
2667 env->type = new_type;
2675 static declaration_t *append_declaration(declaration_t *declaration);
2677 static declaration_t *parse_compound_type_specifier(bool is_struct)
2679 gnu_attribute_t *attributes = NULL;
2680 decl_modifiers_t modifiers = 0;
2687 symbol_t *symbol = NULL;
2688 declaration_t *declaration = NULL;
2690 if (token.type == T___attribute__) {
2691 modifiers |= parse_attributes(&attributes);
2694 if (token.type == T_IDENTIFIER) {
2695 symbol = token.v.symbol;
2698 namespace_t const namespc =
2699 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2700 declaration = get_declaration(symbol, namespc);
2701 if (declaration != NULL) {
2702 if (declaration->parent_scope != scope &&
2703 (token.type == '{' || token.type == ';')) {
2705 } else if (declaration->init.complete &&
2706 token.type == '{') {
2707 assert(symbol != NULL);
2708 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2709 is_struct ? "struct" : "union", symbol,
2710 &declaration->source_position);
2711 declaration->scope.declarations = NULL;
2714 } else if (token.type != '{') {
2716 parse_error_expected("while parsing struct type specifier",
2717 T_IDENTIFIER, '{', NULL);
2719 parse_error_expected("while parsing union type specifier",
2720 T_IDENTIFIER, '{', NULL);
2726 if (declaration == NULL) {
2727 declaration = allocate_declaration_zero();
2728 declaration->namespc =
2729 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2730 declaration->source_position = token.source_position;
2731 declaration->symbol = symbol;
2732 declaration->parent_scope = scope;
2733 if (symbol != NULL) {
2734 environment_push(declaration);
2736 append_declaration(declaration);
2739 if (token.type == '{') {
2740 declaration->init.complete = true;
2742 parse_compound_type_entries(declaration);
2743 modifiers |= parse_attributes(&attributes);
2746 declaration->modifiers |= modifiers;
2750 static void parse_enum_entries(type_t *const enum_type)
2754 if (token.type == '}') {
2756 errorf(HERE, "empty enum not allowed");
2760 add_anchor_token('}');
2762 if (token.type != T_IDENTIFIER) {
2763 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2765 rem_anchor_token('}');
2769 declaration_t *const entry = allocate_declaration_zero();
2770 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2771 entry->type = enum_type;
2772 entry->symbol = token.v.symbol;
2773 entry->source_position = token.source_position;
2776 if (token.type == '=') {
2778 expression_t *value = parse_constant_expression();
2780 value = create_implicit_cast(value, enum_type);
2781 entry->init.enum_value = value;
2786 record_declaration(entry, false);
2788 if (token.type != ',')
2791 } while (token.type != '}');
2792 rem_anchor_token('}');
2800 static type_t *parse_enum_specifier(void)
2802 gnu_attribute_t *attributes = NULL;
2803 declaration_t *declaration;
2807 if (token.type == T_IDENTIFIER) {
2808 symbol = token.v.symbol;
2811 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2812 } else if (token.type != '{') {
2813 parse_error_expected("while parsing enum type specifier",
2814 T_IDENTIFIER, '{', NULL);
2821 if (declaration == NULL) {
2822 declaration = allocate_declaration_zero();
2823 declaration->namespc = NAMESPACE_ENUM;
2824 declaration->source_position = token.source_position;
2825 declaration->symbol = symbol;
2826 declaration->parent_scope = scope;
2829 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2830 type->enumt.declaration = declaration;
2832 if (token.type == '{') {
2833 if (declaration->init.complete) {
2834 errorf(HERE, "multiple definitions of enum %Y", symbol);
2836 if (symbol != NULL) {
2837 environment_push(declaration);
2839 append_declaration(declaration);
2840 declaration->init.complete = true;
2842 parse_enum_entries(type);
2843 parse_attributes(&attributes);
2850 * if a symbol is a typedef to another type, return true
2852 static bool is_typedef_symbol(symbol_t *symbol)
2854 const declaration_t *const declaration =
2855 get_declaration(symbol, NAMESPACE_NORMAL);
2857 declaration != NULL &&
2858 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2861 static type_t *parse_typeof(void)
2868 add_anchor_token(')');
2870 expression_t *expression = NULL;
2872 bool old_type_prop = in_type_prop;
2873 bool old_gcc_extension = in_gcc_extension;
2874 in_type_prop = true;
2876 while (token.type == T___extension__) {
2877 /* This can be a prefix to a typename or an expression. */
2879 in_gcc_extension = true;
2881 switch (token.type) {
2883 if (is_typedef_symbol(token.v.symbol)) {
2884 type = parse_typename();
2886 expression = parse_expression();
2887 type = expression->base.type;
2892 type = parse_typename();
2896 expression = parse_expression();
2897 type = expression->base.type;
2900 in_type_prop = old_type_prop;
2901 in_gcc_extension = old_gcc_extension;
2903 rem_anchor_token(')');
2906 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2907 typeof_type->typeoft.expression = expression;
2908 typeof_type->typeoft.typeof_type = type;
2915 typedef enum specifiers_t {
2916 SPECIFIER_SIGNED = 1 << 0,
2917 SPECIFIER_UNSIGNED = 1 << 1,
2918 SPECIFIER_LONG = 1 << 2,
2919 SPECIFIER_INT = 1 << 3,
2920 SPECIFIER_DOUBLE = 1 << 4,
2921 SPECIFIER_CHAR = 1 << 5,
2922 SPECIFIER_SHORT = 1 << 6,
2923 SPECIFIER_LONG_LONG = 1 << 7,
2924 SPECIFIER_FLOAT = 1 << 8,
2925 SPECIFIER_BOOL = 1 << 9,
2926 SPECIFIER_VOID = 1 << 10,
2927 SPECIFIER_INT8 = 1 << 11,
2928 SPECIFIER_INT16 = 1 << 12,
2929 SPECIFIER_INT32 = 1 << 13,
2930 SPECIFIER_INT64 = 1 << 14,
2931 SPECIFIER_INT128 = 1 << 15,
2932 SPECIFIER_COMPLEX = 1 << 16,
2933 SPECIFIER_IMAGINARY = 1 << 17,
2936 static type_t *create_builtin_type(symbol_t *const symbol,
2937 type_t *const real_type)
2939 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2940 type->builtin.symbol = symbol;
2941 type->builtin.real_type = real_type;
2943 type_t *result = typehash_insert(type);
2944 if (type != result) {
2951 static type_t *get_typedef_type(symbol_t *symbol)
2953 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2954 if (declaration == NULL ||
2955 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2958 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2959 type->typedeft.declaration = declaration;
2965 * check for the allowed MS alignment values.
2967 static bool check_alignment_value(long long intvalue)
2969 if (intvalue < 1 || intvalue > 8192) {
2970 errorf(HERE, "illegal alignment value");
2973 unsigned v = (unsigned)intvalue;
2974 for (unsigned i = 1; i <= 8192; i += i) {
2978 errorf(HERE, "alignment must be power of two");
2982 #define DET_MOD(name, tag) do { \
2983 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2984 *modifiers |= tag; \
2987 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2989 decl_modifiers_t *modifiers = &specifiers->modifiers;
2992 if (token.type == T_restrict) {
2994 DET_MOD(restrict, DM_RESTRICT);
2996 } else if (token.type != T_IDENTIFIER)
2998 symbol_t *symbol = token.v.symbol;
2999 if (symbol == sym_align) {
3002 if (token.type != T_INTEGER)
3004 if (check_alignment_value(token.v.intvalue)) {
3005 if (specifiers->alignment != 0)
3006 warningf(HERE, "align used more than once");
3007 specifiers->alignment = (unsigned char)token.v.intvalue;
3011 } else if (symbol == sym_allocate) {
3014 if (token.type != T_IDENTIFIER)
3016 (void)token.v.symbol;
3018 } else if (symbol == sym_dllimport) {
3020 DET_MOD(dllimport, DM_DLLIMPORT);
3021 } else if (symbol == sym_dllexport) {
3023 DET_MOD(dllexport, DM_DLLEXPORT);
3024 } else if (symbol == sym_thread) {
3026 DET_MOD(thread, DM_THREAD);
3027 } else if (symbol == sym_naked) {
3029 DET_MOD(naked, DM_NAKED);
3030 } else if (symbol == sym_noinline) {
3032 DET_MOD(noinline, DM_NOINLINE);
3033 } else if (symbol == sym_noreturn) {
3035 DET_MOD(noreturn, DM_NORETURN);
3036 } else if (symbol == sym_nothrow) {
3038 DET_MOD(nothrow, DM_NOTHROW);
3039 } else if (symbol == sym_novtable) {
3041 DET_MOD(novtable, DM_NOVTABLE);
3042 } else if (symbol == sym_property) {
3046 bool is_get = false;
3047 if (token.type != T_IDENTIFIER)
3049 if (token.v.symbol == sym_get) {
3051 } else if (token.v.symbol == sym_put) {
3053 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3058 if (token.type != T_IDENTIFIER)
3061 if (specifiers->get_property_sym != NULL) {
3062 errorf(HERE, "get property name already specified");
3064 specifiers->get_property_sym = token.v.symbol;
3067 if (specifiers->put_property_sym != NULL) {
3068 errorf(HERE, "put property name already specified");
3070 specifiers->put_property_sym = token.v.symbol;
3074 if (token.type == ',') {
3081 } else if (symbol == sym_selectany) {
3083 DET_MOD(selectany, DM_SELECTANY);
3084 } else if (symbol == sym_uuid) {
3087 if (token.type != T_STRING_LITERAL)
3091 } else if (symbol == sym_deprecated) {
3093 if (specifiers->deprecated != 0)
3094 warningf(HERE, "deprecated used more than once");
3095 specifiers->deprecated = 1;
3096 if (token.type == '(') {
3098 if (token.type == T_STRING_LITERAL) {
3099 specifiers->deprecated_string = token.v.string.begin;
3102 errorf(HERE, "string literal expected");
3106 } else if (symbol == sym_noalias) {
3108 DET_MOD(noalias, DM_NOALIAS);
3110 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3112 if (token.type == '(')
3116 if (token.type == ',')
3123 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3125 declaration_t *const decl = allocate_declaration_zero();
3126 decl->source_position = *HERE;
3127 decl->declared_storage_class = storage_class;
3128 decl->storage_class =
3129 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3130 storage_class : STORAGE_CLASS_AUTO;
3131 decl->symbol = symbol;
3132 decl->implicit = true;
3133 record_declaration(decl, false);
3138 * Finish the construction of a struct type by calculating
3139 * its size, offsets, alignment.
3141 static void finish_struct_type(compound_type_t *type) {
3142 if (type->declaration == NULL)
3144 declaration_t *struct_decl = type->declaration;
3145 if (! struct_decl->init.complete)
3150 il_alignment_t alignment = 1;
3151 bool need_pad = false;
3153 declaration_t *entry = struct_decl->scope.declarations;
3154 for (; entry != NULL; entry = entry->next) {
3155 if (entry->namespc != NAMESPACE_NORMAL)
3158 type_t *m_type = skip_typeref(entry->type);
3159 if (! is_type_valid(m_type)) {
3160 /* simply ignore errors here */
3163 il_alignment_t m_alignment = m_type->base.alignment;
3164 if (m_alignment > alignment)
3165 alignment = m_alignment;
3167 offset = (size + m_alignment - 1) & -m_alignment;
3171 entry->offset = offset;
3172 size = offset + m_type->base.size;
3174 if (type->base.alignment != 0) {
3175 alignment = type->base.alignment;
3178 offset = (size + alignment - 1) & -alignment;
3182 if (warning.padded && need_pad) {
3183 warningf(&struct_decl->source_position,
3184 "'%#T' needs padding", type, struct_decl->symbol);
3186 if (warning.packed && !need_pad) {
3187 warningf(&struct_decl->source_position,
3188 "superfluous packed attribute on '%#T'",
3189 type, struct_decl->symbol);
3192 type->base.size = offset;
3193 type->base.alignment = alignment;
3197 * Finish the construction of an union type by calculating
3198 * its size and alignment.
3200 static void finish_union_type(compound_type_t *type) {
3201 if (type->declaration == NULL)
3203 declaration_t *union_decl = type->declaration;
3204 if (! union_decl->init.complete)
3208 il_alignment_t alignment = 1;
3210 declaration_t *entry = union_decl->scope.declarations;
3211 for (; entry != NULL; entry = entry->next) {
3212 if (entry->namespc != NAMESPACE_NORMAL)
3215 type_t *m_type = skip_typeref(entry->type);
3216 if (! is_type_valid(m_type))
3220 if (m_type->base.size > size)
3221 size = m_type->base.size;
3222 if (m_type->base.alignment > alignment)
3223 alignment = m_type->base.alignment;
3225 if (type->base.alignment != 0) {
3226 alignment = type->base.alignment;
3228 size = (size + alignment - 1) & -alignment;
3229 type->base.size = size;
3230 type->base.alignment = alignment;
3233 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3235 type_t *type = NULL;
3236 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3237 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3238 unsigned type_specifiers = 0;
3239 bool newtype = false;
3240 bool saw_error = false;
3241 bool old_gcc_extension = in_gcc_extension;
3243 specifiers->source_position = token.source_position;
3246 specifiers->modifiers
3247 |= parse_attributes(&specifiers->gnu_attributes);
3248 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3249 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3251 switch (token.type) {
3254 #define MATCH_STORAGE_CLASS(token, class) \
3256 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3257 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3259 specifiers->declared_storage_class = class; \
3263 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3264 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3265 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3266 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3267 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3272 add_anchor_token(')');
3273 parse_microsoft_extended_decl_modifier(specifiers);
3274 rem_anchor_token(')');
3279 switch (specifiers->declared_storage_class) {
3280 case STORAGE_CLASS_NONE:
3281 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3284 case STORAGE_CLASS_EXTERN:
3285 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3288 case STORAGE_CLASS_STATIC:
3289 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3293 errorf(HERE, "multiple storage classes in declaration specifiers");
3299 /* type qualifiers */
3300 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3302 qualifiers |= qualifier; \
3306 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3307 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3308 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3309 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3310 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3311 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3312 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3313 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3315 case T___extension__:
3317 in_gcc_extension = true;
3320 /* type specifiers */
3321 #define MATCH_SPECIFIER(token, specifier, name) \
3324 if (type_specifiers & specifier) { \
3325 errorf(HERE, "multiple " name " type specifiers given"); \
3327 type_specifiers |= specifier; \
3331 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3332 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3333 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3334 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3335 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3336 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3337 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3338 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3339 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3340 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3341 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3342 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3343 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3344 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3345 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3346 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3348 case T__forceinline:
3349 /* only in microsoft mode */
3350 specifiers->modifiers |= DM_FORCEINLINE;
3355 specifiers->is_inline = true;
3360 if (type_specifiers & SPECIFIER_LONG_LONG) {
3361 errorf(HERE, "multiple type specifiers given");
3362 } else if (type_specifiers & SPECIFIER_LONG) {
3363 type_specifiers |= SPECIFIER_LONG_LONG;
3365 type_specifiers |= SPECIFIER_LONG;
3370 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3372 type->compound.declaration = parse_compound_type_specifier(true);
3373 finish_struct_type(&type->compound);
3377 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3378 type->compound.declaration = parse_compound_type_specifier(false);
3379 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3380 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3382 finish_union_type(&type->compound);
3385 type = parse_enum_specifier();
3388 type = parse_typeof();
3390 case T___builtin_va_list:
3391 type = duplicate_type(type_valist);
3395 case T_IDENTIFIER: {
3396 /* only parse identifier if we haven't found a type yet */
3397 if (type != NULL || type_specifiers != 0) {
3398 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3399 * declaration, so it doesn't generate errors about expecting '(' or
3401 switch (look_ahead(1)->type) {
3408 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3411 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3416 goto finish_specifiers;
3420 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3421 if (typedef_type == NULL) {
3422 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3423 * declaration, so it doesn't generate 'implicit int' followed by more
3424 * errors later on. */
3425 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3430 errorf(HERE, "%K does not name a type", &token);
3432 declaration_t *const decl =
3433 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3435 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3436 type->typedeft.declaration = decl;
3440 if (la1_type == '*')
3441 goto finish_specifiers;
3446 goto finish_specifiers;
3451 type = typedef_type;
3455 /* function specifier */
3457 goto finish_specifiers;
3462 in_gcc_extension = old_gcc_extension;
3464 if (type == NULL || (saw_error && type_specifiers != 0)) {
3465 atomic_type_kind_t atomic_type;
3467 /* match valid basic types */
3468 switch(type_specifiers) {
3469 case SPECIFIER_VOID:
3470 atomic_type = ATOMIC_TYPE_VOID;
3472 case SPECIFIER_CHAR:
3473 atomic_type = ATOMIC_TYPE_CHAR;
3475 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3476 atomic_type = ATOMIC_TYPE_SCHAR;
3478 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3479 atomic_type = ATOMIC_TYPE_UCHAR;
3481 case SPECIFIER_SHORT:
3482 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3483 case SPECIFIER_SHORT | SPECIFIER_INT:
3484 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3485 atomic_type = ATOMIC_TYPE_SHORT;
3487 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3488 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3489 atomic_type = ATOMIC_TYPE_USHORT;
3492 case SPECIFIER_SIGNED:
3493 case SPECIFIER_SIGNED | SPECIFIER_INT:
3494 atomic_type = ATOMIC_TYPE_INT;
3496 case SPECIFIER_UNSIGNED:
3497 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3498 atomic_type = ATOMIC_TYPE_UINT;
3500 case SPECIFIER_LONG:
3501 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3502 case SPECIFIER_LONG | SPECIFIER_INT:
3503 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3504 atomic_type = ATOMIC_TYPE_LONG;
3506 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3507 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3508 atomic_type = ATOMIC_TYPE_ULONG;
3511 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3512 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3513 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3514 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3516 atomic_type = ATOMIC_TYPE_LONGLONG;
3517 goto warn_about_long_long;
3519 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3520 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3522 atomic_type = ATOMIC_TYPE_ULONGLONG;
3523 warn_about_long_long:
3524 if (warning.long_long) {
3525 warningf(&specifiers->source_position,
3526 "ISO C90 does not support 'long long'");
3530 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3531 atomic_type = unsigned_int8_type_kind;
3534 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3535 atomic_type = unsigned_int16_type_kind;
3538 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3539 atomic_type = unsigned_int32_type_kind;
3542 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3543 atomic_type = unsigned_int64_type_kind;
3546 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3547 atomic_type = unsigned_int128_type_kind;
3550 case SPECIFIER_INT8:
3551 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3552 atomic_type = int8_type_kind;
3555 case SPECIFIER_INT16:
3556 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3557 atomic_type = int16_type_kind;
3560 case SPECIFIER_INT32:
3561 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3562 atomic_type = int32_type_kind;
3565 case SPECIFIER_INT64:
3566 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3567 atomic_type = int64_type_kind;
3570 case SPECIFIER_INT128:
3571 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3572 atomic_type = int128_type_kind;
3575 case SPECIFIER_FLOAT:
3576 atomic_type = ATOMIC_TYPE_FLOAT;
3578 case SPECIFIER_DOUBLE:
3579 atomic_type = ATOMIC_TYPE_DOUBLE;
3581 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3582 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3584 case SPECIFIER_BOOL:
3585 atomic_type = ATOMIC_TYPE_BOOL;
3587 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3588 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3589 atomic_type = ATOMIC_TYPE_FLOAT;
3591 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3592 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3593 atomic_type = ATOMIC_TYPE_DOUBLE;
3595 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3596 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3597 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3600 /* invalid specifier combination, give an error message */
3601 if (type_specifiers == 0) {
3606 if (warning.implicit_int) {
3607 warningf(HERE, "no type specifiers in declaration, using 'int'");
3609 atomic_type = ATOMIC_TYPE_INT;
3612 errorf(HERE, "no type specifiers given in declaration");
3614 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3615 (type_specifiers & SPECIFIER_UNSIGNED)) {
3616 errorf(HERE, "signed and unsigned specifiers given");
3617 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3618 errorf(HERE, "only integer types can be signed or unsigned");
3620 errorf(HERE, "multiple datatypes in declaration");
3625 if (type_specifiers & SPECIFIER_COMPLEX) {
3626 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3627 type->complex.akind = atomic_type;
3628 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3629 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3630 type->imaginary.akind = atomic_type;
3632 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3633 type->atomic.akind = atomic_type;
3636 } else if (type_specifiers != 0) {
3637 errorf(HERE, "multiple datatypes in declaration");
3640 /* FIXME: check type qualifiers here */
3642 type->base.qualifiers = qualifiers;
3643 type->base.modifiers = modifiers;
3645 type_t *result = typehash_insert(type);
3646 if (newtype && result != type) {
3650 specifiers->type = result;
3654 specifiers->type = type_error_type;
3658 static type_qualifiers_t parse_type_qualifiers(void)
3660 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3663 switch(token.type) {
3664 /* type qualifiers */
3665 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3666 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3667 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3668 /* microsoft extended type modifiers */
3669 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3670 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3671 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3672 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3673 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3682 * Parses an K&R identifier list and return a list of declarations.
3684 * @param last points to the last declaration in the list
3685 * @return the list of declarations
3687 static declaration_t *parse_identifier_list(declaration_t **last)
3689 declaration_t *declarations = NULL;
3690 declaration_t *last_declaration = NULL;
3692 declaration_t *const declaration = allocate_declaration_zero();
3693 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3694 declaration->source_position = token.source_position;
3695 declaration->symbol = token.v.symbol;
3698 if (last_declaration != NULL) {
3699 last_declaration->next = declaration;
3701 declarations = declaration;
3703 last_declaration = declaration;
3705 if (token.type != ',') {
3709 } while (token.type == T_IDENTIFIER);
3711 *last = last_declaration;
3712 return declarations;
3715 static type_t *automatic_type_conversion(type_t *orig_type);
3717 static void semantic_parameter(declaration_t *declaration)
3719 /* TODO: improve error messages */
3720 source_position_t const* const pos = &declaration->source_position;
3722 switch (declaration->declared_storage_class) {
3723 case STORAGE_CLASS_TYPEDEF:
3724 errorf(pos, "typedef not allowed in parameter list");
3727 /* Allowed storage classes */
3728 case STORAGE_CLASS_NONE:
3729 case STORAGE_CLASS_REGISTER:
3733 errorf(pos, "parameter may only have none or register storage class");
3737 type_t *const orig_type = declaration->type;
3738 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3739 * sugar. Turn it into a pointer.
3740 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3741 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3743 type_t *const type = automatic_type_conversion(orig_type);
3744 declaration->type = type;
3746 if (is_type_incomplete(skip_typeref(type))) {
3747 errorf(pos, "parameter '%#T' is of incomplete type",
3748 orig_type, declaration->symbol);
3752 static declaration_t *parse_parameter(void)
3754 declaration_specifiers_t specifiers;
3755 memset(&specifiers, 0, sizeof(specifiers));
3757 parse_declaration_specifiers(&specifiers);
3759 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3765 * Parses a function type parameter list and return a list of declarations.
3767 * @param last point to the last element of the list
3768 * @return the parameter list
3770 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
3772 declaration_t *declarations = NULL;
3775 add_anchor_token(')');
3776 int saved_comma_state = save_and_reset_anchor_state(',');
3778 if (token.type == T_IDENTIFIER &&
3779 !is_typedef_symbol(token.v.symbol)) {
3780 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3781 if (la1_type == ',' || la1_type == ')') {
3782 type->kr_style_parameters = true;
3783 declarations = parse_identifier_list(last);
3784 goto parameters_finished;
3788 if (token.type == ')') {
3789 type->unspecified_parameters = 1;
3790 goto parameters_finished;
3793 declaration_t *declaration;
3794 declaration_t *last_declaration = NULL;
3795 function_parameter_t *parameter;
3796 function_parameter_t *last_parameter = NULL;
3799 switch(token.type) {
3803 goto parameters_finished;
3806 case T___extension__:
3808 declaration = parse_parameter();
3810 /* func(void) is not a parameter */
3811 if (last_parameter == NULL
3812 && token.type == ')'
3813 && declaration->symbol == NULL
3814 && skip_typeref(declaration->type) == type_void) {
3815 goto parameters_finished;
3817 semantic_parameter(declaration);
3819 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3820 memset(parameter, 0, sizeof(parameter[0]));
3821 parameter->type = declaration->type;
3823 if (last_parameter != NULL) {
3824 last_declaration->next = declaration;
3825 last_parameter->next = parameter;
3827 type->parameters = parameter;
3828 declarations = declaration;
3830 last_parameter = parameter;
3831 last_declaration = declaration;
3835 goto parameters_finished;
3837 if (token.type != ',') {
3838 goto parameters_finished;
3844 parameters_finished:
3845 rem_anchor_token(')');
3848 restore_anchor_state(',', saved_comma_state);
3849 *last = last_declaration;
3850 return declarations;
3853 restore_anchor_state(',', saved_comma_state);
3858 typedef enum construct_type_kind_t {
3863 } construct_type_kind_t;
3865 typedef struct construct_type_t construct_type_t;
3866 struct construct_type_t {
3867 construct_type_kind_t kind;
3868 construct_type_t *next;
3871 typedef struct parsed_pointer_t parsed_pointer_t;
3872 struct parsed_pointer_t {
3873 construct_type_t construct_type;
3874 type_qualifiers_t type_qualifiers;
3877 typedef struct construct_function_type_t construct_function_type_t;
3878 struct construct_function_type_t {
3879 construct_type_t construct_type;
3880 type_t *function_type;
3883 typedef struct parsed_array_t parsed_array_t;
3884 struct parsed_array_t {
3885 construct_type_t construct_type;
3886 type_qualifiers_t type_qualifiers;
3892 typedef struct construct_base_type_t construct_base_type_t;
3893 struct construct_base_type_t {
3894 construct_type_t construct_type;
3898 static construct_type_t *parse_pointer_declarator(void)
3902 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3903 memset(pointer, 0, sizeof(pointer[0]));
3904 pointer->construct_type.kind = CONSTRUCT_POINTER;
3905 pointer->type_qualifiers = parse_type_qualifiers();
3907 return (construct_type_t*) pointer;
3910 static construct_type_t *parse_array_declarator(void)
3913 add_anchor_token(']');
3915 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3916 memset(array, 0, sizeof(array[0]));
3917 array->construct_type.kind = CONSTRUCT_ARRAY;
3919 if (token.type == T_static) {
3920 array->is_static = true;
3924 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3925 if (type_qualifiers != 0) {
3926 if (token.type == T_static) {
3927 array->is_static = true;
3931 array->type_qualifiers = type_qualifiers;
3933 if (token.type == '*' && look_ahead(1)->type == ']') {
3934 array->is_variable = true;
3936 } else if (token.type != ']') {
3937 array->size = parse_assignment_expression();
3940 rem_anchor_token(']');
3944 return (construct_type_t*) array;
3947 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3950 if (declaration != NULL) {
3951 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3953 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3955 if (mask & (mask-1)) {
3956 const char *first = NULL, *second = NULL;
3958 /* more than one calling convention set */
3959 if (declaration->modifiers & DM_CDECL) {
3960 if (first == NULL) first = "cdecl";
3961 else if (second == NULL) second = "cdecl";
3963 if (declaration->modifiers & DM_STDCALL) {
3964 if (first == NULL) first = "stdcall";
3965 else if (second == NULL) second = "stdcall";
3967 if (declaration->modifiers & DM_FASTCALL) {
3968 if (first == NULL) first = "fastcall";
3969 else if (second == NULL) second = "fastcall";
3971 if (declaration->modifiers & DM_THISCALL) {
3972 if (first == NULL) first = "thiscall";
3973 else if (second == NULL) second = "thiscall";
3975 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3978 if (declaration->modifiers & DM_CDECL)
3979 type->function.calling_convention = CC_CDECL;
3980 else if (declaration->modifiers & DM_STDCALL)
3981 type->function.calling_convention = CC_STDCALL;
3982 else if (declaration->modifiers & DM_FASTCALL)
3983 type->function.calling_convention = CC_FASTCALL;
3984 else if (declaration->modifiers & DM_THISCALL)
3985 type->function.calling_convention = CC_THISCALL;
3987 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3990 declaration_t *last;
3991 declaration_t *parameters = parse_parameters(&type->function, &last);
3992 if (declaration != NULL) {
3993 declaration->scope.declarations = parameters;
3994 declaration->scope.last_declaration = last;
3995 declaration->scope.is_parameter = true;
3998 construct_function_type_t *construct_function_type =
3999 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4000 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4001 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4002 construct_function_type->function_type = type;
4004 return &construct_function_type->construct_type;
4007 static void fix_declaration_type(declaration_t *declaration)
4009 decl_modifiers_t declaration_modifiers = declaration->modifiers;
4010 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
4012 if (declaration_modifiers & DM_TRANSPARENT_UNION)
4013 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4015 if (declaration->type->base.modifiers == type_modifiers)
4018 type_t *copy = duplicate_type(declaration->type);
4019 copy->base.modifiers = type_modifiers;
4021 type_t *result = typehash_insert(copy);
4022 if (result != copy) {
4023 obstack_free(type_obst, copy);
4026 declaration->type = result;
4029 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4030 bool may_be_abstract)
4032 /* construct a single linked list of construct_type_t's which describe
4033 * how to construct the final declarator type */
4034 construct_type_t *first = NULL;
4035 construct_type_t *last = NULL;
4036 gnu_attribute_t *attributes = NULL;
4038 decl_modifiers_t modifiers = parse_attributes(&attributes);
4041 while (token.type == '*') {
4042 construct_type_t *type = parse_pointer_declarator();
4052 /* TODO: find out if this is correct */
4053 modifiers |= parse_attributes(&attributes);
4056 if (declaration != NULL)
4057 declaration->modifiers |= modifiers;
4059 construct_type_t *inner_types = NULL;
4061 switch(token.type) {
4063 if (declaration == NULL) {
4064 errorf(HERE, "no identifier expected in typename");
4066 declaration->symbol = token.v.symbol;
4067 declaration->source_position = token.source_position;
4073 add_anchor_token(')');
4074 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4075 if (inner_types != NULL) {
4076 /* All later declarators only modify the return type, not declaration */
4079 rem_anchor_token(')');
4083 if (may_be_abstract)
4085 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4090 construct_type_t *p = last;
4093 construct_type_t *type;
4094 switch(token.type) {
4096 type = parse_function_declarator(declaration);
4099 type = parse_array_declarator();
4102 goto declarator_finished;
4105 /* insert in the middle of the list (behind p) */
4107 type->next = p->next;
4118 declarator_finished:
4119 /* append inner_types at the end of the list, we don't to set last anymore
4120 * as it's not needed anymore */
4122 assert(first == NULL);
4123 first = inner_types;
4125 last->next = inner_types;
4133 static void parse_declaration_attributes(declaration_t *declaration)
4135 gnu_attribute_t *attributes = NULL;
4136 decl_modifiers_t modifiers = parse_attributes(&attributes);
4138 if (declaration == NULL)
4141 declaration->modifiers |= modifiers;
4142 /* check if we have these stupid mode attributes... */
4143 type_t *old_type = declaration->type;
4144 if (old_type == NULL)
4147 gnu_attribute_t *attribute = attributes;
4148 for ( ; attribute != NULL; attribute = attribute->next) {
4149 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4152 atomic_type_kind_t akind = attribute->u.akind;
4153 if (!is_type_signed(old_type)) {
4155 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4156 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4157 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4158 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4160 panic("invalid akind in mode attribute");
4164 = make_atomic_type(akind, old_type->base.qualifiers);
4168 static type_t *construct_declarator_type(construct_type_t *construct_list,
4171 construct_type_t *iter = construct_list;
4172 for( ; iter != NULL; iter = iter->next) {
4173 switch(iter->kind) {
4174 case CONSTRUCT_INVALID:
4175 internal_errorf(HERE, "invalid type construction found");
4176 case CONSTRUCT_FUNCTION: {
4177 construct_function_type_t *construct_function_type
4178 = (construct_function_type_t*) iter;
4180 type_t *function_type = construct_function_type->function_type;
4182 function_type->function.return_type = type;
4184 type_t *skipped_return_type = skip_typeref(type);
4186 if (is_type_function(skipped_return_type)) {
4187 errorf(HERE, "function returning function is not allowed");
4188 } else if (is_type_array(skipped_return_type)) {
4189 errorf(HERE, "function returning array is not allowed");
4191 if (skipped_return_type->base.qualifiers != 0) {
4193 "type qualifiers in return type of function type are meaningless");
4197 type = function_type;
4201 case CONSTRUCT_POINTER: {
4202 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4203 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4204 pointer_type->pointer.points_to = type;
4205 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4207 type = pointer_type;
4211 case CONSTRUCT_ARRAY: {
4212 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4213 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4215 expression_t *size_expression = parsed_array->size;
4216 if (size_expression != NULL) {
4218 = create_implicit_cast(size_expression, type_size_t);
4221 array_type->base.qualifiers = parsed_array->type_qualifiers;
4222 array_type->array.element_type = type;
4223 array_type->array.is_static = parsed_array->is_static;
4224 array_type->array.is_variable = parsed_array->is_variable;
4225 array_type->array.size_expression = size_expression;
4227 if (size_expression != NULL) {
4228 if (is_constant_expression(size_expression)) {
4229 array_type->array.size_constant = true;
4230 array_type->array.size
4231 = fold_constant(size_expression);
4233 array_type->array.is_vla = true;
4237 type_t *skipped_type = skip_typeref(type);
4239 if (is_type_incomplete(skipped_type)) {
4240 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4241 } else if (is_type_function(skipped_type)) {
4242 errorf(HERE, "array of functions is not allowed");
4249 type_t *hashed_type = typehash_insert(type);
4250 if (hashed_type != type) {
4251 /* the function type was constructed earlier freeing it here will
4252 * destroy other types... */
4253 if (iter->kind != CONSTRUCT_FUNCTION) {
4263 static declaration_t *parse_declarator(
4264 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4266 declaration_t *const declaration = allocate_declaration_zero();
4267 declaration->source_position = specifiers->source_position;
4268 declaration->declared_storage_class = specifiers->declared_storage_class;
4269 declaration->modifiers = specifiers->modifiers;
4270 declaration->deprecated_string = specifiers->deprecated_string;
4271 declaration->get_property_sym = specifiers->get_property_sym;
4272 declaration->put_property_sym = specifiers->put_property_sym;
4273 declaration->is_inline = specifiers->is_inline;
4275 declaration->storage_class = specifiers->declared_storage_class;
4276 if (declaration->storage_class == STORAGE_CLASS_NONE
4277 && scope != global_scope) {
4278 declaration->storage_class = STORAGE_CLASS_AUTO;
4281 if (specifiers->alignment != 0) {
4282 /* TODO: add checks here */
4283 declaration->alignment = specifiers->alignment;
4286 construct_type_t *construct_type
4287 = parse_inner_declarator(declaration, may_be_abstract);
4288 type_t *const type = specifiers->type;
4289 declaration->type = construct_declarator_type(construct_type, type);
4291 parse_declaration_attributes(declaration);
4293 fix_declaration_type(declaration);
4295 if (construct_type != NULL) {
4296 obstack_free(&temp_obst, construct_type);
4302 static type_t *parse_abstract_declarator(type_t *base_type)
4304 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4306 type_t *result = construct_declarator_type(construct_type, base_type);
4307 if (construct_type != NULL) {
4308 obstack_free(&temp_obst, construct_type);
4314 static declaration_t *append_declaration(declaration_t* const declaration)
4316 if (last_declaration != NULL) {
4317 last_declaration->next = declaration;
4319 scope->declarations = declaration;
4321 last_declaration = declaration;
4326 * Check if the declaration of main is suspicious. main should be a
4327 * function with external linkage, returning int, taking either zero
4328 * arguments, two, or three arguments of appropriate types, ie.
4330 * int main([ int argc, char **argv [, char **env ] ]).
4332 * @param decl the declaration to check
4333 * @param type the function type of the declaration
4335 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4337 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4338 warningf(&decl->source_position,
4339 "'main' is normally a non-static function");
4341 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4342 warningf(&decl->source_position,
4343 "return type of 'main' should be 'int', but is '%T'",
4344 func_type->return_type);
4346 const function_parameter_t *parm = func_type->parameters;
4348 type_t *const first_type = parm->type;
4349 if (!types_compatible(skip_typeref(first_type), type_int)) {
4350 warningf(&decl->source_position,
4351 "first argument of 'main' should be 'int', but is '%T'", first_type);
4355 type_t *const second_type = parm->type;
4356 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4357 warningf(&decl->source_position,
4358 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4362 type_t *const third_type = parm->type;
4363 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4364 warningf(&decl->source_position,
4365 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4369 goto warn_arg_count;
4373 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4379 * Check if a symbol is the equal to "main".
4381 static bool is_sym_main(const symbol_t *const sym)
4383 return strcmp(sym->string, "main") == 0;
4386 static declaration_t *record_declaration(
4387 declaration_t *const declaration,
4388 const bool is_definition)
4390 const symbol_t *const symbol = declaration->symbol;
4391 const namespace_t namespc = (namespace_t)declaration->namespc;
4393 assert(symbol != NULL);
4394 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4396 type_t *const orig_type = declaration->type;
4397 type_t *const type = skip_typeref(orig_type);
4398 if (is_type_function(type) &&
4399 type->function.unspecified_parameters &&
4400 warning.strict_prototypes &&
4401 previous_declaration == NULL) {
4402 warningf(&declaration->source_position,
4403 "function declaration '%#T' is not a prototype",
4407 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4408 check_type_of_main(declaration, &type->function);
4411 if (warning.nested_externs &&
4412 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4413 scope != global_scope) {
4414 warningf(&declaration->source_position,
4415 "nested extern declaration of '%#T'", declaration->type, symbol);
4418 assert(declaration != previous_declaration);
4419 if (previous_declaration != NULL &&
4420 previous_declaration->parent_scope->is_parameter &&
4421 scope->depth == previous_declaration->parent_scope->depth + 1) {
4422 errorf(&declaration->source_position,
4423 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4424 orig_type, symbol, previous_declaration->type, symbol,
4425 &previous_declaration->source_position);
4428 if (previous_declaration != NULL &&
4429 previous_declaration->parent_scope == scope) {
4430 /* can happen for K&R style declarations */
4431 if (previous_declaration->type == NULL) {
4432 previous_declaration->type = declaration->type;
4435 const type_t *prev_type = skip_typeref(previous_declaration->type);
4436 if (!types_compatible(type, prev_type)) {
4437 errorf(&declaration->source_position,
4438 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4439 orig_type, symbol, previous_declaration->type, symbol,
4440 &previous_declaration->source_position);
4442 unsigned old_storage_class = previous_declaration->storage_class;
4443 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4444 errorf(&declaration->source_position,
4445 "redeclaration of enum entry '%Y' (declared %P)",
4446 symbol, &previous_declaration->source_position);
4447 return previous_declaration;
4450 if (warning.redundant_decls &&
4452 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4453 !(previous_declaration->modifiers & DM_USED) &&
4454 !previous_declaration->used) {
4455 warningf(&previous_declaration->source_position,
4456 "unnecessary static forward declaration for '%#T'",
4457 previous_declaration->type, symbol);
4460 unsigned new_storage_class = declaration->storage_class;
4462 if (is_type_incomplete(prev_type)) {
4463 previous_declaration->type = type;
4467 /* pretend no storage class means extern for function
4468 * declarations (except if the previous declaration is neither
4469 * none nor extern) */
4470 if (is_type_function(type)) {
4471 if (prev_type->function.unspecified_parameters) {
4472 previous_declaration->type = type;
4476 switch (old_storage_class) {
4477 case STORAGE_CLASS_NONE:
4478 old_storage_class = STORAGE_CLASS_EXTERN;
4481 case STORAGE_CLASS_EXTERN:
4482 if (is_definition) {
4483 if (warning.missing_prototypes &&
4484 prev_type->function.unspecified_parameters &&
4485 !is_sym_main(symbol)) {
4486 warningf(&declaration->source_position,
4487 "no previous prototype for '%#T'",
4490 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4491 new_storage_class = STORAGE_CLASS_EXTERN;
4500 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4501 new_storage_class == STORAGE_CLASS_EXTERN) {
4502 warn_redundant_declaration:
4503 if (!is_definition &&
4504 warning.redundant_decls &&
4505 is_type_valid(prev_type) &&
4506 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4507 warningf(&declaration->source_position,
4508 "redundant declaration for '%Y' (declared %P)",
4509 symbol, &previous_declaration->source_position);
4511 } else if (current_function == NULL) {
4512 if (old_storage_class != STORAGE_CLASS_STATIC &&
4513 new_storage_class == STORAGE_CLASS_STATIC) {
4514 errorf(&declaration->source_position,
4515 "static declaration of '%Y' follows non-static declaration (declared %P)",
4516 symbol, &previous_declaration->source_position);
4517 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4518 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4519 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4521 goto warn_redundant_declaration;
4523 } else if (is_type_valid(prev_type)) {
4524 if (old_storage_class == new_storage_class) {
4525 errorf(&declaration->source_position,
4526 "redeclaration of '%Y' (declared %P)",
4527 symbol, &previous_declaration->source_position);
4529 errorf(&declaration->source_position,
4530 "redeclaration of '%Y' with different linkage (declared %P)",
4531 symbol, &previous_declaration->source_position);
4536 previous_declaration->modifiers |= declaration->modifiers;
4537 previous_declaration->is_inline |= declaration->is_inline;
4538 return previous_declaration;
4539 } else if (is_type_function(type)) {
4540 if (is_definition &&
4541 declaration->storage_class != STORAGE_CLASS_STATIC) {
4542 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4543 warningf(&declaration->source_position,
4544 "no previous prototype for '%#T'", orig_type, symbol);
4545 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4546 warningf(&declaration->source_position,
4547 "no previous declaration for '%#T'", orig_type,
4552 if (warning.missing_declarations &&
4553 scope == global_scope && (
4554 declaration->storage_class == STORAGE_CLASS_NONE ||
4555 declaration->storage_class == STORAGE_CLASS_THREAD
4557 warningf(&declaration->source_position,
4558 "no previous declaration for '%#T'", orig_type, symbol);
4562 assert(declaration->parent_scope == NULL);
4563 assert(scope != NULL);
4565 declaration->parent_scope = scope;
4567 environment_push(declaration);
4568 return append_declaration(declaration);
4571 static void parser_error_multiple_definition(declaration_t *declaration,
4572 const source_position_t *source_position)
4574 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4575 declaration->symbol, &declaration->source_position);
4578 static bool is_declaration_specifier(const token_t *token,
4579 bool only_specifiers_qualifiers)
4581 switch (token->type) {
4586 return is_typedef_symbol(token->v.symbol);
4588 case T___extension__:
4590 return !only_specifiers_qualifiers;
4597 static void parse_init_declarator_rest(declaration_t *declaration)
4601 type_t *orig_type = declaration->type;
4602 type_t *type = skip_typeref(orig_type);
4604 if (declaration->init.initializer != NULL) {
4605 parser_error_multiple_definition(declaration, HERE);
4608 bool must_be_constant = false;
4609 if (declaration->storage_class == STORAGE_CLASS_STATIC
4610 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4611 || declaration->parent_scope == global_scope) {
4612 must_be_constant = true;
4615 if (is_type_function(type)) {
4616 errorf(&declaration->source_position,
4617 "function '%#T' is initialized like a variable",
4618 orig_type, declaration->symbol);
4619 orig_type = type_error_type;
4622 parse_initializer_env_t env;
4623 env.type = orig_type;
4624 env.must_be_constant = must_be_constant;
4625 env.declaration = current_init_decl = declaration;
4627 initializer_t *initializer = parse_initializer(&env);
4628 current_init_decl = NULL;
4630 if (!is_type_function(type)) {
4631 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4632 * the array type size */
4633 declaration->type = env.type;
4634 declaration->init.initializer = initializer;
4638 /* parse rest of a declaration without any declarator */
4639 static void parse_anonymous_declaration_rest(
4640 const declaration_specifiers_t *specifiers)
4644 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4645 warningf(&specifiers->source_position,
4646 "useless storage class in empty declaration");
4649 type_t *type = specifiers->type;
4650 switch (type->kind) {
4651 case TYPE_COMPOUND_STRUCT:
4652 case TYPE_COMPOUND_UNION: {
4653 if (type->compound.declaration->symbol == NULL) {
4654 warningf(&specifiers->source_position,
4655 "unnamed struct/union that defines no instances");
4664 warningf(&specifiers->source_position, "empty declaration");
4668 #ifdef RECORD_EMPTY_DECLARATIONS
4669 declaration_t *const declaration = allocate_declaration_zero();
4670 declaration->type = specifiers->type;
4671 declaration->declared_storage_class = specifiers->declared_storage_class;
4672 declaration->source_position = specifiers->source_position;
4673 declaration->modifiers = specifiers->modifiers;
4674 declaration->storage_class = STORAGE_CLASS_NONE;
4676 append_declaration(declaration);
4680 static void parse_declaration_rest(declaration_t *ndeclaration,
4681 const declaration_specifiers_t *specifiers,
4682 parsed_declaration_func finished_declaration)
4684 add_anchor_token(';');
4685 add_anchor_token(',');
4687 declaration_t *declaration =
4688 finished_declaration(ndeclaration, token.type == '=');
4690 type_t *orig_type = declaration->type;
4691 type_t *type = skip_typeref(orig_type);
4693 if (type->kind != TYPE_FUNCTION &&
4694 declaration->is_inline &&
4695 is_type_valid(type)) {
4696 warningf(&declaration->source_position,
4697 "variable '%Y' declared 'inline'\n", declaration->symbol);
4700 if (token.type == '=') {
4701 parse_init_declarator_rest(declaration);
4704 if (token.type != ',')
4708 add_anchor_token('=');
4709 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4710 rem_anchor_token('=');
4715 rem_anchor_token(';');
4716 rem_anchor_token(',');
4719 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4721 symbol_t *symbol = declaration->symbol;
4722 if (symbol == NULL) {
4723 errorf(HERE, "anonymous declaration not valid as function parameter");
4726 namespace_t namespc = (namespace_t) declaration->namespc;
4727 if (namespc != NAMESPACE_NORMAL) {
4728 return record_declaration(declaration, false);
4731 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4732 if (previous_declaration == NULL ||
4733 previous_declaration->parent_scope != scope) {
4734 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4739 if (is_definition) {
4740 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4743 if (previous_declaration->type == NULL) {
4744 previous_declaration->type = declaration->type;
4745 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4746 previous_declaration->storage_class = declaration->storage_class;
4747 previous_declaration->parent_scope = scope;
4748 return previous_declaration;
4750 return record_declaration(declaration, false);
4754 static void parse_declaration(parsed_declaration_func finished_declaration)
4756 declaration_specifiers_t specifiers;
4757 memset(&specifiers, 0, sizeof(specifiers));
4759 add_anchor_token(';');
4760 parse_declaration_specifiers(&specifiers);
4761 rem_anchor_token(';');
4763 if (token.type == ';') {
4764 parse_anonymous_declaration_rest(&specifiers);
4766 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4767 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4771 static type_t *get_default_promoted_type(type_t *orig_type)
4773 type_t *result = orig_type;
4775 type_t *type = skip_typeref(orig_type);
4776 if (is_type_integer(type)) {
4777 result = promote_integer(type);
4778 } else if (type == type_float) {
4779 result = type_double;
4785 static void parse_kr_declaration_list(declaration_t *declaration)
4787 type_t *type = skip_typeref(declaration->type);
4788 if (!is_type_function(type))
4791 if (!type->function.kr_style_parameters)
4794 add_anchor_token('{');
4796 /* push function parameters */
4797 size_t const top = environment_top();
4798 scope_push(&declaration->scope);
4800 declaration_t *parameter = declaration->scope.declarations;
4801 for ( ; parameter != NULL; parameter = parameter->next) {
4802 assert(parameter->parent_scope == NULL);
4803 parameter->parent_scope = scope;
4804 environment_push(parameter);
4807 /* parse declaration list */
4808 while (is_declaration_specifier(&token, false)) {
4809 parse_declaration(finished_kr_declaration);
4812 /* pop function parameters */
4813 assert(scope == &declaration->scope);
4815 environment_pop_to(top);
4817 /* update function type */
4818 type_t *new_type = duplicate_type(type);
4820 function_parameter_t *parameters = NULL;
4821 function_parameter_t *last_parameter = NULL;
4823 declaration_t *parameter_declaration = declaration->scope.declarations;
4824 for( ; parameter_declaration != NULL;
4825 parameter_declaration = parameter_declaration->next) {
4826 type_t *parameter_type = parameter_declaration->type;
4827 if (parameter_type == NULL) {
4829 errorf(HERE, "no type specified for function parameter '%Y'",
4830 parameter_declaration->symbol);
4832 if (warning.implicit_int) {
4833 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4834 parameter_declaration->symbol);
4836 parameter_type = type_int;
4837 parameter_declaration->type = parameter_type;
4841 semantic_parameter(parameter_declaration);
4842 parameter_type = parameter_declaration->type;
4845 * we need the default promoted types for the function type
4847 parameter_type = get_default_promoted_type(parameter_type);
4849 function_parameter_t *function_parameter
4850 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4851 memset(function_parameter, 0, sizeof(function_parameter[0]));
4853 function_parameter->type = parameter_type;
4854 if (last_parameter != NULL) {
4855 last_parameter->next = function_parameter;
4857 parameters = function_parameter;
4859 last_parameter = function_parameter;
4862 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4864 new_type->function.parameters = parameters;
4865 new_type->function.unspecified_parameters = true;
4867 type = typehash_insert(new_type);
4868 if (type != new_type) {
4869 obstack_free(type_obst, new_type);
4872 declaration->type = type;
4874 rem_anchor_token('{');
4877 static bool first_err = true;
4880 * When called with first_err set, prints the name of the current function,
4883 static void print_in_function(void)
4887 diagnosticf("%s: In function '%Y':\n",
4888 current_function->source_position.input_name,
4889 current_function->symbol);
4894 * Check if all labels are defined in the current function.
4895 * Check if all labels are used in the current function.
4897 static void check_labels(void)
4899 for (const goto_statement_t *goto_statement = goto_first;
4900 goto_statement != NULL;
4901 goto_statement = goto_statement->next) {
4902 /* skip computed gotos */
4903 if (goto_statement->expression != NULL)
4906 declaration_t *label = goto_statement->label;
4909 if (label->source_position.input_name == NULL) {
4910 print_in_function();
4911 errorf(&goto_statement->base.source_position,
4912 "label '%Y' used but not defined", label->symbol);
4915 goto_first = goto_last = NULL;
4917 if (warning.unused_label) {
4918 for (const label_statement_t *label_statement = label_first;
4919 label_statement != NULL;
4920 label_statement = label_statement->next) {
4921 const declaration_t *label = label_statement->label;
4923 if (! label->used) {
4924 print_in_function();
4925 warningf(&label_statement->base.source_position,
4926 "label '%Y' defined but not used", label->symbol);
4930 label_first = label_last = NULL;
4934 * Check declarations of current_function for unused entities.
4936 static void check_declarations(void)
4938 if (warning.unused_parameter) {
4939 const scope_t *scope = ¤t_function->scope;
4941 if (is_sym_main(current_function->symbol)) {
4942 /* do not issue unused warnings for main */
4945 const declaration_t *parameter = scope->declarations;
4946 for (; parameter != NULL; parameter = parameter->next) {
4947 if (! parameter->used) {
4948 print_in_function();
4949 warningf(¶meter->source_position,
4950 "unused parameter '%Y'", parameter->symbol);
4954 if (warning.unused_variable) {
4958 static int determine_truth(expression_t const* const cond)
4961 !is_constant_expression(cond) ? 0 :
4962 fold_constant(cond) != 0 ? 1 :
4966 static bool noreturn_candidate;
4968 static void check_reachable(statement_t *const stmt)
4970 if (stmt->base.reachable)
4972 if (stmt->kind != STATEMENT_DO_WHILE)
4973 stmt->base.reachable = true;
4975 statement_t *last = stmt;
4977 switch (stmt->kind) {
4978 case STATEMENT_INVALID:
4979 case STATEMENT_EMPTY:
4980 case STATEMENT_DECLARATION:
4982 next = stmt->base.next;
4985 case STATEMENT_COMPOUND:
4986 next = stmt->compound.statements;
4989 case STATEMENT_RETURN:
4990 noreturn_candidate = false;
4993 case STATEMENT_IF: {
4994 if_statement_t const* const ifs = &stmt->ifs;
4995 int const val = determine_truth(ifs->condition);
4998 check_reachable(ifs->true_statement);
5003 if (ifs->false_statement != NULL) {
5004 check_reachable(ifs->false_statement);
5008 next = stmt->base.next;
5012 case STATEMENT_SWITCH: {
5013 switch_statement_t const *const switchs = &stmt->switchs;
5014 expression_t const *const expr = switchs->expression;
5016 if (is_constant_expression(expr)) {
5017 long const val = fold_constant(expr);
5018 case_label_statement_t * defaults = NULL;
5019 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5020 if (i->expression == NULL) {
5025 if (i->first_case <= val && val <= i->last_case) {
5026 check_reachable((statement_t*)i);
5031 if (defaults != NULL) {
5032 check_reachable((statement_t*)defaults);
5036 bool has_default = false;
5037 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5038 if (i->expression == NULL)
5041 check_reachable((statement_t*)i);
5048 next = stmt->base.next;
5052 case STATEMENT_EXPRESSION: {
5053 /* Check for noreturn function call */
5054 expression_t const *const expr = stmt->expression.expression;
5055 if (expr->kind == EXPR_CALL) {
5056 expression_t const *const func = expr->call.function;
5057 if (func->kind == EXPR_REFERENCE) {
5058 declaration_t const *const decl = func->reference.declaration;
5059 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5065 next = stmt->base.next;
5069 case STATEMENT_CONTINUE: {
5070 statement_t *parent = stmt;
5072 parent = parent->base.parent;
5073 if (parent == NULL) /* continue not within loop */
5077 switch (parent->kind) {
5078 case STATEMENT_WHILE: goto continue_while;
5079 case STATEMENT_DO_WHILE: goto continue_do_while;
5080 case STATEMENT_FOR: goto continue_for;
5087 case STATEMENT_BREAK: {
5088 statement_t *parent = stmt;
5090 parent = parent->base.parent;
5091 if (parent == NULL) /* break not within loop/switch */
5094 switch (parent->kind) {
5095 case STATEMENT_SWITCH:
5096 case STATEMENT_WHILE:
5097 case STATEMENT_DO_WHILE:
5100 next = parent->base.next;
5101 goto found_break_parent;
5110 case STATEMENT_GOTO:
5111 if (stmt->gotos.expression) {
5112 statement_t *parent = stmt->base.parent;
5113 if (parent == NULL) /* top level goto */
5117 next = stmt->gotos.label->init.statement;
5118 if (next == NULL) /* missing label */
5123 case STATEMENT_LABEL:
5124 next = stmt->label.statement;
5127 case STATEMENT_CASE_LABEL:
5128 next = stmt->case_label.statement;
5131 case STATEMENT_WHILE: {
5132 while_statement_t const *const whiles = &stmt->whiles;
5133 int const val = determine_truth(whiles->condition);
5136 check_reachable(whiles->body);
5141 next = stmt->base.next;
5145 case STATEMENT_DO_WHILE:
5146 next = stmt->do_while.body;
5149 case STATEMENT_FOR: {
5150 for_statement_t *const fors = &stmt->fors;
5152 if (fors->condition_reachable)
5154 fors->condition_reachable = true;
5156 expression_t const *const cond = fors->condition;
5158 cond == NULL ? 1 : determine_truth(cond);
5161 check_reachable(fors->body);
5166 next = stmt->base.next;
5170 case STATEMENT_MS_TRY: {
5171 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5172 check_reachable(ms_try->try_statement);
5173 next = ms_try->final_statement;
5177 case STATEMENT_LEAVE: {
5178 statement_t *parent = stmt;
5180 parent = parent->base.parent;
5181 if (parent == NULL) /* __leave not within __try */
5184 if (parent->kind == STATEMENT_MS_TRY) {
5186 next = parent->ms_try.final_statement;
5194 while (next == NULL) {
5195 next = last->base.parent;
5197 noreturn_candidate = false;
5199 type_t *const type = current_function->type;
5200 assert(is_type_function(type));
5201 type_t *const ret = skip_typeref(type->function.return_type);
5202 if (warning.return_type &&
5203 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5204 is_type_valid(ret) &&
5205 !is_sym_main(current_function->symbol)) {
5206 warningf(&stmt->base.source_position,
5207 "control reaches end of non-void function");
5212 switch (next->kind) {
5213 case STATEMENT_INVALID:
5214 case STATEMENT_EMPTY:
5215 case STATEMENT_DECLARATION:
5216 case STATEMENT_EXPRESSION:
5218 case STATEMENT_RETURN:
5219 case STATEMENT_CONTINUE:
5220 case STATEMENT_BREAK:
5221 case STATEMENT_GOTO:
5222 case STATEMENT_LEAVE:
5223 panic("invalid control flow in function");
5225 case STATEMENT_COMPOUND:
5227 case STATEMENT_SWITCH:
5228 case STATEMENT_LABEL:
5229 case STATEMENT_CASE_LABEL:
5231 next = next->base.next;
5234 case STATEMENT_WHILE: {
5236 if (next->base.reachable)
5238 next->base.reachable = true;
5240 while_statement_t const *const whiles = &next->whiles;
5241 int const val = determine_truth(whiles->condition);
5244 check_reachable(whiles->body);
5250 next = next->base.next;
5254 case STATEMENT_DO_WHILE: {
5256 if (next->base.reachable)
5258 next->base.reachable = true;
5260 do_while_statement_t const *const dw = &next->do_while;
5261 int const val = determine_truth(dw->condition);
5264 check_reachable(dw->body);
5270 next = next->base.next;
5274 case STATEMENT_FOR: {
5276 for_statement_t *const fors = &next->fors;
5278 fors->step_reachable = true;
5280 if (fors->condition_reachable)
5282 fors->condition_reachable = true;
5284 expression_t const *const cond = fors->condition;
5286 cond == NULL ? 1 : determine_truth(cond);
5289 check_reachable(fors->body);
5295 next = next->base.next;
5299 case STATEMENT_MS_TRY:
5301 next = next->ms_try.final_statement;
5307 next = stmt->base.parent;
5309 warningf(&stmt->base.source_position,
5310 "control reaches end of non-void function");
5314 check_reachable(next);
5317 static void check_unreachable(statement_t const* const stmt)
5319 if (!stmt->base.reachable &&
5320 stmt->kind != STATEMENT_DO_WHILE &&
5321 stmt->kind != STATEMENT_FOR &&
5322 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5323 warningf(&stmt->base.source_position, "statement is unreachable");
5326 switch (stmt->kind) {
5327 case STATEMENT_INVALID:
5328 case STATEMENT_EMPTY:
5329 case STATEMENT_RETURN:
5330 case STATEMENT_DECLARATION:
5331 case STATEMENT_EXPRESSION:
5332 case STATEMENT_CONTINUE:
5333 case STATEMENT_BREAK:
5334 case STATEMENT_GOTO:
5336 case STATEMENT_LEAVE:
5339 case STATEMENT_COMPOUND:
5340 if (stmt->compound.statements)
5341 check_unreachable(stmt->compound.statements);
5345 check_unreachable(stmt->ifs.true_statement);
5346 if (stmt->ifs.false_statement != NULL)
5347 check_unreachable(stmt->ifs.false_statement);
5350 case STATEMENT_SWITCH:
5351 check_unreachable(stmt->switchs.body);
5354 case STATEMENT_LABEL:
5355 check_unreachable(stmt->label.statement);
5358 case STATEMENT_CASE_LABEL:
5359 check_unreachable(stmt->case_label.statement);
5362 case STATEMENT_WHILE:
5363 check_unreachable(stmt->whiles.body);
5366 case STATEMENT_DO_WHILE:
5367 check_unreachable(stmt->do_while.body);
5368 if (!stmt->base.reachable) {
5369 expression_t const *const cond = stmt->do_while.condition;
5370 if (determine_truth(cond) >= 0) {
5371 warningf(&cond->base.source_position,
5372 "condition of do-while-loop is unreachable");
5377 case STATEMENT_FOR: {
5378 for_statement_t const* const fors = &stmt->fors;
5380 // if init and step are unreachable, cond is unreachable, too
5381 if (!stmt->base.reachable && !fors->step_reachable) {
5382 warningf(&stmt->base.source_position, "statement is unreachable");
5384 if (!stmt->base.reachable && fors->initialisation != NULL) {
5385 warningf(&fors->initialisation->base.source_position,
5386 "initialisation of for-statement is unreachable");
5389 if (!fors->condition_reachable && fors->condition != NULL) {
5390 warningf(&fors->condition->base.source_position,
5391 "condition of for-statement is unreachable");
5394 if (!fors->step_reachable && fors->step != NULL) {
5395 warningf(&fors->step->base.source_position,
5396 "step of for-statement is unreachable");
5400 check_unreachable(fors->body);
5404 case STATEMENT_MS_TRY: {
5405 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5406 check_unreachable(ms_try->try_statement);
5407 check_unreachable(ms_try->final_statement);
5411 if (stmt->base.next)
5412 check_unreachable(stmt->base.next);
5415 static void parse_external_declaration(void)
5417 /* function-definitions and declarations both start with declaration
5419 declaration_specifiers_t specifiers;
5420 memset(&specifiers, 0, sizeof(specifiers));
5422 add_anchor_token(';');
5423 parse_declaration_specifiers(&specifiers);
5424 rem_anchor_token(';');
5426 /* must be a declaration */
5427 if (token.type == ';') {
5428 parse_anonymous_declaration_rest(&specifiers);
5432 add_anchor_token(',');
5433 add_anchor_token('=');
5434 add_anchor_token(';');
5435 add_anchor_token('{');
5437 /* declarator is common to both function-definitions and declarations */
5438 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5440 rem_anchor_token('{');
5441 rem_anchor_token(';');
5442 rem_anchor_token('=');
5443 rem_anchor_token(',');
5445 /* must be a declaration */
5446 switch (token.type) {
5450 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5454 /* must be a function definition */
5455 parse_kr_declaration_list(ndeclaration);
5457 if (token.type != '{') {
5458 parse_error_expected("while parsing function definition", '{', NULL);
5459 eat_until_matching_token(';');
5463 type_t *type = ndeclaration->type;
5465 /* note that we don't skip typerefs: the standard doesn't allow them here
5466 * (so we can't use is_type_function here) */
5467 if (type->kind != TYPE_FUNCTION) {
5468 if (is_type_valid(type)) {
5469 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5470 type, ndeclaration->symbol);
5476 if (warning.aggregate_return &&
5477 is_type_compound(skip_typeref(type->function.return_type))) {
5478 warningf(HERE, "function '%Y' returns an aggregate",
5479 ndeclaration->symbol);
5481 if (warning.traditional && !type->function.unspecified_parameters) {
5482 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5483 ndeclaration->symbol);
5485 if (warning.old_style_definition && type->function.unspecified_parameters) {
5486 warningf(HERE, "old-style function definition '%Y'",
5487 ndeclaration->symbol);
5490 /* § 6.7.5.3 (14) a function definition with () means no
5491 * parameters (and not unspecified parameters) */
5492 if (type->function.unspecified_parameters
5493 && type->function.parameters == NULL
5494 && !type->function.kr_style_parameters) {
5495 type_t *duplicate = duplicate_type(type);
5496 duplicate->function.unspecified_parameters = false;
5498 type = typehash_insert(duplicate);
5499 if (type != duplicate) {
5500 obstack_free(type_obst, duplicate);
5502 ndeclaration->type = type;
5505 declaration_t *const declaration = record_declaration(ndeclaration, true);
5506 if (ndeclaration != declaration) {
5507 declaration->scope = ndeclaration->scope;
5509 type = skip_typeref(declaration->type);
5511 /* push function parameters and switch scope */
5512 size_t const top = environment_top();
5513 scope_push(&declaration->scope);
5515 declaration_t *parameter = declaration->scope.declarations;
5516 for( ; parameter != NULL; parameter = parameter->next) {
5517 if (parameter->parent_scope == &ndeclaration->scope) {
5518 parameter->parent_scope = scope;
5520 assert(parameter->parent_scope == NULL
5521 || parameter->parent_scope == scope);
5522 parameter->parent_scope = scope;
5523 if (parameter->symbol == NULL) {
5524 errorf(¶meter->source_position, "parameter name omitted");
5527 environment_push(parameter);
5530 if (declaration->init.statement != NULL) {
5531 parser_error_multiple_definition(declaration, HERE);
5534 /* parse function body */
5535 int label_stack_top = label_top();
5536 declaration_t *old_current_function = current_function;
5537 current_function = declaration;
5538 current_parent = NULL;
5540 statement_t *const body = parse_compound_statement(false);
5541 declaration->init.statement = body;
5544 check_declarations();
5545 if (warning.return_type ||
5546 warning.unreachable_code ||
5547 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5548 noreturn_candidate = true;
5549 check_reachable(body);
5550 if (warning.unreachable_code)
5551 check_unreachable(body);
5552 if (warning.missing_noreturn &&
5553 noreturn_candidate &&
5554 !(declaration->modifiers & DM_NORETURN)) {
5555 warningf(&body->base.source_position,
5556 "function '%#T' is candidate for attribute 'noreturn'",
5557 type, declaration->symbol);
5561 assert(current_parent == NULL);
5562 assert(current_function == declaration);
5563 current_function = old_current_function;
5564 label_pop_to(label_stack_top);
5567 assert(scope == &declaration->scope);
5569 environment_pop_to(top);
5572 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5573 source_position_t *source_position,
5574 const symbol_t *symbol)
5576 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5578 type->bitfield.base_type = base_type;
5579 type->bitfield.size_expression = size;
5582 type_t *skipped_type = skip_typeref(base_type);
5583 if (!is_type_integer(skipped_type)) {
5584 errorf(HERE, "bitfield base type '%T' is not an integer type",
5588 bit_size = skipped_type->base.size * 8;
5591 if (is_constant_expression(size)) {
5592 long v = fold_constant(size);
5595 errorf(source_position, "negative width in bit-field '%Y'",
5597 } else if (v == 0) {
5598 errorf(source_position, "zero width for bit-field '%Y'",
5600 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5601 errorf(source_position, "width of '%Y' exceeds its type",
5604 type->bitfield.bit_size = v;
5611 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5614 declaration_t *iter = compound_declaration->scope.declarations;
5615 for( ; iter != NULL; iter = iter->next) {
5616 if (iter->namespc != NAMESPACE_NORMAL)
5619 if (iter->symbol == NULL) {
5620 type_t *type = skip_typeref(iter->type);
5621 if (is_type_compound(type)) {
5622 declaration_t *result
5623 = find_compound_entry(type->compound.declaration, symbol);
5630 if (iter->symbol == symbol) {
5638 static void parse_compound_declarators(declaration_t *struct_declaration,
5639 const declaration_specifiers_t *specifiers)
5641 declaration_t *last_declaration = struct_declaration->scope.declarations;
5642 if (last_declaration != NULL) {
5643 while (last_declaration->next != NULL) {
5644 last_declaration = last_declaration->next;
5649 declaration_t *declaration;
5651 if (token.type == ':') {
5652 source_position_t source_position = *HERE;
5655 type_t *base_type = specifiers->type;
5656 expression_t *size = parse_constant_expression();
5658 type_t *type = make_bitfield_type(base_type, size,
5659 &source_position, sym_anonymous);
5661 declaration = allocate_declaration_zero();
5662 declaration->namespc = NAMESPACE_NORMAL;
5663 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5664 declaration->storage_class = STORAGE_CLASS_NONE;
5665 declaration->source_position = source_position;
5666 declaration->modifiers = specifiers->modifiers;
5667 declaration->type = type;
5669 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5671 type_t *orig_type = declaration->type;
5672 type_t *type = skip_typeref(orig_type);
5674 if (token.type == ':') {
5675 source_position_t source_position = *HERE;
5677 expression_t *size = parse_constant_expression();
5679 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5680 &source_position, declaration->symbol);
5681 declaration->type = bitfield_type;
5683 /* TODO we ignore arrays for now... what is missing is a check
5684 * that they're at the end of the struct */
5685 if (is_type_incomplete(type) && !is_type_array(type)) {
5687 "compound member '%Y' has incomplete type '%T'",
5688 declaration->symbol, orig_type);
5689 } else if (is_type_function(type)) {
5690 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5691 declaration->symbol, orig_type);
5696 /* make sure we don't define a symbol multiple times */
5697 symbol_t *symbol = declaration->symbol;
5698 if (symbol != NULL) {
5699 declaration_t *prev_decl
5700 = find_compound_entry(struct_declaration, symbol);
5702 if (prev_decl != NULL) {
5703 assert(prev_decl->symbol == symbol);
5704 errorf(&declaration->source_position,
5705 "multiple declarations of symbol '%Y' (declared %P)",
5706 symbol, &prev_decl->source_position);
5710 /* append declaration */
5711 if (last_declaration != NULL) {
5712 last_declaration->next = declaration;
5714 struct_declaration->scope.declarations = declaration;
5716 last_declaration = declaration;
5718 if (token.type != ',')
5728 static void parse_compound_type_entries(declaration_t *compound_declaration)
5731 add_anchor_token('}');
5733 while (token.type != '}' && token.type != T_EOF) {
5734 declaration_specifiers_t specifiers;
5735 memset(&specifiers, 0, sizeof(specifiers));
5736 parse_declaration_specifiers(&specifiers);
5738 parse_compound_declarators(compound_declaration, &specifiers);
5740 rem_anchor_token('}');
5742 if (token.type == T_EOF) {
5743 errorf(HERE, "EOF while parsing struct");
5748 static type_t *parse_typename(void)
5750 declaration_specifiers_t specifiers;
5751 memset(&specifiers, 0, sizeof(specifiers));
5752 parse_declaration_specifiers(&specifiers);
5753 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5754 /* TODO: improve error message, user does probably not know what a
5755 * storage class is...
5757 errorf(HERE, "typename may not have a storage class");
5760 type_t *result = parse_abstract_declarator(specifiers.type);
5768 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5769 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5770 expression_t *left);
5772 typedef struct expression_parser_function_t expression_parser_function_t;
5773 struct expression_parser_function_t {
5774 unsigned precedence;
5775 parse_expression_function parser;
5776 unsigned infix_precedence;
5777 parse_expression_infix_function infix_parser;
5780 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5783 * Prints an error message if an expression was expected but not read
5785 static expression_t *expected_expression_error(void)
5787 /* skip the error message if the error token was read */
5788 if (token.type != T_ERROR) {
5789 errorf(HERE, "expected expression, got token '%K'", &token);
5793 return create_invalid_expression();
5797 * Parse a string constant.
5799 static expression_t *parse_string_const(void)
5802 if (token.type == T_STRING_LITERAL) {
5803 string_t res = token.v.string;
5805 while (token.type == T_STRING_LITERAL) {
5806 res = concat_strings(&res, &token.v.string);
5809 if (token.type != T_WIDE_STRING_LITERAL) {
5810 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5811 /* note: that we use type_char_ptr here, which is already the
5812 * automatic converted type. revert_automatic_type_conversion
5813 * will construct the array type */
5814 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5815 cnst->string.value = res;
5819 wres = concat_string_wide_string(&res, &token.v.wide_string);
5821 wres = token.v.wide_string;
5826 switch (token.type) {
5827 case T_WIDE_STRING_LITERAL:
5828 wres = concat_wide_strings(&wres, &token.v.wide_string);
5831 case T_STRING_LITERAL:
5832 wres = concat_wide_string_string(&wres, &token.v.string);
5836 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5837 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5838 cnst->wide_string.value = wres;
5847 * Parse an integer constant.
5849 static expression_t *parse_int_const(void)
5851 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5852 cnst->base.source_position = *HERE;
5853 cnst->base.type = token.datatype;
5854 cnst->conste.v.int_value = token.v.intvalue;
5862 * Parse a character constant.
5864 static expression_t *parse_character_constant(void)
5866 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5868 cnst->base.source_position = *HERE;
5869 cnst->base.type = token.datatype;
5870 cnst->conste.v.character = token.v.string;
5872 if (cnst->conste.v.character.size != 1) {
5873 if (warning.multichar && GNU_MODE) {
5874 warningf(HERE, "multi-character character constant");
5876 errorf(HERE, "more than 1 characters in character constant");
5885 * Parse a wide character constant.
5887 static expression_t *parse_wide_character_constant(void)
5889 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5891 cnst->base.source_position = *HERE;
5892 cnst->base.type = token.datatype;
5893 cnst->conste.v.wide_character = token.v.wide_string;
5895 if (cnst->conste.v.wide_character.size != 1) {
5896 if (warning.multichar && GNU_MODE) {
5897 warningf(HERE, "multi-character character constant");
5899 errorf(HERE, "more than 1 characters in character constant");
5908 * Parse a float constant.
5910 static expression_t *parse_float_const(void)
5912 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5913 cnst->base.type = token.datatype;
5914 cnst->conste.v.float_value = token.v.floatvalue;
5921 static declaration_t *create_implicit_function(symbol_t *symbol,
5922 const source_position_t *source_position)
5924 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5925 ntype->function.return_type = type_int;
5926 ntype->function.unspecified_parameters = true;
5928 type_t *type = typehash_insert(ntype);
5929 if (type != ntype) {
5933 declaration_t *const declaration = allocate_declaration_zero();
5934 declaration->storage_class = STORAGE_CLASS_EXTERN;
5935 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5936 declaration->type = type;
5937 declaration->symbol = symbol;
5938 declaration->source_position = *source_position;
5939 declaration->implicit = true;
5941 bool strict_prototypes_old = warning.strict_prototypes;
5942 warning.strict_prototypes = false;
5943 record_declaration(declaration, false);
5944 warning.strict_prototypes = strict_prototypes_old;
5950 * Creates a return_type (func)(argument_type) function type if not
5953 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5954 type_t *argument_type2)
5956 function_parameter_t *parameter2
5957 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5958 memset(parameter2, 0, sizeof(parameter2[0]));
5959 parameter2->type = argument_type2;
5961 function_parameter_t *parameter1
5962 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5963 memset(parameter1, 0, sizeof(parameter1[0]));
5964 parameter1->type = argument_type1;
5965 parameter1->next = parameter2;
5967 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5968 type->function.return_type = return_type;
5969 type->function.parameters = parameter1;
5971 type_t *result = typehash_insert(type);
5972 if (result != type) {
5980 * Creates a return_type (func)(argument_type) function type if not
5983 * @param return_type the return type
5984 * @param argument_type the argument type
5986 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5988 function_parameter_t *parameter
5989 = obstack_alloc(type_obst, sizeof(parameter[0]));
5990 memset(parameter, 0, sizeof(parameter[0]));
5991 parameter->type = argument_type;
5993 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5994 type->function.return_type = return_type;
5995 type->function.parameters = parameter;
5997 type_t *result = typehash_insert(type);
5998 if (result != type) {
6005 static type_t *make_function_0_type(type_t *return_type)
6007 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
6008 type->function.return_type = return_type;
6009 type->function.parameters = NULL;
6011 type_t *result = typehash_insert(type);
6012 if (result != type) {
6020 * Creates a function type for some function like builtins.
6022 * @param symbol the symbol describing the builtin
6024 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6026 switch(symbol->ID) {
6027 case T___builtin_alloca:
6028 return make_function_1_type(type_void_ptr, type_size_t);
6029 case T___builtin_huge_val:
6030 return make_function_0_type(type_double);
6031 case T___builtin_nan:
6032 return make_function_1_type(type_double, type_char_ptr);
6033 case T___builtin_nanf:
6034 return make_function_1_type(type_float, type_char_ptr);
6035 case T___builtin_nand:
6036 return make_function_1_type(type_long_double, type_char_ptr);
6037 case T___builtin_va_end:
6038 return make_function_1_type(type_void, type_valist);
6039 case T___builtin_expect:
6040 return make_function_2_type(type_long, type_long, type_long);
6042 internal_errorf(HERE, "not implemented builtin symbol found");
6047 * Performs automatic type cast as described in § 6.3.2.1.
6049 * @param orig_type the original type
6051 static type_t *automatic_type_conversion(type_t *orig_type)
6053 type_t *type = skip_typeref(orig_type);
6054 if (is_type_array(type)) {
6055 array_type_t *array_type = &type->array;
6056 type_t *element_type = array_type->element_type;
6057 unsigned qualifiers = array_type->base.qualifiers;
6059 return make_pointer_type(element_type, qualifiers);
6062 if (is_type_function(type)) {
6063 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6070 * reverts the automatic casts of array to pointer types and function
6071 * to function-pointer types as defined § 6.3.2.1
6073 type_t *revert_automatic_type_conversion(const expression_t *expression)
6075 switch (expression->kind) {
6076 case EXPR_REFERENCE: return expression->reference.declaration->type;
6079 return get_qualified_type(expression->select.compound_entry->type,
6080 expression->base.type->base.qualifiers);
6082 case EXPR_UNARY_DEREFERENCE: {
6083 const expression_t *const value = expression->unary.value;
6084 type_t *const type = skip_typeref(value->base.type);
6085 assert(is_type_pointer(type));
6086 return type->pointer.points_to;
6089 case EXPR_BUILTIN_SYMBOL:
6090 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6092 case EXPR_ARRAY_ACCESS: {
6093 const expression_t *array_ref = expression->array_access.array_ref;
6094 type_t *type_left = skip_typeref(array_ref->base.type);
6095 if (!is_type_valid(type_left))
6097 assert(is_type_pointer(type_left));
6098 return type_left->pointer.points_to;
6101 case EXPR_STRING_LITERAL: {
6102 size_t size = expression->string.value.size;
6103 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6106 case EXPR_WIDE_STRING_LITERAL: {
6107 size_t size = expression->wide_string.value.size;
6108 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6111 case EXPR_COMPOUND_LITERAL:
6112 return expression->compound_literal.type;
6117 return expression->base.type;
6120 static expression_t *parse_reference(void)
6122 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6124 reference_expression_t *ref = &expression->reference;
6125 symbol_t *const symbol = token.v.symbol;
6127 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6129 if (declaration == NULL) {
6130 if (!strict_mode && look_ahead(1)->type == '(') {
6131 /* an implicitly declared function */
6132 if (warning.implicit_function_declaration) {
6133 warningf(HERE, "implicit declaration of function '%Y'",
6137 declaration = create_implicit_function(symbol, HERE);
6139 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6140 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6144 type_t *orig_type = declaration->type;
6146 /* we always do the auto-type conversions; the & and sizeof parser contains
6147 * code to revert this! */
6148 type_t *type = automatic_type_conversion(orig_type);
6150 ref->declaration = declaration;
6151 ref->base.type = type;
6153 /* this declaration is used */
6154 declaration->used = true;
6156 if (declaration->parent_scope != global_scope &&
6157 declaration->parent_scope->depth < current_function->scope.depth &&
6158 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6159 /* access of a variable from an outer function */
6160 declaration->address_taken = true;
6161 ref->is_outer_ref = true;
6162 current_function->need_closure = true;
6165 /* check for deprecated functions */
6166 if (warning.deprecated_declarations &&
6167 declaration->modifiers & DM_DEPRECATED) {
6168 char const *const prefix = is_type_function(declaration->type) ?
6169 "function" : "variable";
6171 if (declaration->deprecated_string != NULL) {
6172 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6173 prefix, declaration->symbol, &declaration->source_position,
6174 declaration->deprecated_string);
6176 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6177 declaration->symbol, &declaration->source_position);
6180 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6181 current_init_decl = NULL;
6182 warningf(HERE, "variable '%#T' is initialized by itself",
6183 declaration->type, declaration->symbol);
6190 static bool semantic_cast(expression_t *cast)
6192 expression_t *expression = cast->unary.value;
6193 type_t *orig_dest_type = cast->base.type;
6194 type_t *orig_type_right = expression->base.type;
6195 type_t const *dst_type = skip_typeref(orig_dest_type);
6196 type_t const *src_type = skip_typeref(orig_type_right);
6197 source_position_t const *pos = &cast->base.source_position;
6199 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6200 if (dst_type == type_void)
6203 /* only integer and pointer can be casted to pointer */
6204 if (is_type_pointer(dst_type) &&
6205 !is_type_pointer(src_type) &&
6206 !is_type_integer(src_type) &&
6207 is_type_valid(src_type)) {
6208 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6212 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6213 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6217 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6218 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6222 if (warning.cast_qual &&
6223 is_type_pointer(src_type) &&
6224 is_type_pointer(dst_type)) {
6225 type_t *src = skip_typeref(src_type->pointer.points_to);
6226 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6227 unsigned missing_qualifiers =
6228 src->base.qualifiers & ~dst->base.qualifiers;
6229 if (missing_qualifiers != 0) {
6231 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6232 missing_qualifiers, orig_type_right);
6238 static expression_t *parse_compound_literal(type_t *type)
6240 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6242 parse_initializer_env_t env;
6244 env.declaration = NULL;
6245 env.must_be_constant = false;
6246 initializer_t *initializer = parse_initializer(&env);
6249 expression->compound_literal.initializer = initializer;
6250 expression->compound_literal.type = type;
6251 expression->base.type = automatic_type_conversion(type);
6257 * Parse a cast expression.
6259 static expression_t *parse_cast(void)
6261 add_anchor_token(')');
6263 source_position_t source_position = token.source_position;
6265 type_t *type = parse_typename();
6267 rem_anchor_token(')');
6270 if (token.type == '{') {
6271 return parse_compound_literal(type);
6274 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6275 cast->base.source_position = source_position;
6277 expression_t *value = parse_sub_expression(20);
6278 cast->base.type = type;
6279 cast->unary.value = value;
6281 if (! semantic_cast(cast)) {
6282 /* TODO: record the error in the AST. else it is impossible to detect it */
6287 return create_invalid_expression();
6291 * Parse a statement expression.
6293 static expression_t *parse_statement_expression(void)
6295 add_anchor_token(')');
6297 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6299 statement_t *statement = parse_compound_statement(true);
6300 expression->statement.statement = statement;
6301 expression->base.source_position = statement->base.source_position;
6303 /* find last statement and use its type */
6304 type_t *type = type_void;
6305 const statement_t *stmt = statement->compound.statements;
6307 while (stmt->base.next != NULL)
6308 stmt = stmt->base.next;
6310 if (stmt->kind == STATEMENT_EXPRESSION) {
6311 type = stmt->expression.expression->base.type;
6314 warningf(&expression->base.source_position, "empty statement expression ({})");
6316 expression->base.type = type;
6318 rem_anchor_token(')');
6326 * Parse a parenthesized expression.
6328 static expression_t *parse_parenthesized_expression(void)
6332 switch(token.type) {
6334 /* gcc extension: a statement expression */
6335 return parse_statement_expression();
6339 return parse_cast();
6341 if (is_typedef_symbol(token.v.symbol)) {
6342 return parse_cast();
6346 add_anchor_token(')');
6347 expression_t *result = parse_expression();
6348 rem_anchor_token(')');
6355 static expression_t *parse_function_keyword(void)
6360 if (current_function == NULL) {
6361 errorf(HERE, "'__func__' used outside of a function");
6364 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6365 expression->base.type = type_char_ptr;
6366 expression->funcname.kind = FUNCNAME_FUNCTION;
6371 static expression_t *parse_pretty_function_keyword(void)
6373 eat(T___PRETTY_FUNCTION__);
6375 if (current_function == NULL) {
6376 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6379 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6380 expression->base.type = type_char_ptr;
6381 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6386 static expression_t *parse_funcsig_keyword(void)
6390 if (current_function == NULL) {
6391 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6394 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6395 expression->base.type = type_char_ptr;
6396 expression->funcname.kind = FUNCNAME_FUNCSIG;
6401 static expression_t *parse_funcdname_keyword(void)
6403 eat(T___FUNCDNAME__);
6405 if (current_function == NULL) {
6406 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6409 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6410 expression->base.type = type_char_ptr;
6411 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6416 static designator_t *parse_designator(void)
6418 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6419 result->source_position = *HERE;
6421 if (token.type != T_IDENTIFIER) {
6422 parse_error_expected("while parsing member designator",
6423 T_IDENTIFIER, NULL);
6426 result->symbol = token.v.symbol;
6429 designator_t *last_designator = result;
6431 if (token.type == '.') {
6433 if (token.type != T_IDENTIFIER) {
6434 parse_error_expected("while parsing member designator",
6435 T_IDENTIFIER, NULL);
6438 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6439 designator->source_position = *HERE;
6440 designator->symbol = token.v.symbol;
6443 last_designator->next = designator;
6444 last_designator = designator;
6447 if (token.type == '[') {
6449 add_anchor_token(']');
6450 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6451 designator->source_position = *HERE;
6452 designator->array_index = parse_expression();
6453 rem_anchor_token(']');
6455 if (designator->array_index == NULL) {
6459 last_designator->next = designator;
6460 last_designator = designator;
6472 * Parse the __builtin_offsetof() expression.
6474 static expression_t *parse_offsetof(void)
6476 eat(T___builtin_offsetof);
6478 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6479 expression->base.type = type_size_t;
6482 add_anchor_token(',');
6483 type_t *type = parse_typename();
6484 rem_anchor_token(',');
6486 add_anchor_token(')');
6487 designator_t *designator = parse_designator();
6488 rem_anchor_token(')');
6491 expression->offsetofe.type = type;
6492 expression->offsetofe.designator = designator;
6495 memset(&path, 0, sizeof(path));
6496 path.top_type = type;
6497 path.path = NEW_ARR_F(type_path_entry_t, 0);
6499 descend_into_subtype(&path);
6501 if (!walk_designator(&path, designator, true)) {
6502 return create_invalid_expression();
6505 DEL_ARR_F(path.path);
6509 return create_invalid_expression();
6513 * Parses a _builtin_va_start() expression.
6515 static expression_t *parse_va_start(void)
6517 eat(T___builtin_va_start);
6519 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6522 add_anchor_token(',');
6523 expression->va_starte.ap = parse_assignment_expression();
6524 rem_anchor_token(',');
6526 expression_t *const expr = parse_assignment_expression();
6527 if (expr->kind == EXPR_REFERENCE) {
6528 declaration_t *const decl = expr->reference.declaration;
6529 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6530 errorf(&expr->base.source_position,
6531 "second argument of 'va_start' must be last parameter of the current function");
6533 expression->va_starte.parameter = decl;
6539 return create_invalid_expression();
6543 * Parses a _builtin_va_arg() expression.
6545 static expression_t *parse_va_arg(void)
6547 eat(T___builtin_va_arg);
6549 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6552 expression->va_arge.ap = parse_assignment_expression();
6554 expression->base.type = parse_typename();
6559 return create_invalid_expression();
6562 static expression_t *parse_builtin_symbol(void)
6564 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6566 symbol_t *symbol = token.v.symbol;
6568 expression->builtin_symbol.symbol = symbol;
6571 type_t *type = get_builtin_symbol_type(symbol);
6572 type = automatic_type_conversion(type);
6574 expression->base.type = type;
6579 * Parses a __builtin_constant() expression.
6581 static expression_t *parse_builtin_constant(void)
6583 eat(T___builtin_constant_p);
6585 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6588 add_anchor_token(')');
6589 expression->builtin_constant.value = parse_assignment_expression();
6590 rem_anchor_token(')');
6592 expression->base.type = type_int;
6596 return create_invalid_expression();
6600 * Parses a __builtin_prefetch() expression.
6602 static expression_t *parse_builtin_prefetch(void)
6604 eat(T___builtin_prefetch);
6606 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6609 add_anchor_token(')');
6610 expression->builtin_prefetch.adr = parse_assignment_expression();
6611 if (token.type == ',') {
6613 expression->builtin_prefetch.rw = parse_assignment_expression();
6615 if (token.type == ',') {
6617 expression->builtin_prefetch.locality = parse_assignment_expression();
6619 rem_anchor_token(')');
6621 expression->base.type = type_void;
6625 return create_invalid_expression();
6629 * Parses a __builtin_is_*() compare expression.
6631 static expression_t *parse_compare_builtin(void)
6633 expression_t *expression;
6635 switch(token.type) {
6636 case T___builtin_isgreater:
6637 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6639 case T___builtin_isgreaterequal:
6640 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6642 case T___builtin_isless:
6643 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6645 case T___builtin_islessequal:
6646 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6648 case T___builtin_islessgreater:
6649 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6651 case T___builtin_isunordered:
6652 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6655 internal_errorf(HERE, "invalid compare builtin found");
6658 expression->base.source_position = *HERE;
6662 expression->binary.left = parse_assignment_expression();
6664 expression->binary.right = parse_assignment_expression();
6667 type_t *const orig_type_left = expression->binary.left->base.type;
6668 type_t *const orig_type_right = expression->binary.right->base.type;
6670 type_t *const type_left = skip_typeref(orig_type_left);
6671 type_t *const type_right = skip_typeref(orig_type_right);
6672 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6673 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6674 type_error_incompatible("invalid operands in comparison",
6675 &expression->base.source_position, orig_type_left, orig_type_right);
6678 semantic_comparison(&expression->binary);
6683 return create_invalid_expression();
6688 * Parses a __builtin_expect() expression.
6690 static expression_t *parse_builtin_expect(void)
6692 eat(T___builtin_expect);
6694 expression_t *expression
6695 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6698 expression->binary.left = parse_assignment_expression();
6700 expression->binary.right = parse_constant_expression();
6703 expression->base.type = expression->binary.left->base.type;
6707 return create_invalid_expression();
6712 * Parses a MS assume() expression.
6714 static expression_t *parse_assume(void)
6718 expression_t *expression
6719 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6722 add_anchor_token(')');
6723 expression->unary.value = parse_assignment_expression();
6724 rem_anchor_token(')');
6727 expression->base.type = type_void;
6730 return create_invalid_expression();
6734 * Return the declaration for a given label symbol or create a new one.
6736 * @param symbol the symbol of the label
6738 static declaration_t *get_label(symbol_t *symbol)
6740 declaration_t *candidate;
6741 assert(current_function != NULL);
6743 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6744 /* if we found a local label, we already created the declaration */
6745 if (candidate != NULL) {
6746 if (candidate->parent_scope != scope) {
6747 assert(candidate->parent_scope->depth < scope->depth);
6748 current_function->goto_to_outer = true;
6753 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6754 /* if we found a label in the same function, then we already created the
6756 if (candidate != NULL
6757 && candidate->parent_scope == ¤t_function->scope) {
6761 /* otherwise we need to create a new one */
6762 declaration_t *const declaration = allocate_declaration_zero();
6763 declaration->namespc = NAMESPACE_LABEL;
6764 declaration->symbol = symbol;
6766 label_push(declaration);
6772 * Parses a GNU && label address expression.
6774 static expression_t *parse_label_address(void)
6776 source_position_t source_position = token.source_position;
6778 if (token.type != T_IDENTIFIER) {
6779 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6782 symbol_t *symbol = token.v.symbol;
6785 declaration_t *label = get_label(symbol);
6788 label->address_taken = true;
6790 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6791 expression->base.source_position = source_position;
6793 /* label address is threaten as a void pointer */
6794 expression->base.type = type_void_ptr;
6795 expression->label_address.declaration = label;
6798 return create_invalid_expression();
6802 * Parse a microsoft __noop expression.
6804 static expression_t *parse_noop_expression(void)
6806 source_position_t source_position = *HERE;
6809 if (token.type == '(') {
6810 /* parse arguments */
6812 add_anchor_token(')');
6813 add_anchor_token(',');
6815 if (token.type != ')') {
6817 (void)parse_assignment_expression();
6818 if (token.type != ',')
6824 rem_anchor_token(',');
6825 rem_anchor_token(')');
6828 /* the result is a (int)0 */
6829 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6830 cnst->base.source_position = source_position;
6831 cnst->base.type = type_int;
6832 cnst->conste.v.int_value = 0;
6833 cnst->conste.is_ms_noop = true;
6838 return create_invalid_expression();
6842 * Parses a primary expression.
6844 static expression_t *parse_primary_expression(void)
6846 switch (token.type) {
6847 case T_INTEGER: return parse_int_const();
6848 case T_CHARACTER_CONSTANT: return parse_character_constant();
6849 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6850 case T_FLOATINGPOINT: return parse_float_const();
6851 case T_STRING_LITERAL:
6852 case T_WIDE_STRING_LITERAL: return parse_string_const();
6853 case T_IDENTIFIER: return parse_reference();
6854 case T___FUNCTION__:
6855 case T___func__: return parse_function_keyword();
6856 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6857 case T___FUNCSIG__: return parse_funcsig_keyword();
6858 case T___FUNCDNAME__: return parse_funcdname_keyword();
6859 case T___builtin_offsetof: return parse_offsetof();
6860 case T___builtin_va_start: return parse_va_start();
6861 case T___builtin_va_arg: return parse_va_arg();
6862 case T___builtin_expect:
6863 case T___builtin_alloca:
6864 case T___builtin_nan:
6865 case T___builtin_nand:
6866 case T___builtin_nanf:
6867 case T___builtin_huge_val:
6868 case T___builtin_va_end: return parse_builtin_symbol();
6869 case T___builtin_isgreater:
6870 case T___builtin_isgreaterequal:
6871 case T___builtin_isless:
6872 case T___builtin_islessequal:
6873 case T___builtin_islessgreater:
6874 case T___builtin_isunordered: return parse_compare_builtin();
6875 case T___builtin_constant_p: return parse_builtin_constant();
6876 case T___builtin_prefetch: return parse_builtin_prefetch();
6877 case T__assume: return parse_assume();
6880 return parse_label_address();
6883 case '(': return parse_parenthesized_expression();
6884 case T___noop: return parse_noop_expression();
6887 errorf(HERE, "unexpected token %K, expected an expression", &token);
6888 return create_invalid_expression();
6892 * Check if the expression has the character type and issue a warning then.
6894 static void check_for_char_index_type(const expression_t *expression)
6896 type_t *const type = expression->base.type;
6897 const type_t *const base_type = skip_typeref(type);
6899 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6900 warning.char_subscripts) {
6901 warningf(&expression->base.source_position,
6902 "array subscript has type '%T'", type);
6906 static expression_t *parse_array_expression(unsigned precedence,
6912 add_anchor_token(']');
6914 expression_t *inside = parse_expression();
6916 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6918 array_access_expression_t *array_access = &expression->array_access;
6920 type_t *const orig_type_left = left->base.type;
6921 type_t *const orig_type_inside = inside->base.type;
6923 type_t *const type_left = skip_typeref(orig_type_left);
6924 type_t *const type_inside = skip_typeref(orig_type_inside);
6926 type_t *return_type;
6927 if (is_type_pointer(type_left)) {
6928 return_type = type_left->pointer.points_to;
6929 array_access->array_ref = left;
6930 array_access->index = inside;
6931 check_for_char_index_type(inside);
6932 } else if (is_type_pointer(type_inside)) {
6933 return_type = type_inside->pointer.points_to;
6934 array_access->array_ref = inside;
6935 array_access->index = left;
6936 array_access->flipped = true;
6937 check_for_char_index_type(left);
6939 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6941 "array access on object with non-pointer types '%T', '%T'",
6942 orig_type_left, orig_type_inside);
6944 return_type = type_error_type;
6945 array_access->array_ref = left;
6946 array_access->index = inside;
6949 expression->base.type = automatic_type_conversion(return_type);
6951 rem_anchor_token(']');
6952 if (token.type == ']') {
6955 parse_error_expected("Problem while parsing array access", ']', NULL);
6960 static expression_t *parse_typeprop(expression_kind_t const kind,
6961 source_position_t const pos,
6962 unsigned const precedence)
6964 expression_t *tp_expression = allocate_expression_zero(kind);
6965 tp_expression->base.type = type_size_t;
6966 tp_expression->base.source_position = pos;
6968 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6970 /* we only refer to a type property, mark this case */
6971 bool old = in_type_prop;
6972 in_type_prop = true;
6973 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6975 add_anchor_token(')');
6976 type_t* const orig_type = parse_typename();
6977 tp_expression->typeprop.type = orig_type;
6979 type_t const* const type = skip_typeref(orig_type);
6980 char const* const wrong_type =
6981 is_type_incomplete(type) ? "incomplete" :
6982 type->kind == TYPE_FUNCTION ? "function designator" :
6983 type->kind == TYPE_BITFIELD ? "bitfield" :
6985 if (wrong_type != NULL) {
6986 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6987 what, wrong_type, type);
6990 rem_anchor_token(')');
6993 expression_t *expression = parse_sub_expression(precedence);
6995 type_t* const orig_type = revert_automatic_type_conversion(expression);
6996 expression->base.type = orig_type;
6998 type_t const* const type = skip_typeref(orig_type);
6999 char const* const wrong_type =
7000 is_type_incomplete(type) ? "incomplete" :
7001 type->kind == TYPE_FUNCTION ? "function designator" :
7002 type->kind == TYPE_BITFIELD ? "bitfield" :
7004 if (wrong_type != NULL) {
7005 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
7008 tp_expression->typeprop.type = expression->base.type;
7009 tp_expression->typeprop.tp_expression = expression;
7014 return tp_expression;
7017 static expression_t *parse_sizeof(unsigned precedence)
7019 source_position_t pos = *HERE;
7021 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
7024 static expression_t *parse_alignof(unsigned precedence)
7026 source_position_t pos = *HERE;
7028 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
7031 static expression_t *parse_select_expression(unsigned precedence,
7032 expression_t *compound)
7035 assert(token.type == '.' || token.type == T_MINUSGREATER);
7037 bool is_pointer = (token.type == T_MINUSGREATER);
7040 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7041 select->select.compound = compound;
7043 if (token.type != T_IDENTIFIER) {
7044 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7047 symbol_t *symbol = token.v.symbol;
7050 type_t *const orig_type = compound->base.type;
7051 type_t *const type = skip_typeref(orig_type);
7054 bool saw_error = false;
7055 if (is_type_pointer(type)) {
7058 "request for member '%Y' in something not a struct or union, but '%T'",
7062 type_left = skip_typeref(type->pointer.points_to);
7064 if (is_pointer && is_type_valid(type)) {
7065 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7071 declaration_t *entry;
7072 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7073 type_left->kind == TYPE_COMPOUND_UNION) {
7074 declaration_t *const declaration = type_left->compound.declaration;
7076 if (!declaration->init.complete) {
7077 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7079 goto create_error_entry;
7082 entry = find_compound_entry(declaration, symbol);
7083 if (entry == NULL) {
7084 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7085 goto create_error_entry;
7088 if (is_type_valid(type_left) && !saw_error) {
7090 "request for member '%Y' in something not a struct or union, but '%T'",
7094 entry = allocate_declaration_zero();
7095 entry->symbol = symbol;
7098 select->select.compound_entry = entry;
7100 type_t *const res_type =
7101 get_qualified_type(entry->type, type_left->base.qualifiers);
7103 /* we always do the auto-type conversions; the & and sizeof parser contains
7104 * code to revert this! */
7105 select->base.type = automatic_type_conversion(res_type);
7107 type_t *skipped = skip_typeref(res_type);
7108 if (skipped->kind == TYPE_BITFIELD) {
7109 select->base.type = skipped->bitfield.base_type;
7115 static void check_call_argument(const function_parameter_t *parameter,
7116 call_argument_t *argument, unsigned pos)
7118 type_t *expected_type = parameter->type;
7119 type_t *expected_type_skip = skip_typeref(expected_type);
7120 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7121 expression_t *arg_expr = argument->expression;
7122 type_t *arg_type = skip_typeref(arg_expr->base.type);
7124 /* handle transparent union gnu extension */
7125 if (is_type_union(expected_type_skip)
7126 && (expected_type_skip->base.modifiers
7127 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7128 declaration_t *union_decl = expected_type_skip->compound.declaration;
7130 declaration_t *declaration = union_decl->scope.declarations;
7131 type_t *best_type = NULL;
7132 for ( ; declaration != NULL; declaration = declaration->next) {
7133 type_t *decl_type = declaration->type;
7134 error = semantic_assign(decl_type, arg_expr);
7135 if (error == ASSIGN_ERROR_INCOMPATIBLE
7136 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7139 if (error == ASSIGN_SUCCESS) {
7140 best_type = decl_type;
7141 } else if (best_type == NULL) {
7142 best_type = decl_type;
7146 if (best_type != NULL) {
7147 expected_type = best_type;
7151 error = semantic_assign(expected_type, arg_expr);
7152 argument->expression = create_implicit_cast(argument->expression,
7155 if (error != ASSIGN_SUCCESS) {
7156 /* report exact scope in error messages (like "in argument 3") */
7158 snprintf(buf, sizeof(buf), "call argument %u", pos);
7159 report_assign_error(error, expected_type, arg_expr, buf,
7160 &arg_expr->base.source_position);
7161 } else if (warning.traditional || warning.conversion) {
7162 type_t *const promoted_type = get_default_promoted_type(arg_type);
7163 if (!types_compatible(expected_type_skip, promoted_type) &&
7164 !types_compatible(expected_type_skip, type_void_ptr) &&
7165 !types_compatible(type_void_ptr, promoted_type)) {
7166 /* Deliberately show the skipped types in this warning */
7167 warningf(&arg_expr->base.source_position,
7168 "passing call argument %u as '%T' rather than '%T' due to prototype",
7169 pos, expected_type_skip, promoted_type);
7175 * Parse a call expression, ie. expression '( ... )'.
7177 * @param expression the function address
7179 static expression_t *parse_call_expression(unsigned precedence,
7180 expression_t *expression)
7183 expression_t *result = allocate_expression_zero(EXPR_CALL);
7184 result->base.source_position = expression->base.source_position;
7186 call_expression_t *call = &result->call;
7187 call->function = expression;
7189 type_t *const orig_type = expression->base.type;
7190 type_t *const type = skip_typeref(orig_type);
7192 function_type_t *function_type = NULL;
7193 if (is_type_pointer(type)) {
7194 type_t *const to_type = skip_typeref(type->pointer.points_to);
7196 if (is_type_function(to_type)) {
7197 function_type = &to_type->function;
7198 call->base.type = function_type->return_type;
7202 if (function_type == NULL && is_type_valid(type)) {
7203 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7206 /* parse arguments */
7208 add_anchor_token(')');
7209 add_anchor_token(',');
7211 if (token.type != ')') {
7212 call_argument_t *last_argument = NULL;
7215 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7217 argument->expression = parse_assignment_expression();
7218 if (last_argument == NULL) {
7219 call->arguments = argument;
7221 last_argument->next = argument;
7223 last_argument = argument;
7225 if (token.type != ',')
7230 rem_anchor_token(',');
7231 rem_anchor_token(')');
7234 if (function_type == NULL)
7237 function_parameter_t *parameter = function_type->parameters;
7238 call_argument_t *argument = call->arguments;
7239 if (!function_type->unspecified_parameters) {
7240 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7241 parameter = parameter->next, argument = argument->next) {
7242 check_call_argument(parameter, argument, ++pos);
7245 if (parameter != NULL) {
7246 errorf(HERE, "too few arguments to function '%E'", expression);
7247 } else if (argument != NULL && !function_type->variadic) {
7248 errorf(HERE, "too many arguments to function '%E'", expression);
7252 /* do default promotion */
7253 for( ; argument != NULL; argument = argument->next) {
7254 type_t *type = argument->expression->base.type;
7256 type = get_default_promoted_type(type);
7258 argument->expression
7259 = create_implicit_cast(argument->expression, type);
7262 check_format(&result->call);
7264 if (warning.aggregate_return &&
7265 is_type_compound(skip_typeref(function_type->return_type))) {
7266 warningf(&result->base.source_position,
7267 "function call has aggregate value");
7274 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7276 static bool same_compound_type(const type_t *type1, const type_t *type2)
7279 is_type_compound(type1) &&
7280 type1->kind == type2->kind &&
7281 type1->compound.declaration == type2->compound.declaration;
7285 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7287 * @param expression the conditional expression
7289 static expression_t *parse_conditional_expression(unsigned precedence,
7290 expression_t *expression)
7292 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7294 conditional_expression_t *conditional = &result->conditional;
7295 conditional->base.source_position = *HERE;
7296 conditional->condition = expression;
7299 add_anchor_token(':');
7302 type_t *const condition_type_orig = expression->base.type;
7303 type_t *const condition_type = skip_typeref(condition_type_orig);
7304 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7305 type_error("expected a scalar type in conditional condition",
7306 &expression->base.source_position, condition_type_orig);
7309 expression_t *true_expression = expression;
7310 bool gnu_cond = false;
7311 if (GNU_MODE && token.type == ':') {
7314 true_expression = parse_expression();
7315 rem_anchor_token(':');
7317 expression_t *false_expression = parse_sub_expression(precedence);
7319 type_t *const orig_true_type = true_expression->base.type;
7320 type_t *const orig_false_type = false_expression->base.type;
7321 type_t *const true_type = skip_typeref(orig_true_type);
7322 type_t *const false_type = skip_typeref(orig_false_type);
7325 type_t *result_type;
7326 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7327 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7328 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7329 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7330 warningf(&conditional->base.source_position,
7331 "ISO C forbids conditional expression with only one void side");
7333 result_type = type_void;
7334 } else if (is_type_arithmetic(true_type)
7335 && is_type_arithmetic(false_type)) {
7336 result_type = semantic_arithmetic(true_type, false_type);
7338 true_expression = create_implicit_cast(true_expression, result_type);
7339 false_expression = create_implicit_cast(false_expression, result_type);
7341 conditional->true_expression = true_expression;
7342 conditional->false_expression = false_expression;
7343 conditional->base.type = result_type;
7344 } else if (same_compound_type(true_type, false_type)) {
7345 /* just take 1 of the 2 types */
7346 result_type = true_type;
7347 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7348 type_t *pointer_type;
7350 expression_t *other_expression;
7351 if (is_type_pointer(true_type) &&
7352 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7353 pointer_type = true_type;
7354 other_type = false_type;
7355 other_expression = false_expression;
7357 pointer_type = false_type;
7358 other_type = true_type;
7359 other_expression = true_expression;
7362 if (is_null_pointer_constant(other_expression)) {
7363 result_type = pointer_type;
7364 } else if (is_type_pointer(other_type)) {
7365 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7366 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7369 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7370 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7372 } else if (types_compatible(get_unqualified_type(to1),
7373 get_unqualified_type(to2))) {
7376 warningf(&conditional->base.source_position,
7377 "pointer types '%T' and '%T' in conditional expression are incompatible",
7378 true_type, false_type);
7382 type_t *const type =
7383 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7384 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7385 } else if (is_type_integer(other_type)) {
7386 warningf(&conditional->base.source_position,
7387 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7388 result_type = pointer_type;
7390 type_error_incompatible("while parsing conditional",
7391 &expression->base.source_position, true_type, false_type);
7392 result_type = type_error_type;
7395 /* TODO: one pointer to void*, other some pointer */
7397 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7398 type_error_incompatible("while parsing conditional",
7399 &conditional->base.source_position, true_type,
7402 result_type = type_error_type;
7405 conditional->true_expression
7406 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7407 conditional->false_expression
7408 = create_implicit_cast(false_expression, result_type);
7409 conditional->base.type = result_type;
7412 return create_invalid_expression();
7416 * Parse an extension expression.
7418 static expression_t *parse_extension(unsigned precedence)
7420 eat(T___extension__);
7422 bool old_gcc_extension = in_gcc_extension;
7423 in_gcc_extension = true;
7424 expression_t *expression = parse_sub_expression(precedence);
7425 in_gcc_extension = old_gcc_extension;
7430 * Parse a __builtin_classify_type() expression.
7432 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7434 eat(T___builtin_classify_type);
7436 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7437 result->base.type = type_int;
7440 add_anchor_token(')');
7441 expression_t *expression = parse_sub_expression(precedence);
7442 rem_anchor_token(')');
7444 result->classify_type.type_expression = expression;
7448 return create_invalid_expression();
7451 static bool check_pointer_arithmetic(const source_position_t *source_position,
7452 type_t *pointer_type,
7453 type_t *orig_pointer_type)
7455 type_t *points_to = pointer_type->pointer.points_to;
7456 points_to = skip_typeref(points_to);
7458 if (is_type_incomplete(points_to)) {
7459 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7460 errorf(source_position,
7461 "arithmetic with pointer to incomplete type '%T' not allowed",
7464 } else if (warning.pointer_arith) {
7465 warningf(source_position,
7466 "pointer of type '%T' used in arithmetic",
7469 } else if (is_type_function(points_to)) {
7471 errorf(source_position,
7472 "arithmetic with pointer to function type '%T' not allowed",
7475 } else if (warning.pointer_arith) {
7476 warningf(source_position,
7477 "pointer to a function '%T' used in arithmetic",
7484 static bool is_lvalue(const expression_t *expression)
7486 switch (expression->kind) {
7487 case EXPR_REFERENCE:
7488 case EXPR_ARRAY_ACCESS:
7490 case EXPR_UNARY_DEREFERENCE:
7498 static void semantic_incdec(unary_expression_t *expression)
7500 type_t *const orig_type = expression->value->base.type;
7501 type_t *const type = skip_typeref(orig_type);
7502 if (is_type_pointer(type)) {
7503 if (!check_pointer_arithmetic(&expression->base.source_position,
7507 } else if (!is_type_real(type) && is_type_valid(type)) {
7508 /* TODO: improve error message */
7509 errorf(&expression->base.source_position,
7510 "operation needs an arithmetic or pointer type");
7513 if (!is_lvalue(expression->value)) {
7514 /* TODO: improve error message */
7515 errorf(&expression->base.source_position, "lvalue required as operand");
7517 expression->base.type = orig_type;
7520 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7522 type_t *const orig_type = expression->value->base.type;
7523 type_t *const type = skip_typeref(orig_type);
7524 if (!is_type_arithmetic(type)) {
7525 if (is_type_valid(type)) {
7526 /* TODO: improve error message */
7527 errorf(&expression->base.source_position,
7528 "operation needs an arithmetic type");
7533 expression->base.type = orig_type;
7536 static void semantic_unexpr_plus(unary_expression_t *expression)
7538 semantic_unexpr_arithmetic(expression);
7539 if (warning.traditional)
7540 warningf(&expression->base.source_position,
7541 "traditional C rejects the unary plus operator");
7544 static expression_t const *get_reference_address(expression_t const *expr)
7546 bool regular_take_address = true;
7548 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7549 expr = expr->unary.value;
7551 regular_take_address = false;
7554 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7557 expr = expr->unary.value;
7560 if (expr->kind != EXPR_REFERENCE)
7563 if (!regular_take_address &&
7564 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7571 static void warn_function_address_as_bool(expression_t const* expr)
7573 if (!warning.address)
7576 expr = get_reference_address(expr);
7578 warningf(&expr->base.source_position,
7579 "the address of '%Y' will always evaluate as 'true'",
7580 expr->reference.declaration->symbol);
7584 static void semantic_not(unary_expression_t *expression)
7586 type_t *const orig_type = expression->value->base.type;
7587 type_t *const type = skip_typeref(orig_type);
7588 if (!is_type_scalar(type) && is_type_valid(type)) {
7589 errorf(&expression->base.source_position,
7590 "operand of ! must be of scalar type");
7593 warn_function_address_as_bool(expression->value);
7595 expression->base.type = type_int;
7598 static void semantic_unexpr_integer(unary_expression_t *expression)
7600 type_t *const orig_type = expression->value->base.type;
7601 type_t *const type = skip_typeref(orig_type);
7602 if (!is_type_integer(type)) {
7603 if (is_type_valid(type)) {
7604 errorf(&expression->base.source_position,
7605 "operand of ~ must be of integer type");
7610 expression->base.type = orig_type;
7613 static void semantic_dereference(unary_expression_t *expression)
7615 type_t *const orig_type = expression->value->base.type;
7616 type_t *const type = skip_typeref(orig_type);
7617 if (!is_type_pointer(type)) {
7618 if (is_type_valid(type)) {
7619 errorf(&expression->base.source_position,
7620 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7625 type_t *result_type = type->pointer.points_to;
7626 result_type = automatic_type_conversion(result_type);
7627 expression->base.type = result_type;
7631 * Record that an address is taken (expression represents an lvalue).
7633 * @param expression the expression
7634 * @param may_be_register if true, the expression might be an register
7636 static void set_address_taken(expression_t *expression, bool may_be_register)
7638 if (expression->kind != EXPR_REFERENCE)
7641 declaration_t *const declaration = expression->reference.declaration;
7642 /* happens for parse errors */
7643 if (declaration == NULL)
7646 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7647 errorf(&expression->base.source_position,
7648 "address of register variable '%Y' requested",
7649 declaration->symbol);
7651 declaration->address_taken = 1;
7656 * Check the semantic of the address taken expression.
7658 static void semantic_take_addr(unary_expression_t *expression)
7660 expression_t *value = expression->value;
7661 value->base.type = revert_automatic_type_conversion(value);
7663 type_t *orig_type = value->base.type;
7664 if (!is_type_valid(orig_type))
7667 set_address_taken(value, false);
7669 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7672 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7673 static expression_t *parse_##unexpression_type(unsigned precedence) \
7675 expression_t *unary_expression \
7676 = allocate_expression_zero(unexpression_type); \
7677 unary_expression->base.source_position = *HERE; \
7679 unary_expression->unary.value = parse_sub_expression(precedence); \
7681 sfunc(&unary_expression->unary); \
7683 return unary_expression; \
7686 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7687 semantic_unexpr_arithmetic)
7688 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7689 semantic_unexpr_plus)
7690 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7692 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7693 semantic_dereference)
7694 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7696 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7697 semantic_unexpr_integer)
7698 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7700 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7703 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7705 static expression_t *parse_##unexpression_type(unsigned precedence, \
7706 expression_t *left) \
7708 (void) precedence; \
7710 expression_t *unary_expression \
7711 = allocate_expression_zero(unexpression_type); \
7712 unary_expression->base.source_position = *HERE; \
7714 unary_expression->unary.value = left; \
7716 sfunc(&unary_expression->unary); \
7718 return unary_expression; \
7721 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7722 EXPR_UNARY_POSTFIX_INCREMENT,
7724 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7725 EXPR_UNARY_POSTFIX_DECREMENT,
7728 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7730 /* TODO: handle complex + imaginary types */
7732 type_left = get_unqualified_type(type_left);
7733 type_right = get_unqualified_type(type_right);
7735 /* § 6.3.1.8 Usual arithmetic conversions */
7736 if (type_left == type_long_double || type_right == type_long_double) {
7737 return type_long_double;
7738 } else if (type_left == type_double || type_right == type_double) {
7740 } else if (type_left == type_float || type_right == type_float) {
7744 type_left = promote_integer(type_left);
7745 type_right = promote_integer(type_right);
7747 if (type_left == type_right)
7750 bool const signed_left = is_type_signed(type_left);
7751 bool const signed_right = is_type_signed(type_right);
7752 int const rank_left = get_rank(type_left);
7753 int const rank_right = get_rank(type_right);
7755 if (signed_left == signed_right)
7756 return rank_left >= rank_right ? type_left : type_right;
7765 u_rank = rank_right;
7766 u_type = type_right;
7768 s_rank = rank_right;
7769 s_type = type_right;
7774 if (u_rank >= s_rank)
7777 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7779 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7780 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7784 case ATOMIC_TYPE_INT: return type_unsigned_int;
7785 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7786 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7788 default: panic("invalid atomic type");
7793 * Check the semantic restrictions for a binary expression.
7795 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7797 expression_t *const left = expression->left;
7798 expression_t *const right = expression->right;
7799 type_t *const orig_type_left = left->base.type;
7800 type_t *const orig_type_right = right->base.type;
7801 type_t *const type_left = skip_typeref(orig_type_left);
7802 type_t *const type_right = skip_typeref(orig_type_right);
7804 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7805 /* TODO: improve error message */
7806 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7807 errorf(&expression->base.source_position,
7808 "operation needs arithmetic types");
7813 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7814 expression->left = create_implicit_cast(left, arithmetic_type);
7815 expression->right = create_implicit_cast(right, arithmetic_type);
7816 expression->base.type = arithmetic_type;
7819 static void warn_div_by_zero(binary_expression_t const *const expression)
7821 if (!warning.div_by_zero ||
7822 !is_type_integer(expression->base.type))
7825 expression_t const *const right = expression->right;
7826 /* The type of the right operand can be different for /= */
7827 if (is_type_integer(right->base.type) &&
7828 is_constant_expression(right) &&
7829 fold_constant(right) == 0) {
7830 warningf(&expression->base.source_position, "division by zero");
7835 * Check the semantic restrictions for a div/mod expression.
7837 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7838 semantic_binexpr_arithmetic(expression);
7839 warn_div_by_zero(expression);
7842 static void semantic_shift_op(binary_expression_t *expression)
7844 expression_t *const left = expression->left;
7845 expression_t *const right = expression->right;
7846 type_t *const orig_type_left = left->base.type;
7847 type_t *const orig_type_right = right->base.type;
7848 type_t * type_left = skip_typeref(orig_type_left);
7849 type_t * type_right = skip_typeref(orig_type_right);
7851 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7852 /* TODO: improve error message */
7853 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7854 errorf(&expression->base.source_position,
7855 "operands of shift operation must have integer types");
7860 type_left = promote_integer(type_left);
7861 type_right = promote_integer(type_right);
7863 expression->left = create_implicit_cast(left, type_left);
7864 expression->right = create_implicit_cast(right, type_right);
7865 expression->base.type = type_left;
7868 static void semantic_add(binary_expression_t *expression)
7870 expression_t *const left = expression->left;
7871 expression_t *const right = expression->right;
7872 type_t *const orig_type_left = left->base.type;
7873 type_t *const orig_type_right = right->base.type;
7874 type_t *const type_left = skip_typeref(orig_type_left);
7875 type_t *const type_right = skip_typeref(orig_type_right);
7878 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7879 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7880 expression->left = create_implicit_cast(left, arithmetic_type);
7881 expression->right = create_implicit_cast(right, arithmetic_type);
7882 expression->base.type = arithmetic_type;
7884 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7885 check_pointer_arithmetic(&expression->base.source_position,
7886 type_left, orig_type_left);
7887 expression->base.type = type_left;
7888 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7889 check_pointer_arithmetic(&expression->base.source_position,
7890 type_right, orig_type_right);
7891 expression->base.type = type_right;
7892 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7893 errorf(&expression->base.source_position,
7894 "invalid operands to binary + ('%T', '%T')",
7895 orig_type_left, orig_type_right);
7899 static void semantic_sub(binary_expression_t *expression)
7901 expression_t *const left = expression->left;
7902 expression_t *const right = expression->right;
7903 type_t *const orig_type_left = left->base.type;
7904 type_t *const orig_type_right = right->base.type;
7905 type_t *const type_left = skip_typeref(orig_type_left);
7906 type_t *const type_right = skip_typeref(orig_type_right);
7907 source_position_t const *const pos = &expression->base.source_position;
7910 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7911 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7912 expression->left = create_implicit_cast(left, arithmetic_type);
7913 expression->right = create_implicit_cast(right, arithmetic_type);
7914 expression->base.type = arithmetic_type;
7916 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7917 check_pointer_arithmetic(&expression->base.source_position,
7918 type_left, orig_type_left);
7919 expression->base.type = type_left;
7920 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7921 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7922 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7923 if (!types_compatible(unqual_left, unqual_right)) {
7925 "subtracting pointers to incompatible types '%T' and '%T'",
7926 orig_type_left, orig_type_right);
7927 } else if (!is_type_object(unqual_left)) {
7928 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7929 warningf(pos, "subtracting pointers to void");
7931 errorf(pos, "subtracting pointers to non-object types '%T'",
7935 expression->base.type = type_ptrdiff_t;
7936 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7937 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7938 orig_type_left, orig_type_right);
7942 static void warn_string_literal_address(expression_t const* expr)
7944 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7945 expr = expr->unary.value;
7946 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7948 expr = expr->unary.value;
7951 if (expr->kind == EXPR_STRING_LITERAL ||
7952 expr->kind == EXPR_WIDE_STRING_LITERAL) {
7953 warningf(&expr->base.source_position,
7954 "comparison with string literal results in unspecified behaviour");
7959 * Check the semantics of comparison expressions.
7961 * @param expression The expression to check.
7963 static void semantic_comparison(binary_expression_t *expression)
7965 expression_t *left = expression->left;
7966 expression_t *right = expression->right;
7968 if (warning.address) {
7969 warn_string_literal_address(left);
7970 warn_string_literal_address(right);
7972 expression_t const* const func_left = get_reference_address(left);
7973 if (func_left != NULL && is_null_pointer_constant(right)) {
7974 warningf(&expression->base.source_position,
7975 "the address of '%Y' will never be NULL",
7976 func_left->reference.declaration->symbol);
7979 expression_t const* const func_right = get_reference_address(right);
7980 if (func_right != NULL && is_null_pointer_constant(right)) {
7981 warningf(&expression->base.source_position,
7982 "the address of '%Y' will never be NULL",
7983 func_right->reference.declaration->symbol);
7987 type_t *orig_type_left = left->base.type;
7988 type_t *orig_type_right = right->base.type;
7989 type_t *type_left = skip_typeref(orig_type_left);
7990 type_t *type_right = skip_typeref(orig_type_right);
7992 /* TODO non-arithmetic types */
7993 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7994 /* test for signed vs unsigned compares */
7995 if (warning.sign_compare &&
7996 (expression->base.kind != EXPR_BINARY_EQUAL &&
7997 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7998 (is_type_signed(type_left) != is_type_signed(type_right))) {
8000 /* check if 1 of the operands is a constant, in this case we just
8001 * check wether we can safely represent the resulting constant in
8002 * the type of the other operand. */
8003 expression_t *const_expr = NULL;
8004 expression_t *other_expr = NULL;
8006 if (is_constant_expression(left)) {
8009 } else if (is_constant_expression(right)) {
8014 if (const_expr != NULL) {
8015 type_t *other_type = skip_typeref(other_expr->base.type);
8016 long val = fold_constant(const_expr);
8017 /* TODO: check if val can be represented by other_type */
8021 warningf(&expression->base.source_position,
8022 "comparison between signed and unsigned");
8024 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8025 expression->left = create_implicit_cast(left, arithmetic_type);
8026 expression->right = create_implicit_cast(right, arithmetic_type);
8027 expression->base.type = arithmetic_type;
8028 if (warning.float_equal &&
8029 (expression->base.kind == EXPR_BINARY_EQUAL ||
8030 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8031 is_type_float(arithmetic_type)) {
8032 warningf(&expression->base.source_position,
8033 "comparing floating point with == or != is unsafe");
8035 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8036 /* TODO check compatibility */
8037 } else if (is_type_pointer(type_left)) {
8038 expression->right = create_implicit_cast(right, type_left);
8039 } else if (is_type_pointer(type_right)) {
8040 expression->left = create_implicit_cast(left, type_right);
8041 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8042 type_error_incompatible("invalid operands in comparison",
8043 &expression->base.source_position,
8044 type_left, type_right);
8046 expression->base.type = type_int;
8050 * Checks if a compound type has constant fields.
8052 static bool has_const_fields(const compound_type_t *type)
8054 const scope_t *scope = &type->declaration->scope;
8055 const declaration_t *declaration = scope->declarations;
8057 for (; declaration != NULL; declaration = declaration->next) {
8058 if (declaration->namespc != NAMESPACE_NORMAL)
8061 const type_t *decl_type = skip_typeref(declaration->type);
8062 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8069 static bool is_valid_assignment_lhs(expression_t const* const left)
8071 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8072 type_t *const type_left = skip_typeref(orig_type_left);
8074 if (!is_lvalue(left)) {
8075 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8080 if (is_type_array(type_left)) {
8081 errorf(HERE, "cannot assign to arrays ('%E')", left);
8084 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8085 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8089 if (is_type_incomplete(type_left)) {
8090 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8091 left, orig_type_left);
8094 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8095 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8096 left, orig_type_left);
8103 static void semantic_arithmetic_assign(binary_expression_t *expression)
8105 expression_t *left = expression->left;
8106 expression_t *right = expression->right;
8107 type_t *orig_type_left = left->base.type;
8108 type_t *orig_type_right = right->base.type;
8110 if (!is_valid_assignment_lhs(left))
8113 type_t *type_left = skip_typeref(orig_type_left);
8114 type_t *type_right = skip_typeref(orig_type_right);
8116 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8117 /* TODO: improve error message */
8118 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8119 errorf(&expression->base.source_position,
8120 "operation needs arithmetic types");
8125 /* combined instructions are tricky. We can't create an implicit cast on
8126 * the left side, because we need the uncasted form for the store.
8127 * The ast2firm pass has to know that left_type must be right_type
8128 * for the arithmetic operation and create a cast by itself */
8129 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8130 expression->right = create_implicit_cast(right, arithmetic_type);
8131 expression->base.type = type_left;
8134 static void semantic_divmod_assign(binary_expression_t *expression)
8136 semantic_arithmetic_assign(expression);
8137 warn_div_by_zero(expression);
8140 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8142 expression_t *const left = expression->left;
8143 expression_t *const right = expression->right;
8144 type_t *const orig_type_left = left->base.type;
8145 type_t *const orig_type_right = right->base.type;
8146 type_t *const type_left = skip_typeref(orig_type_left);
8147 type_t *const type_right = skip_typeref(orig_type_right);
8149 if (!is_valid_assignment_lhs(left))
8152 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8153 /* combined instructions are tricky. We can't create an implicit cast on
8154 * the left side, because we need the uncasted form for the store.
8155 * The ast2firm pass has to know that left_type must be right_type
8156 * for the arithmetic operation and create a cast by itself */
8157 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8158 expression->right = create_implicit_cast(right, arithmetic_type);
8159 expression->base.type = type_left;
8160 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8161 check_pointer_arithmetic(&expression->base.source_position,
8162 type_left, orig_type_left);
8163 expression->base.type = type_left;
8164 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8165 errorf(&expression->base.source_position,
8166 "incompatible types '%T' and '%T' in assignment",
8167 orig_type_left, orig_type_right);
8172 * Check the semantic restrictions of a logical expression.
8174 static void semantic_logical_op(binary_expression_t *expression)
8176 expression_t *const left = expression->left;
8177 expression_t *const right = expression->right;
8178 type_t *const orig_type_left = left->base.type;
8179 type_t *const orig_type_right = right->base.type;
8180 type_t *const type_left = skip_typeref(orig_type_left);
8181 type_t *const type_right = skip_typeref(orig_type_right);
8183 warn_function_address_as_bool(left);
8184 warn_function_address_as_bool(right);
8186 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8187 /* TODO: improve error message */
8188 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8189 errorf(&expression->base.source_position,
8190 "operation needs scalar types");
8195 expression->base.type = type_int;
8199 * Check the semantic restrictions of a binary assign expression.
8201 static void semantic_binexpr_assign(binary_expression_t *expression)
8203 expression_t *left = expression->left;
8204 type_t *orig_type_left = left->base.type;
8206 if (!is_valid_assignment_lhs(left))
8209 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8210 report_assign_error(error, orig_type_left, expression->right,
8211 "assignment", &left->base.source_position);
8212 expression->right = create_implicit_cast(expression->right, orig_type_left);
8213 expression->base.type = orig_type_left;
8217 * Determine if the outermost operation (or parts thereof) of the given
8218 * expression has no effect in order to generate a warning about this fact.
8219 * Therefore in some cases this only examines some of the operands of the
8220 * expression (see comments in the function and examples below).
8222 * f() + 23; // warning, because + has no effect
8223 * x || f(); // no warning, because x controls execution of f()
8224 * x ? y : f(); // warning, because y has no effect
8225 * (void)x; // no warning to be able to suppress the warning
8226 * This function can NOT be used for an "expression has definitely no effect"-
8228 static bool expression_has_effect(const expression_t *const expr)
8230 switch (expr->kind) {
8231 case EXPR_UNKNOWN: break;
8232 case EXPR_INVALID: return true; /* do NOT warn */
8233 case EXPR_REFERENCE: return false;
8234 /* suppress the warning for microsoft __noop operations */
8235 case EXPR_CONST: return expr->conste.is_ms_noop;
8236 case EXPR_CHARACTER_CONSTANT: return false;
8237 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8238 case EXPR_STRING_LITERAL: return false;
8239 case EXPR_WIDE_STRING_LITERAL: return false;
8240 case EXPR_LABEL_ADDRESS: return false;
8243 const call_expression_t *const call = &expr->call;
8244 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8247 switch (call->function->builtin_symbol.symbol->ID) {
8248 case T___builtin_va_end: return true;
8249 default: return false;
8253 /* Generate the warning if either the left or right hand side of a
8254 * conditional expression has no effect */
8255 case EXPR_CONDITIONAL: {
8256 const conditional_expression_t *const cond = &expr->conditional;
8258 expression_has_effect(cond->true_expression) &&
8259 expression_has_effect(cond->false_expression);
8262 case EXPR_SELECT: return false;
8263 case EXPR_ARRAY_ACCESS: return false;
8264 case EXPR_SIZEOF: return false;
8265 case EXPR_CLASSIFY_TYPE: return false;
8266 case EXPR_ALIGNOF: return false;
8268 case EXPR_FUNCNAME: return false;
8269 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8270 case EXPR_BUILTIN_CONSTANT_P: return false;
8271 case EXPR_BUILTIN_PREFETCH: return true;
8272 case EXPR_OFFSETOF: return false;
8273 case EXPR_VA_START: return true;
8274 case EXPR_VA_ARG: return true;
8275 case EXPR_STATEMENT: return true; // TODO
8276 case EXPR_COMPOUND_LITERAL: return false;
8278 case EXPR_UNARY_NEGATE: return false;
8279 case EXPR_UNARY_PLUS: return false;
8280 case EXPR_UNARY_BITWISE_NEGATE: return false;
8281 case EXPR_UNARY_NOT: return false;
8282 case EXPR_UNARY_DEREFERENCE: return false;
8283 case EXPR_UNARY_TAKE_ADDRESS: return false;
8284 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8285 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8286 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8287 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8289 /* Treat void casts as if they have an effect in order to being able to
8290 * suppress the warning */
8291 case EXPR_UNARY_CAST: {
8292 type_t *const type = skip_typeref(expr->base.type);
8293 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8296 case EXPR_UNARY_CAST_IMPLICIT: return true;
8297 case EXPR_UNARY_ASSUME: return true;
8299 case EXPR_BINARY_ADD: return false;
8300 case EXPR_BINARY_SUB: return false;
8301 case EXPR_BINARY_MUL: return false;
8302 case EXPR_BINARY_DIV: return false;
8303 case EXPR_BINARY_MOD: return false;
8304 case EXPR_BINARY_EQUAL: return false;
8305 case EXPR_BINARY_NOTEQUAL: return false;
8306 case EXPR_BINARY_LESS: return false;
8307 case EXPR_BINARY_LESSEQUAL: return false;
8308 case EXPR_BINARY_GREATER: return false;
8309 case EXPR_BINARY_GREATEREQUAL: return false;
8310 case EXPR_BINARY_BITWISE_AND: return false;
8311 case EXPR_BINARY_BITWISE_OR: return false;
8312 case EXPR_BINARY_BITWISE_XOR: return false;
8313 case EXPR_BINARY_SHIFTLEFT: return false;
8314 case EXPR_BINARY_SHIFTRIGHT: return false;
8315 case EXPR_BINARY_ASSIGN: return true;
8316 case EXPR_BINARY_MUL_ASSIGN: return true;
8317 case EXPR_BINARY_DIV_ASSIGN: return true;
8318 case EXPR_BINARY_MOD_ASSIGN: return true;
8319 case EXPR_BINARY_ADD_ASSIGN: return true;
8320 case EXPR_BINARY_SUB_ASSIGN: return true;
8321 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8322 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8323 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8324 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8325 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8327 /* Only examine the right hand side of && and ||, because the left hand
8328 * side already has the effect of controlling the execution of the right
8330 case EXPR_BINARY_LOGICAL_AND:
8331 case EXPR_BINARY_LOGICAL_OR:
8332 /* Only examine the right hand side of a comma expression, because the left
8333 * hand side has a separate warning */
8334 case EXPR_BINARY_COMMA:
8335 return expression_has_effect(expr->binary.right);
8337 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8338 case EXPR_BINARY_ISGREATER: return false;
8339 case EXPR_BINARY_ISGREATEREQUAL: return false;
8340 case EXPR_BINARY_ISLESS: return false;
8341 case EXPR_BINARY_ISLESSEQUAL: return false;
8342 case EXPR_BINARY_ISLESSGREATER: return false;
8343 case EXPR_BINARY_ISUNORDERED: return false;
8346 internal_errorf(HERE, "unexpected expression");
8349 static void semantic_comma(binary_expression_t *expression)
8351 if (warning.unused_value) {
8352 const expression_t *const left = expression->left;
8353 if (!expression_has_effect(left)) {
8354 warningf(&left->base.source_position,
8355 "left-hand operand of comma expression has no effect");
8358 expression->base.type = expression->right->base.type;
8361 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8362 static expression_t *parse_##binexpression_type(unsigned precedence, \
8363 expression_t *left) \
8365 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8366 binexpr->base.source_position = *HERE; \
8367 binexpr->binary.left = left; \
8370 expression_t *right = parse_sub_expression(precedence + lr); \
8372 binexpr->binary.right = right; \
8373 sfunc(&binexpr->binary); \
8378 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8379 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8380 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8381 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8382 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8383 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8384 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8385 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8386 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8388 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8389 semantic_comparison, 1)
8390 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8391 semantic_comparison, 1)
8392 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8393 semantic_comparison, 1)
8394 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8395 semantic_comparison, 1)
8397 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8398 semantic_binexpr_arithmetic, 1)
8399 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8400 semantic_binexpr_arithmetic, 1)
8401 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8402 semantic_binexpr_arithmetic, 1)
8403 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8404 semantic_logical_op, 1)
8405 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8406 semantic_logical_op, 1)
8407 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8408 semantic_shift_op, 1)
8409 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8410 semantic_shift_op, 1)
8411 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8412 semantic_arithmetic_addsubb_assign, 0)
8413 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8414 semantic_arithmetic_addsubb_assign, 0)
8415 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8416 semantic_arithmetic_assign, 0)
8417 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8418 semantic_divmod_assign, 0)
8419 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8420 semantic_divmod_assign, 0)
8421 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8422 semantic_arithmetic_assign, 0)
8423 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8424 semantic_arithmetic_assign, 0)
8425 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8426 semantic_arithmetic_assign, 0)
8427 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8428 semantic_arithmetic_assign, 0)
8429 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8430 semantic_arithmetic_assign, 0)
8432 static expression_t *parse_sub_expression(unsigned precedence)
8434 if (token.type < 0) {
8435 return expected_expression_error();
8438 expression_parser_function_t *parser
8439 = &expression_parsers[token.type];
8440 source_position_t source_position = token.source_position;
8443 if (parser->parser != NULL) {
8444 left = parser->parser(parser->precedence);
8446 left = parse_primary_expression();
8448 assert(left != NULL);
8449 left->base.source_position = source_position;
8452 if (token.type < 0) {
8453 return expected_expression_error();
8456 parser = &expression_parsers[token.type];
8457 if (parser->infix_parser == NULL)
8459 if (parser->infix_precedence < precedence)
8462 left = parser->infix_parser(parser->infix_precedence, left);
8464 assert(left != NULL);
8465 assert(left->kind != EXPR_UNKNOWN);
8466 left->base.source_position = source_position;
8473 * Parse an expression.
8475 static expression_t *parse_expression(void)
8477 return parse_sub_expression(1);
8481 * Register a parser for a prefix-like operator with given precedence.
8483 * @param parser the parser function
8484 * @param token_type the token type of the prefix token
8485 * @param precedence the precedence of the operator
8487 static void register_expression_parser(parse_expression_function parser,
8488 int token_type, unsigned precedence)
8490 expression_parser_function_t *entry = &expression_parsers[token_type];
8492 if (entry->parser != NULL) {
8493 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8494 panic("trying to register multiple expression parsers for a token");
8496 entry->parser = parser;
8497 entry->precedence = precedence;
8501 * Register a parser for an infix operator with given precedence.
8503 * @param parser the parser function
8504 * @param token_type the token type of the infix operator
8505 * @param precedence the precedence of the operator
8507 static void register_infix_parser(parse_expression_infix_function parser,
8508 int token_type, unsigned precedence)
8510 expression_parser_function_t *entry = &expression_parsers[token_type];
8512 if (entry->infix_parser != NULL) {
8513 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8514 panic("trying to register multiple infix expression parsers for a "
8517 entry->infix_parser = parser;
8518 entry->infix_precedence = precedence;
8522 * Initialize the expression parsers.
8524 static void init_expression_parsers(void)
8526 memset(&expression_parsers, 0, sizeof(expression_parsers));
8528 register_infix_parser(parse_array_expression, '[', 30);
8529 register_infix_parser(parse_call_expression, '(', 30);
8530 register_infix_parser(parse_select_expression, '.', 30);
8531 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8532 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8534 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8537 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8538 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8539 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8540 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8541 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8542 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8543 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8544 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8545 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8546 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8547 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8548 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8549 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8550 T_EXCLAMATIONMARKEQUAL, 13);
8551 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8552 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8553 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8554 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8555 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8556 register_infix_parser(parse_conditional_expression, '?', 7);
8557 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8558 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8559 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8560 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8561 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8562 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8563 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8564 T_LESSLESSEQUAL, 2);
8565 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8566 T_GREATERGREATEREQUAL, 2);
8567 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8569 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8571 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8574 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8576 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8577 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8578 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8579 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8580 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8581 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8582 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8584 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8586 register_expression_parser(parse_sizeof, T_sizeof, 25);
8587 register_expression_parser(parse_alignof, T___alignof__, 25);
8588 register_expression_parser(parse_extension, T___extension__, 25);
8589 register_expression_parser(parse_builtin_classify_type,
8590 T___builtin_classify_type, 25);
8594 * Parse a asm statement arguments specification.
8596 static asm_argument_t *parse_asm_arguments(bool is_out)
8598 asm_argument_t *result = NULL;
8599 asm_argument_t *last = NULL;
8601 while (token.type == T_STRING_LITERAL || token.type == '[') {
8602 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8603 memset(argument, 0, sizeof(argument[0]));
8605 if (token.type == '[') {
8607 if (token.type != T_IDENTIFIER) {
8608 parse_error_expected("while parsing asm argument",
8609 T_IDENTIFIER, NULL);
8612 argument->symbol = token.v.symbol;
8617 argument->constraints = parse_string_literals();
8619 add_anchor_token(')');
8620 expression_t *expression = parse_expression();
8621 rem_anchor_token(')');
8623 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8624 * change size or type representation (e.g. int -> long is ok, but
8625 * int -> float is not) */
8626 if (expression->kind == EXPR_UNARY_CAST) {
8627 type_t *const type = expression->base.type;
8628 type_kind_t const kind = type->kind;
8629 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8632 if (kind == TYPE_ATOMIC) {
8633 atomic_type_kind_t const akind = type->atomic.akind;
8634 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8635 size = get_atomic_type_size(akind);
8637 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8638 size = get_atomic_type_size(get_intptr_kind());
8642 expression_t *const value = expression->unary.value;
8643 type_t *const value_type = value->base.type;
8644 type_kind_t const value_kind = value_type->kind;
8646 unsigned value_flags;
8647 unsigned value_size;
8648 if (value_kind == TYPE_ATOMIC) {
8649 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8650 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8651 value_size = get_atomic_type_size(value_akind);
8652 } else if (value_kind == TYPE_POINTER) {
8653 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8654 value_size = get_atomic_type_size(get_intptr_kind());
8659 if (value_flags != flags || value_size != size)
8663 } while (expression->kind == EXPR_UNARY_CAST);
8667 if (!is_lvalue(expression)) {
8668 errorf(&expression->base.source_position,
8669 "asm output argument is not an lvalue");
8672 argument->expression = expression;
8675 set_address_taken(expression, true);
8678 last->next = argument;
8684 if (token.type != ',')
8695 * Parse a asm statement clobber specification.
8697 static asm_clobber_t *parse_asm_clobbers(void)
8699 asm_clobber_t *result = NULL;
8700 asm_clobber_t *last = NULL;
8702 while(token.type == T_STRING_LITERAL) {
8703 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8704 clobber->clobber = parse_string_literals();
8707 last->next = clobber;
8713 if (token.type != ',')
8722 * Parse an asm statement.
8724 static statement_t *parse_asm_statement(void)
8728 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8729 statement->base.source_position = token.source_position;
8731 asm_statement_t *asm_statement = &statement->asms;
8733 if (token.type == T_volatile) {
8735 asm_statement->is_volatile = true;
8739 add_anchor_token(')');
8740 add_anchor_token(':');
8741 asm_statement->asm_text = parse_string_literals();
8743 if (token.type != ':') {
8744 rem_anchor_token(':');
8749 asm_statement->outputs = parse_asm_arguments(true);
8750 if (token.type != ':') {
8751 rem_anchor_token(':');
8756 asm_statement->inputs = parse_asm_arguments(false);
8757 if (token.type != ':') {
8758 rem_anchor_token(':');
8761 rem_anchor_token(':');
8764 asm_statement->clobbers = parse_asm_clobbers();
8767 rem_anchor_token(')');
8771 if (asm_statement->outputs == NULL) {
8772 /* GCC: An 'asm' instruction without any output operands will be treated
8773 * identically to a volatile 'asm' instruction. */
8774 asm_statement->is_volatile = true;
8779 return create_invalid_statement();
8783 * Parse a case statement.
8785 static statement_t *parse_case_statement(void)
8789 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8790 source_position_t *const pos = &statement->base.source_position;
8792 *pos = token.source_position;
8793 expression_t *const expression = parse_expression();
8794 statement->case_label.expression = expression;
8795 if (!is_constant_expression(expression)) {
8796 /* This check does not prevent the error message in all cases of an
8797 * prior error while parsing the expression. At least it catches the
8798 * common case of a mistyped enum entry. */
8799 if (is_type_valid(expression->base.type)) {
8800 errorf(pos, "case label does not reduce to an integer constant");
8802 statement->case_label.is_bad = true;
8804 long const val = fold_constant(expression);
8805 statement->case_label.first_case = val;
8806 statement->case_label.last_case = val;
8810 if (token.type == T_DOTDOTDOT) {
8812 expression_t *const end_range = parse_expression();
8813 statement->case_label.end_range = end_range;
8814 if (!is_constant_expression(end_range)) {
8815 /* This check does not prevent the error message in all cases of an
8816 * prior error while parsing the expression. At least it catches the
8817 * common case of a mistyped enum entry. */
8818 if (is_type_valid(end_range->base.type)) {
8819 errorf(pos, "case range does not reduce to an integer constant");
8821 statement->case_label.is_bad = true;
8823 long const val = fold_constant(end_range);
8824 statement->case_label.last_case = val;
8826 if (val < statement->case_label.first_case) {
8827 statement->case_label.is_empty_range = true;
8828 warningf(pos, "empty range specified");
8834 PUSH_PARENT(statement);
8838 if (current_switch != NULL) {
8839 if (! statement->case_label.is_bad) {
8840 /* Check for duplicate case values */
8841 case_label_statement_t *c = &statement->case_label;
8842 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8843 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8846 if (c->last_case < l->first_case || c->first_case > l->last_case)
8849 errorf(pos, "duplicate case value (previously used %P)",
8850 &l->base.source_position);
8854 /* link all cases into the switch statement */
8855 if (current_switch->last_case == NULL) {
8856 current_switch->first_case = &statement->case_label;
8858 current_switch->last_case->next = &statement->case_label;
8860 current_switch->last_case = &statement->case_label;
8862 errorf(pos, "case label not within a switch statement");
8865 statement_t *const inner_stmt = parse_statement();
8866 statement->case_label.statement = inner_stmt;
8867 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8868 errorf(&inner_stmt->base.source_position, "declaration after case label");
8875 return create_invalid_statement();
8879 * Parse a default statement.
8881 static statement_t *parse_default_statement(void)
8885 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8886 statement->base.source_position = token.source_position;
8888 PUSH_PARENT(statement);
8891 if (current_switch != NULL) {
8892 const case_label_statement_t *def_label = current_switch->default_label;
8893 if (def_label != NULL) {
8894 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8895 &def_label->base.source_position);
8897 current_switch->default_label = &statement->case_label;
8899 /* link all cases into the switch statement */
8900 if (current_switch->last_case == NULL) {
8901 current_switch->first_case = &statement->case_label;
8903 current_switch->last_case->next = &statement->case_label;
8905 current_switch->last_case = &statement->case_label;
8908 errorf(&statement->base.source_position,
8909 "'default' label not within a switch statement");
8912 statement_t *const inner_stmt = parse_statement();
8913 statement->case_label.statement = inner_stmt;
8914 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8915 errorf(&inner_stmt->base.source_position, "declaration after default label");
8922 return create_invalid_statement();
8926 * Parse a label statement.
8928 static statement_t *parse_label_statement(void)
8930 assert(token.type == T_IDENTIFIER);
8931 symbol_t *symbol = token.v.symbol;
8934 declaration_t *label = get_label(symbol);
8936 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8937 statement->base.source_position = token.source_position;
8938 statement->label.label = label;
8940 PUSH_PARENT(statement);
8942 /* if statement is already set then the label is defined twice,
8943 * otherwise it was just mentioned in a goto/local label declaration so far */
8944 if (label->init.statement != NULL) {
8945 errorf(HERE, "duplicate label '%Y' (declared %P)",
8946 symbol, &label->source_position);
8948 label->source_position = token.source_position;
8949 label->init.statement = statement;
8954 if (token.type == '}') {
8955 /* TODO only warn? */
8957 warningf(HERE, "label at end of compound statement");
8958 statement->label.statement = create_empty_statement();
8960 errorf(HERE, "label at end of compound statement");
8961 statement->label.statement = create_invalid_statement();
8963 } else if (token.type == ';') {
8964 /* Eat an empty statement here, to avoid the warning about an empty
8965 * statement after a label. label:; is commonly used to have a label
8966 * before a closing brace. */
8967 statement->label.statement = create_empty_statement();
8970 statement_t *const inner_stmt = parse_statement();
8971 statement->label.statement = inner_stmt;
8972 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8973 errorf(&inner_stmt->base.source_position, "declaration after label");
8977 /* remember the labels in a list for later checking */
8978 if (label_last == NULL) {
8979 label_first = &statement->label;
8981 label_last->next = &statement->label;
8983 label_last = &statement->label;
8990 * Parse an if statement.
8992 static statement_t *parse_if(void)
8996 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8997 statement->base.source_position = token.source_position;
8999 PUSH_PARENT(statement);
9002 add_anchor_token(')');
9003 statement->ifs.condition = parse_expression();
9004 rem_anchor_token(')');
9007 add_anchor_token(T_else);
9008 statement->ifs.true_statement = parse_statement();
9009 rem_anchor_token(T_else);
9011 if (token.type == T_else) {
9013 statement->ifs.false_statement = parse_statement();
9020 return create_invalid_statement();
9024 * Check that all enums are handled in a switch.
9026 * @param statement the switch statement to check
9028 static void check_enum_cases(const switch_statement_t *statement) {
9029 const type_t *type = skip_typeref(statement->expression->base.type);
9030 if (! is_type_enum(type))
9032 const enum_type_t *enumt = &type->enumt;
9034 /* if we have a default, no warnings */
9035 if (statement->default_label != NULL)
9038 /* FIXME: calculation of value should be done while parsing */
9039 const declaration_t *declaration;
9040 long last_value = -1;
9041 for (declaration = enumt->declaration->next;
9042 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9043 declaration = declaration->next) {
9044 const expression_t *expression = declaration->init.enum_value;
9045 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9047 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9048 if (l->expression == NULL)
9050 if (l->first_case <= value && value <= l->last_case) {
9056 warningf(&statement->base.source_position,
9057 "enumeration value '%Y' not handled in switch", declaration->symbol);
9064 * Parse a switch statement.
9066 static statement_t *parse_switch(void)
9070 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9071 statement->base.source_position = token.source_position;
9073 PUSH_PARENT(statement);
9076 add_anchor_token(')');
9077 expression_t *const expr = parse_expression();
9078 type_t * type = skip_typeref(expr->base.type);
9079 if (is_type_integer(type)) {
9080 type = promote_integer(type);
9081 if (warning.traditional) {
9082 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9083 warningf(&expr->base.source_position,
9084 "'%T' switch expression not converted to '%T' in ISO C",
9088 } else if (is_type_valid(type)) {
9089 errorf(&expr->base.source_position,
9090 "switch quantity is not an integer, but '%T'", type);
9091 type = type_error_type;
9093 statement->switchs.expression = create_implicit_cast(expr, type);
9095 rem_anchor_token(')');
9097 switch_statement_t *rem = current_switch;
9098 current_switch = &statement->switchs;
9099 statement->switchs.body = parse_statement();
9100 current_switch = rem;
9102 if (warning.switch_default &&
9103 statement->switchs.default_label == NULL) {
9104 warningf(&statement->base.source_position, "switch has no default case");
9106 if (warning.switch_enum)
9107 check_enum_cases(&statement->switchs);
9113 return create_invalid_statement();
9116 static statement_t *parse_loop_body(statement_t *const loop)
9118 statement_t *const rem = current_loop;
9119 current_loop = loop;
9121 statement_t *const body = parse_statement();
9128 * Parse a while statement.
9130 static statement_t *parse_while(void)
9134 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9135 statement->base.source_position = token.source_position;
9137 PUSH_PARENT(statement);
9140 add_anchor_token(')');
9141 statement->whiles.condition = parse_expression();
9142 rem_anchor_token(')');
9145 statement->whiles.body = parse_loop_body(statement);
9151 return create_invalid_statement();
9155 * Parse a do statement.
9157 static statement_t *parse_do(void)
9161 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9162 statement->base.source_position = token.source_position;
9164 PUSH_PARENT(statement)
9166 add_anchor_token(T_while);
9167 statement->do_while.body = parse_loop_body(statement);
9168 rem_anchor_token(T_while);
9172 add_anchor_token(')');
9173 statement->do_while.condition = parse_expression();
9174 rem_anchor_token(')');
9182 return create_invalid_statement();
9186 * Parse a for statement.
9188 static statement_t *parse_for(void)
9192 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9193 statement->base.source_position = token.source_position;
9195 PUSH_PARENT(statement);
9197 size_t const top = environment_top();
9198 scope_push(&statement->fors.scope);
9201 add_anchor_token(')');
9203 if (token.type != ';') {
9204 if (is_declaration_specifier(&token, false)) {
9205 parse_declaration(record_declaration);
9207 add_anchor_token(';');
9208 expression_t *const init = parse_expression();
9209 statement->fors.initialisation = init;
9210 if (warning.unused_value && !expression_has_effect(init)) {
9211 warningf(&init->base.source_position,
9212 "initialisation of 'for'-statement has no effect");
9214 rem_anchor_token(';');
9221 if (token.type != ';') {
9222 add_anchor_token(';');
9223 statement->fors.condition = parse_expression();
9224 rem_anchor_token(';');
9227 if (token.type != ')') {
9228 expression_t *const step = parse_expression();
9229 statement->fors.step = step;
9230 if (warning.unused_value && !expression_has_effect(step)) {
9231 warningf(&step->base.source_position,
9232 "step of 'for'-statement has no effect");
9235 rem_anchor_token(')');
9237 statement->fors.body = parse_loop_body(statement);
9239 assert(scope == &statement->fors.scope);
9241 environment_pop_to(top);
9248 rem_anchor_token(')');
9249 assert(scope == &statement->fors.scope);
9251 environment_pop_to(top);
9253 return create_invalid_statement();
9257 * Parse a goto statement.
9259 static statement_t *parse_goto(void)
9261 source_position_t source_position = token.source_position;
9264 statement_t *statement;
9265 if (GNU_MODE && token.type == '*') {
9267 expression_t *expression = parse_expression();
9269 /* Argh: although documentation say the expression must be of type void *,
9270 * gcc excepts anything that can be casted into void * without error */
9271 type_t *type = expression->base.type;
9273 if (type != type_error_type) {
9274 if (!is_type_pointer(type) && !is_type_integer(type)) {
9275 errorf(&source_position, "cannot convert to a pointer type");
9276 } else if (type != type_void_ptr) {
9277 warningf(&source_position,
9278 "type of computed goto expression should be 'void*' not '%T'", type);
9280 expression = create_implicit_cast(expression, type_void_ptr);
9283 statement = allocate_statement_zero(STATEMENT_GOTO);
9284 statement->base.source_position = source_position;
9285 statement->gotos.expression = expression;
9287 if (token.type != T_IDENTIFIER) {
9289 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9291 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9295 symbol_t *symbol = token.v.symbol;
9298 statement = allocate_statement_zero(STATEMENT_GOTO);
9299 statement->base.source_position = source_position;
9300 statement->gotos.label = get_label(symbol);
9302 if (statement->gotos.label->parent_scope->depth < current_function->scope.depth) {
9303 statement->gotos.outer_fkt_jmp = true;
9307 /* remember the goto's in a list for later checking */
9308 if (goto_last == NULL) {
9309 goto_first = &statement->gotos;
9311 goto_last->next = &statement->gotos;
9313 goto_last = &statement->gotos;
9319 return create_invalid_statement();
9323 * Parse a continue statement.
9325 static statement_t *parse_continue(void)
9327 if (current_loop == NULL) {
9328 errorf(HERE, "continue statement not within loop");
9331 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9332 statement->base.source_position = token.source_position;
9342 * Parse a break statement.
9344 static statement_t *parse_break(void)
9346 if (current_switch == NULL && current_loop == NULL) {
9347 errorf(HERE, "break statement not within loop or switch");
9350 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9351 statement->base.source_position = token.source_position;
9361 * Parse a __leave statement.
9363 static statement_t *parse_leave_statement(void)
9365 if (current_try == NULL) {
9366 errorf(HERE, "__leave statement not within __try");
9369 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9370 statement->base.source_position = token.source_position;
9380 * Check if a given declaration represents a local variable.
9382 static bool is_local_var_declaration(const declaration_t *declaration)
9384 switch ((storage_class_tag_t) declaration->storage_class) {
9385 case STORAGE_CLASS_AUTO:
9386 case STORAGE_CLASS_REGISTER: {
9387 const type_t *type = skip_typeref(declaration->type);
9388 if (is_type_function(type)) {
9400 * Check if a given declaration represents a variable.
9402 static bool is_var_declaration(const declaration_t *declaration)
9404 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9407 const type_t *type = skip_typeref(declaration->type);
9408 return !is_type_function(type);
9412 * Check if a given expression represents a local variable.
9414 static bool is_local_variable(const expression_t *expression)
9416 if (expression->base.kind != EXPR_REFERENCE) {
9419 const declaration_t *declaration = expression->reference.declaration;
9420 return is_local_var_declaration(declaration);
9424 * Check if a given expression represents a local variable and
9425 * return its declaration then, else return NULL.
9427 declaration_t *expr_is_variable(const expression_t *expression)
9429 if (expression->base.kind != EXPR_REFERENCE) {
9432 declaration_t *declaration = expression->reference.declaration;
9433 if (is_var_declaration(declaration))
9439 * Parse a return statement.
9441 static statement_t *parse_return(void)
9443 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9444 statement->base.source_position = token.source_position;
9448 expression_t *return_value = NULL;
9449 if (token.type != ';') {
9450 return_value = parse_expression();
9453 const type_t *const func_type = current_function->type;
9454 assert(is_type_function(func_type));
9455 type_t *const return_type = skip_typeref(func_type->function.return_type);
9457 if (return_value != NULL) {
9458 type_t *return_value_type = skip_typeref(return_value->base.type);
9460 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9461 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9462 warningf(&statement->base.source_position,
9463 "'return' with a value, in function returning void");
9464 return_value = NULL;
9466 assign_error_t error = semantic_assign(return_type, return_value);
9467 report_assign_error(error, return_type, return_value, "'return'",
9468 &statement->base.source_position);
9469 return_value = create_implicit_cast(return_value, return_type);
9471 /* check for returning address of a local var */
9472 if (return_value != NULL &&
9473 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9474 const expression_t *expression = return_value->unary.value;
9475 if (is_local_variable(expression)) {
9476 warningf(&statement->base.source_position,
9477 "function returns address of local variable");
9481 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9482 warningf(&statement->base.source_position,
9483 "'return' without value, in function returning non-void");
9486 statement->returns.value = return_value;
9495 * Parse a declaration statement.
9497 static statement_t *parse_declaration_statement(void)
9499 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9501 statement->base.source_position = token.source_position;
9503 declaration_t *before = last_declaration;
9505 parse_external_declaration();
9507 parse_declaration(record_declaration);
9509 if (before == NULL) {
9510 statement->declaration.declarations_begin = scope->declarations;
9512 statement->declaration.declarations_begin = before->next;
9514 statement->declaration.declarations_end = last_declaration;
9520 * Parse an expression statement, ie. expr ';'.
9522 static statement_t *parse_expression_statement(void)
9524 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9526 statement->base.source_position = token.source_position;
9527 expression_t *const expr = parse_expression();
9528 statement->expression.expression = expr;
9537 * Parse a microsoft __try { } __finally { } or
9538 * __try{ } __except() { }
9540 static statement_t *parse_ms_try_statment(void)
9542 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9543 statement->base.source_position = token.source_position;
9546 PUSH_PARENT(statement);
9548 ms_try_statement_t *rem = current_try;
9549 current_try = &statement->ms_try;
9550 statement->ms_try.try_statement = parse_compound_statement(false);
9555 if (token.type == T___except) {
9558 add_anchor_token(')');
9559 expression_t *const expr = parse_expression();
9560 type_t * type = skip_typeref(expr->base.type);
9561 if (is_type_integer(type)) {
9562 type = promote_integer(type);
9563 } else if (is_type_valid(type)) {
9564 errorf(&expr->base.source_position,
9565 "__expect expression is not an integer, but '%T'", type);
9566 type = type_error_type;
9568 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9569 rem_anchor_token(')');
9571 statement->ms_try.final_statement = parse_compound_statement(false);
9572 } else if (token.type == T__finally) {
9574 statement->ms_try.final_statement = parse_compound_statement(false);
9576 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9577 return create_invalid_statement();
9581 return create_invalid_statement();
9584 static statement_t *parse_empty_statement(void)
9586 if (warning.empty_statement) {
9587 warningf(HERE, "statement is empty");
9589 statement_t *const statement = create_empty_statement();
9594 static statement_t *parse_local_label_declaration(void) {
9595 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9596 statement->base.source_position = token.source_position;
9600 declaration_t *begin = NULL, *end = NULL;
9603 if (token.type != T_IDENTIFIER) {
9604 parse_error_expected("while parsing local label declaration",
9605 T_IDENTIFIER, NULL);
9608 symbol_t *symbol = token.v.symbol;
9609 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9610 if (declaration != NULL) {
9611 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9612 symbol, &declaration->source_position);
9614 declaration = allocate_declaration_zero();
9615 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9616 declaration->source_position = token.source_position;
9617 declaration->symbol = symbol;
9618 declaration->parent_scope = scope;
9619 declaration->init.statement = NULL;
9622 end->next = declaration;
9625 begin = declaration;
9627 local_label_push(declaration);
9631 if (token.type != ',')
9637 statement->declaration.declarations_begin = begin;
9638 statement->declaration.declarations_end = end;
9643 * Parse a statement.
9644 * There's also parse_statement() which additionally checks for
9645 * "statement has no effect" warnings
9647 static statement_t *intern_parse_statement(void)
9649 statement_t *statement = NULL;
9651 /* declaration or statement */
9652 add_anchor_token(';');
9653 switch (token.type) {
9654 case T_IDENTIFIER: {
9655 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9656 if (la1_type == ':') {
9657 statement = parse_label_statement();
9658 } else if (is_typedef_symbol(token.v.symbol)) {
9659 statement = parse_declaration_statement();
9660 } else switch (la1_type) {
9662 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9663 goto expression_statment;
9668 statement = parse_declaration_statement();
9672 expression_statment:
9673 statement = parse_expression_statement();
9679 case T___extension__:
9680 /* This can be a prefix to a declaration or an expression statement.
9681 * We simply eat it now and parse the rest with tail recursion. */
9684 } while (token.type == T___extension__);
9685 bool old_gcc_extension = in_gcc_extension;
9686 in_gcc_extension = true;
9687 statement = parse_statement();
9688 in_gcc_extension = old_gcc_extension;
9692 statement = parse_declaration_statement();
9696 statement = parse_local_label_declaration();
9699 case ';': statement = parse_empty_statement(); break;
9700 case '{': statement = parse_compound_statement(false); break;
9701 case T___leave: statement = parse_leave_statement(); break;
9702 case T___try: statement = parse_ms_try_statment(); break;
9703 case T_asm: statement = parse_asm_statement(); break;
9704 case T_break: statement = parse_break(); break;
9705 case T_case: statement = parse_case_statement(); break;
9706 case T_continue: statement = parse_continue(); break;
9707 case T_default: statement = parse_default_statement(); break;
9708 case T_do: statement = parse_do(); break;
9709 case T_for: statement = parse_for(); break;
9710 case T_goto: statement = parse_goto(); break;
9711 case T_if: statement = parse_if (); break;
9712 case T_return: statement = parse_return(); break;
9713 case T_switch: statement = parse_switch(); break;
9714 case T_while: statement = parse_while(); break;
9724 case T_CHARACTER_CONSTANT:
9725 case T_FLOATINGPOINT:
9729 case T_STRING_LITERAL:
9730 case T_WIDE_CHARACTER_CONSTANT:
9731 case T_WIDE_STRING_LITERAL:
9732 case T___FUNCDNAME__:
9734 case T___FUNCTION__:
9735 case T___PRETTY_FUNCTION__:
9736 case T___builtin_alloca:
9737 case T___builtin_classify_type:
9738 case T___builtin_constant_p:
9739 case T___builtin_expect:
9740 case T___builtin_huge_val:
9741 case T___builtin_isgreater:
9742 case T___builtin_isgreaterequal:
9743 case T___builtin_isless:
9744 case T___builtin_islessequal:
9745 case T___builtin_islessgreater:
9746 case T___builtin_isunordered:
9747 case T___builtin_nan:
9748 case T___builtin_nand:
9749 case T___builtin_nanf:
9750 case T___builtin_offsetof:
9751 case T___builtin_prefetch:
9752 case T___builtin_va_arg:
9753 case T___builtin_va_end:
9754 case T___builtin_va_start:
9758 statement = parse_expression_statement();
9762 errorf(HERE, "unexpected token %K while parsing statement", &token);
9763 statement = create_invalid_statement();
9768 rem_anchor_token(';');
9770 assert(statement != NULL
9771 && statement->base.source_position.input_name != NULL);
9777 * parse a statement and emits "statement has no effect" warning if needed
9778 * (This is really a wrapper around intern_parse_statement with check for 1
9779 * single warning. It is needed, because for statement expressions we have
9780 * to avoid the warning on the last statement)
9782 static statement_t *parse_statement(void)
9784 statement_t *statement = intern_parse_statement();
9786 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9787 expression_t *expression = statement->expression.expression;
9788 if (!expression_has_effect(expression)) {
9789 warningf(&expression->base.source_position,
9790 "statement has no effect");
9798 * Parse a compound statement.
9800 static statement_t *parse_compound_statement(bool inside_expression_statement)
9802 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9803 statement->base.source_position = token.source_position;
9805 PUSH_PARENT(statement);
9808 add_anchor_token('}');
9810 size_t const top = environment_top();
9811 size_t const top_local = local_label_top();
9812 scope_push(&statement->compound.scope);
9814 statement_t **anchor = &statement->compound.statements;
9815 bool only_decls_so_far = true;
9816 while (token.type != '}' && token.type != T_EOF) {
9817 statement_t *sub_statement = intern_parse_statement();
9818 if (is_invalid_statement(sub_statement)) {
9819 /* an error occurred. if we are at an anchor, return */
9825 if (warning.declaration_after_statement) {
9826 if (sub_statement->kind != STATEMENT_DECLARATION) {
9827 only_decls_so_far = false;
9828 } else if (!only_decls_so_far) {
9829 warningf(&sub_statement->base.source_position,
9830 "ISO C90 forbids mixed declarations and code");
9834 *anchor = sub_statement;
9836 while (sub_statement->base.next != NULL)
9837 sub_statement = sub_statement->base.next;
9839 anchor = &sub_statement->base.next;
9842 if (token.type == '}') {
9845 errorf(&statement->base.source_position,
9846 "end of file while looking for closing '}'");
9849 /* look over all statements again to produce no effect warnings */
9850 if (warning.unused_value) {
9851 statement_t *sub_statement = statement->compound.statements;
9852 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9853 if (sub_statement->kind != STATEMENT_EXPRESSION)
9855 /* don't emit a warning for the last expression in an expression
9856 * statement as it has always an effect */
9857 if (inside_expression_statement && sub_statement->base.next == NULL)
9860 expression_t *expression = sub_statement->expression.expression;
9861 if (!expression_has_effect(expression)) {
9862 warningf(&expression->base.source_position,
9863 "statement has no effect");
9869 rem_anchor_token('}');
9870 assert(scope == &statement->compound.scope);
9872 environment_pop_to(top);
9873 local_label_pop_to(top_local);
9880 * Initialize builtin types.
9882 static void initialize_builtin_types(void)
9884 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9885 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9886 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9887 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9888 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9889 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9890 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9891 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9893 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9894 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9895 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9896 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9898 /* const version of wchar_t */
9899 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9900 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9901 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9903 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9907 * Check for unused global static functions and variables
9909 static void check_unused_globals(void)
9911 if (!warning.unused_function && !warning.unused_variable)
9914 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9916 decl->modifiers & DM_UNUSED ||
9917 decl->modifiers & DM_USED ||
9918 decl->storage_class != STORAGE_CLASS_STATIC)
9921 type_t *const type = decl->type;
9923 if (is_type_function(skip_typeref(type))) {
9924 if (!warning.unused_function || decl->is_inline)
9927 s = (decl->init.statement != NULL ? "defined" : "declared");
9929 if (!warning.unused_variable)
9935 warningf(&decl->source_position, "'%#T' %s but not used",
9936 type, decl->symbol, s);
9940 static void parse_global_asm(void)
9945 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9946 statement->base.source_position = token.source_position;
9947 statement->asms.asm_text = parse_string_literals();
9948 statement->base.next = unit->global_asm;
9949 unit->global_asm = statement;
9958 * Parse a translation unit.
9960 static void parse_translation_unit(void)
9964 bool anchor_leak = false;
9965 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9966 unsigned char count = token_anchor_set[i];
9968 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9972 if (in_gcc_extension) {
9973 errorf(HERE, "Leaked __extension__");
9981 switch (token.type) {
9984 case T___extension__:
9985 parse_external_declaration();
9996 /* TODO error in strict mode */
9997 warningf(HERE, "stray ';' outside of function");
10002 errorf(HERE, "stray %K outside of function", &token);
10003 if (token.type == '(' || token.type == '{' || token.type == '[')
10004 eat_until_matching_token(token.type);
10014 * @return the translation unit or NULL if errors occurred.
10016 void start_parsing(void)
10018 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10019 label_stack = NEW_ARR_F(stack_entry_t, 0);
10020 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10021 diagnostic_count = 0;
10025 type_set_output(stderr);
10026 ast_set_output(stderr);
10028 assert(unit == NULL);
10029 unit = allocate_ast_zero(sizeof(unit[0]));
10031 assert(global_scope == NULL);
10032 global_scope = &unit->scope;
10034 assert(scope == NULL);
10035 scope_push(&unit->scope);
10037 initialize_builtin_types();
10040 translation_unit_t *finish_parsing(void)
10042 /* do NOT use scope_pop() here, this will crash, will it by hand */
10043 assert(scope == &unit->scope);
10045 last_declaration = NULL;
10047 assert(global_scope == &unit->scope);
10048 check_unused_globals();
10049 global_scope = NULL;
10051 DEL_ARR_F(environment_stack);
10052 DEL_ARR_F(label_stack);
10053 DEL_ARR_F(local_label_stack);
10055 translation_unit_t *result = unit;
10062 lookahead_bufpos = 0;
10063 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10066 parse_translation_unit();
10070 * Initialize the parser.
10072 void init_parser(void)
10074 sym_anonymous = symbol_table_insert("<anonymous>");
10076 if (c_mode & _MS) {
10077 /* add predefined symbols for extended-decl-modifier */
10078 sym_align = symbol_table_insert("align");
10079 sym_allocate = symbol_table_insert("allocate");
10080 sym_dllimport = symbol_table_insert("dllimport");
10081 sym_dllexport = symbol_table_insert("dllexport");
10082 sym_naked = symbol_table_insert("naked");
10083 sym_noinline = symbol_table_insert("noinline");
10084 sym_noreturn = symbol_table_insert("noreturn");
10085 sym_nothrow = symbol_table_insert("nothrow");
10086 sym_novtable = symbol_table_insert("novtable");
10087 sym_property = symbol_table_insert("property");
10088 sym_get = symbol_table_insert("get");
10089 sym_put = symbol_table_insert("put");
10090 sym_selectany = symbol_table_insert("selectany");
10091 sym_thread = symbol_table_insert("thread");
10092 sym_uuid = symbol_table_insert("uuid");
10093 sym_deprecated = symbol_table_insert("deprecated");
10094 sym_restrict = symbol_table_insert("restrict");
10095 sym_noalias = symbol_table_insert("noalias");
10097 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10099 init_expression_parsers();
10100 obstack_init(&temp_obst);
10102 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10103 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10107 * Terminate the parser.
10109 void exit_parser(void)
10111 obstack_free(&temp_obst, NULL);