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 **anchor;
844 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
846 assert(iter != NULL);
847 /* replace an entry? */
848 if (iter->namespc == namespc)
852 /* Because of scopes and appending other namespaces to the end of
853 * the list, this must hold. */
854 assert((old_declaration != NULL ? old_declaration->symbol_next : NULL) == iter->symbol_next);
855 *anchor = old_declaration;
858 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
862 * Pop all entries from the environment stack until the new_top
865 * @param new_top the new stack top
867 static void environment_pop_to(size_t new_top)
869 stack_pop_to(&environment_stack, new_top);
873 * Pop all entries from the global label stack until the new_top
876 * @param new_top the new stack top
878 static void label_pop_to(size_t new_top)
880 stack_pop_to(&label_stack, new_top);
884 * Pop all entries from the local label stack until the new_top
887 * @param new_top the new stack top
889 static void local_label_pop_to(size_t new_top)
891 stack_pop_to(&local_label_stack, new_top);
895 static int get_akind_rank(atomic_type_kind_t akind)
900 static int get_rank(const type_t *type)
902 assert(!is_typeref(type));
903 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
904 * and esp. footnote 108). However we can't fold constants (yet), so we
905 * can't decide whether unsigned int is possible, while int always works.
906 * (unsigned int would be preferable when possible... for stuff like
907 * struct { enum { ... } bla : 4; } ) */
908 if (type->kind == TYPE_ENUM)
909 return get_akind_rank(ATOMIC_TYPE_INT);
911 assert(type->kind == TYPE_ATOMIC);
912 return get_akind_rank(type->atomic.akind);
915 static type_t *promote_integer(type_t *type)
917 if (type->kind == TYPE_BITFIELD)
918 type = type->bitfield.base_type;
920 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
927 * Create a cast expression.
929 * @param expression the expression to cast
930 * @param dest_type the destination type
932 static expression_t *create_cast_expression(expression_t *expression,
935 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
937 cast->unary.value = expression;
938 cast->base.type = dest_type;
944 * Check if a given expression represents the 0 pointer constant.
946 static bool is_null_pointer_constant(const expression_t *expression)
948 /* skip void* cast */
949 if (expression->kind == EXPR_UNARY_CAST
950 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
951 expression = expression->unary.value;
954 /* TODO: not correct yet, should be any constant integer expression
955 * which evaluates to 0 */
956 if (expression->kind != EXPR_CONST)
959 type_t *const type = skip_typeref(expression->base.type);
960 if (!is_type_integer(type))
963 return expression->conste.v.int_value == 0;
967 * Create an implicit cast expression.
969 * @param expression the expression to cast
970 * @param dest_type the destination type
972 static expression_t *create_implicit_cast(expression_t *expression,
975 type_t *const source_type = expression->base.type;
977 if (source_type == dest_type)
980 return create_cast_expression(expression, dest_type);
983 typedef enum assign_error_t {
985 ASSIGN_ERROR_INCOMPATIBLE,
986 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
987 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
988 ASSIGN_WARNING_POINTER_FROM_INT,
989 ASSIGN_WARNING_INT_FROM_POINTER
992 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
993 const expression_t *const right,
995 const source_position_t *source_position)
997 type_t *const orig_type_right = right->base.type;
998 type_t *const type_left = skip_typeref(orig_type_left);
999 type_t *const type_right = skip_typeref(orig_type_right);
1002 case ASSIGN_SUCCESS:
1004 case ASSIGN_ERROR_INCOMPATIBLE:
1005 errorf(source_position,
1006 "destination type '%T' in %s is incompatible with type '%T'",
1007 orig_type_left, context, orig_type_right);
1010 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1011 type_t *points_to_left
1012 = skip_typeref(type_left->pointer.points_to);
1013 type_t *points_to_right
1014 = skip_typeref(type_right->pointer.points_to);
1016 /* the left type has all qualifiers from the right type */
1017 unsigned missing_qualifiers
1018 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1019 warningf(source_position,
1020 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1021 orig_type_left, context, orig_type_right, missing_qualifiers);
1025 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1026 warningf(source_position,
1027 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1028 orig_type_left, context, right, orig_type_right);
1031 case ASSIGN_WARNING_POINTER_FROM_INT:
1032 warningf(source_position,
1033 "%s makes pointer '%T' from integer '%T' without a cast",
1034 context, orig_type_left, orig_type_right);
1037 case ASSIGN_WARNING_INT_FROM_POINTER:
1038 warningf(source_position,
1039 "%s makes integer '%T' from pointer '%T' without a cast",
1040 context, orig_type_left, orig_type_right);
1044 panic("invalid error value");
1048 /** Implements the rules from § 6.5.16.1 */
1049 static assign_error_t semantic_assign(type_t *orig_type_left,
1050 const expression_t *const right)
1052 type_t *const orig_type_right = right->base.type;
1053 type_t *const type_left = skip_typeref(orig_type_left);
1054 type_t *const type_right = skip_typeref(orig_type_right);
1056 if (is_type_pointer(type_left)) {
1057 if (is_null_pointer_constant(right)) {
1058 return ASSIGN_SUCCESS;
1059 } else if (is_type_pointer(type_right)) {
1060 type_t *points_to_left
1061 = skip_typeref(type_left->pointer.points_to);
1062 type_t *points_to_right
1063 = skip_typeref(type_right->pointer.points_to);
1064 assign_error_t res = ASSIGN_SUCCESS;
1066 /* the left type has all qualifiers from the right type */
1067 unsigned missing_qualifiers
1068 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1069 if (missing_qualifiers != 0) {
1070 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1073 points_to_left = get_unqualified_type(points_to_left);
1074 points_to_right = get_unqualified_type(points_to_right);
1076 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1077 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1081 if (!types_compatible(points_to_left, points_to_right)) {
1082 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1086 } else if (is_type_integer(type_right)) {
1087 return ASSIGN_WARNING_POINTER_FROM_INT;
1089 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1090 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1091 && is_type_pointer(type_right))) {
1092 return ASSIGN_SUCCESS;
1093 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1094 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1095 type_t *const unqual_type_left = get_unqualified_type(type_left);
1096 type_t *const unqual_type_right = get_unqualified_type(type_right);
1097 if (types_compatible(unqual_type_left, unqual_type_right)) {
1098 return ASSIGN_SUCCESS;
1100 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1101 return ASSIGN_WARNING_INT_FROM_POINTER;
1104 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1105 return ASSIGN_SUCCESS;
1107 return ASSIGN_ERROR_INCOMPATIBLE;
1110 static expression_t *parse_constant_expression(void)
1112 /* start parsing at precedence 7 (conditional expression) */
1113 expression_t *result = parse_sub_expression(7);
1115 if (!is_constant_expression(result)) {
1116 errorf(&result->base.source_position,
1117 "expression '%E' is not constant\n", result);
1123 static expression_t *parse_assignment_expression(void)
1125 /* start parsing at precedence 2 (assignment expression) */
1126 return parse_sub_expression(2);
1129 static type_t *make_global_typedef(const char *name, type_t *type)
1131 symbol_t *const symbol = symbol_table_insert(name);
1133 declaration_t *const declaration = allocate_declaration_zero();
1134 declaration->namespc = NAMESPACE_NORMAL;
1135 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1136 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1137 declaration->type = type;
1138 declaration->symbol = symbol;
1139 declaration->source_position = builtin_source_position;
1140 declaration->implicit = true;
1142 record_declaration(declaration, false);
1144 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1145 typedef_type->typedeft.declaration = declaration;
1147 return typedef_type;
1150 static string_t parse_string_literals(void)
1152 assert(token.type == T_STRING_LITERAL);
1153 string_t result = token.v.string;
1157 while (token.type == T_STRING_LITERAL) {
1158 result = concat_strings(&result, &token.v.string);
1165 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1166 [GNU_AK_CONST] = "const",
1167 [GNU_AK_VOLATILE] = "volatile",
1168 [GNU_AK_CDECL] = "cdecl",
1169 [GNU_AK_STDCALL] = "stdcall",
1170 [GNU_AK_FASTCALL] = "fastcall",
1171 [GNU_AK_DEPRECATED] = "deprecated",
1172 [GNU_AK_NOINLINE] = "noinline",
1173 [GNU_AK_NORETURN] = "noreturn",
1174 [GNU_AK_NAKED] = "naked",
1175 [GNU_AK_PURE] = "pure",
1176 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1177 [GNU_AK_MALLOC] = "malloc",
1178 [GNU_AK_WEAK] = "weak",
1179 [GNU_AK_CONSTRUCTOR] = "constructor",
1180 [GNU_AK_DESTRUCTOR] = "destructor",
1181 [GNU_AK_NOTHROW] = "nothrow",
1182 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1183 [GNU_AK_COMMON] = "common",
1184 [GNU_AK_NOCOMMON] = "nocommon",
1185 [GNU_AK_PACKED] = "packed",
1186 [GNU_AK_SHARED] = "shared",
1187 [GNU_AK_NOTSHARED] = "notshared",
1188 [GNU_AK_USED] = "used",
1189 [GNU_AK_UNUSED] = "unused",
1190 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1191 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1192 [GNU_AK_LONGCALL] = "longcall",
1193 [GNU_AK_SHORTCALL] = "shortcall",
1194 [GNU_AK_LONG_CALL] = "long_call",
1195 [GNU_AK_SHORT_CALL] = "short_call",
1196 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1197 [GNU_AK_INTERRUPT] = "interrupt",
1198 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1199 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1200 [GNU_AK_NESTING] = "nesting",
1201 [GNU_AK_NEAR] = "near",
1202 [GNU_AK_FAR] = "far",
1203 [GNU_AK_SIGNAL] = "signal",
1204 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1205 [GNU_AK_TINY_DATA] = "tiny_data",
1206 [GNU_AK_SAVEALL] = "saveall",
1207 [GNU_AK_FLATTEN] = "flatten",
1208 [GNU_AK_SSEREGPARM] = "sseregparm",
1209 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1210 [GNU_AK_RETURN_TWICE] = "return_twice",
1211 [GNU_AK_MAY_ALIAS] = "may_alias",
1212 [GNU_AK_MS_STRUCT] = "ms_struct",
1213 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1214 [GNU_AK_DLLIMPORT] = "dllimport",
1215 [GNU_AK_DLLEXPORT] = "dllexport",
1216 [GNU_AK_ALIGNED] = "aligned",
1217 [GNU_AK_ALIAS] = "alias",
1218 [GNU_AK_SECTION] = "section",
1219 [GNU_AK_FORMAT] = "format",
1220 [GNU_AK_FORMAT_ARG] = "format_arg",
1221 [GNU_AK_WEAKREF] = "weakref",
1222 [GNU_AK_NONNULL] = "nonnull",
1223 [GNU_AK_TLS_MODEL] = "tls_model",
1224 [GNU_AK_VISIBILITY] = "visibility",
1225 [GNU_AK_REGPARM] = "regparm",
1226 [GNU_AK_MODE] = "mode",
1227 [GNU_AK_MODEL] = "model",
1228 [GNU_AK_TRAP_EXIT] = "trap_exit",
1229 [GNU_AK_SP_SWITCH] = "sp_switch",
1230 [GNU_AK_SENTINEL] = "sentinel"
1234 * compare two string, ignoring double underscores on the second.
1236 static int strcmp_underscore(const char *s1, const char *s2)
1238 if (s2[0] == '_' && s2[1] == '_') {
1239 size_t len2 = strlen(s2);
1240 size_t len1 = strlen(s1);
1241 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1242 return strncmp(s1, s2+2, len2-4);
1246 return strcmp(s1, s2);
1250 * Allocate a new gnu temporal attribute.
1252 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1254 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1255 attribute->kind = kind;
1256 attribute->next = NULL;
1257 attribute->invalid = false;
1258 attribute->have_arguments = false;
1264 * parse one constant expression argument.
1266 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1268 expression_t *expression;
1269 add_anchor_token(')');
1270 expression = parse_constant_expression();
1271 rem_anchor_token(')');
1273 attribute->u.argument = fold_constant(expression);
1276 attribute->invalid = true;
1280 * parse a list of constant expressions arguments.
1282 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1284 argument_list_t **list = &attribute->u.arguments;
1285 argument_list_t *entry;
1286 expression_t *expression;
1287 add_anchor_token(')');
1288 add_anchor_token(',');
1290 expression = parse_constant_expression();
1291 entry = obstack_alloc(&temp_obst, sizeof(entry));
1292 entry->argument = fold_constant(expression);
1295 list = &entry->next;
1296 if (token.type != ',')
1300 rem_anchor_token(',');
1301 rem_anchor_token(')');
1305 attribute->invalid = true;
1309 * parse one string literal argument.
1311 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1314 add_anchor_token('(');
1315 if (token.type != T_STRING_LITERAL) {
1316 parse_error_expected("while parsing attribute directive",
1317 T_STRING_LITERAL, NULL);
1320 *string = parse_string_literals();
1321 rem_anchor_token('(');
1325 attribute->invalid = true;
1329 * parse one tls model.
1331 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1333 static const char *const tls_models[] = {
1339 string_t string = { NULL, 0 };
1340 parse_gnu_attribute_string_arg(attribute, &string);
1341 if (string.begin != NULL) {
1342 for(size_t i = 0; i < 4; ++i) {
1343 if (strcmp(tls_models[i], string.begin) == 0) {
1344 attribute->u.value = i;
1348 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1350 attribute->invalid = true;
1354 * parse one tls model.
1356 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1358 static const char *const visibilities[] = {
1364 string_t string = { NULL, 0 };
1365 parse_gnu_attribute_string_arg(attribute, &string);
1366 if (string.begin != NULL) {
1367 for(size_t i = 0; i < 4; ++i) {
1368 if (strcmp(visibilities[i], string.begin) == 0) {
1369 attribute->u.value = i;
1373 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1375 attribute->invalid = true;
1379 * parse one (code) model.
1381 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1383 static const char *const visibilities[] = {
1388 string_t string = { NULL, 0 };
1389 parse_gnu_attribute_string_arg(attribute, &string);
1390 if (string.begin != NULL) {
1391 for(int i = 0; i < 3; ++i) {
1392 if (strcmp(visibilities[i], string.begin) == 0) {
1393 attribute->u.value = i;
1397 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1399 attribute->invalid = true;
1402 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1404 /* TODO: find out what is allowed here... */
1406 /* at least: byte, word, pointer, list of machine modes
1407 * __XXX___ is interpreted as XXX */
1408 add_anchor_token(')');
1410 if (token.type != T_IDENTIFIER) {
1411 expect(T_IDENTIFIER);
1414 /* This isn't really correct, the backend should provide a list of machine
1415 * specific modes (according to gcc philosophy that is...) */
1416 const char *symbol_str = token.v.symbol->string;
1417 if (strcmp_underscore("QI", symbol_str) == 0 ||
1418 strcmp_underscore("byte", symbol_str) == 0) {
1419 attribute->u.akind = ATOMIC_TYPE_CHAR;
1420 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1421 attribute->u.akind = ATOMIC_TYPE_SHORT;
1422 } else if (strcmp_underscore("SI", symbol_str) == 0
1423 || strcmp_underscore("word", symbol_str) == 0
1424 || strcmp_underscore("pointer", symbol_str) == 0) {
1425 attribute->u.akind = ATOMIC_TYPE_INT;
1426 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1427 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1429 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1430 attribute->invalid = true;
1434 rem_anchor_token(')');
1438 attribute->invalid = true;
1442 * parse one interrupt argument.
1444 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1446 static const char *const interrupts[] = {
1453 string_t string = { NULL, 0 };
1454 parse_gnu_attribute_string_arg(attribute, &string);
1455 if (string.begin != NULL) {
1456 for(size_t i = 0; i < 5; ++i) {
1457 if (strcmp(interrupts[i], string.begin) == 0) {
1458 attribute->u.value = i;
1462 errorf(HERE, "'%s' is not an interrupt", string.begin);
1464 attribute->invalid = true;
1468 * parse ( identifier, const expression, const expression )
1470 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1472 static const char *const format_names[] = {
1480 if (token.type != T_IDENTIFIER) {
1481 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1484 const char *name = token.v.symbol->string;
1485 for(i = 0; i < 4; ++i) {
1486 if (strcmp_underscore(format_names[i], name) == 0)
1490 if (warning.attribute)
1491 warningf(HERE, "'%s' is an unrecognized format function type", name);
1496 add_anchor_token(')');
1497 add_anchor_token(',');
1498 parse_constant_expression();
1499 rem_anchor_token(',');
1500 rem_anchor_token(')');
1503 add_anchor_token(')');
1504 parse_constant_expression();
1505 rem_anchor_token(')');
1509 attribute->u.value = true;
1512 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1514 if (!attribute->have_arguments)
1517 /* should have no arguments */
1518 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1519 eat_until_matching_token('(');
1520 /* we have already consumed '(', so we stop before ')', eat it */
1522 attribute->invalid = true;
1526 * Parse one GNU attribute.
1528 * Note that attribute names can be specified WITH or WITHOUT
1529 * double underscores, ie const or __const__.
1531 * The following attributes are parsed without arguments
1556 * no_instrument_function
1557 * warn_unused_result
1574 * externally_visible
1582 * The following attributes are parsed with arguments
1583 * aligned( const expression )
1584 * alias( string literal )
1585 * section( string literal )
1586 * format( identifier, const expression, const expression )
1587 * format_arg( const expression )
1588 * tls_model( string literal )
1589 * visibility( string literal )
1590 * regparm( const expression )
1591 * model( string leteral )
1592 * trap_exit( const expression )
1593 * sp_switch( string literal )
1595 * The following attributes might have arguments
1596 * weak_ref( string literal )
1597 * non_null( const expression // ',' )
1598 * interrupt( string literal )
1599 * sentinel( constant expression )
1601 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1603 gnu_attribute_t *head = *attributes;
1604 gnu_attribute_t *last = *attributes;
1605 decl_modifiers_t modifiers = 0;
1606 gnu_attribute_t *attribute;
1608 eat(T___attribute__);
1612 if (token.type != ')') {
1613 /* find the end of the list */
1615 while (last->next != NULL)
1619 /* non-empty attribute list */
1622 if (token.type == T_const) {
1624 } else if (token.type == T_volatile) {
1626 } else if (token.type == T_cdecl) {
1627 /* __attribute__((cdecl)), WITH ms mode */
1629 } else if (token.type == T_IDENTIFIER) {
1630 const symbol_t *sym = token.v.symbol;
1633 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1640 for(i = 0; i < GNU_AK_LAST; ++i) {
1641 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1644 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1647 if (kind == GNU_AK_LAST) {
1648 if (warning.attribute)
1649 warningf(HERE, "'%s' attribute directive ignored", name);
1651 /* skip possible arguments */
1652 if (token.type == '(') {
1653 eat_until_matching_token(')');
1656 /* check for arguments */
1657 attribute = allocate_gnu_attribute(kind);
1658 if (token.type == '(') {
1660 if (token.type == ')') {
1661 /* empty args are allowed */
1664 attribute->have_arguments = true;
1669 case GNU_AK_VOLATILE:
1674 case GNU_AK_NOCOMMON:
1676 case GNU_AK_NOTSHARED:
1677 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1678 case GNU_AK_WARN_UNUSED_RESULT:
1679 case GNU_AK_LONGCALL:
1680 case GNU_AK_SHORTCALL:
1681 case GNU_AK_LONG_CALL:
1682 case GNU_AK_SHORT_CALL:
1683 case GNU_AK_FUNCTION_VECTOR:
1684 case GNU_AK_INTERRUPT_HANDLER:
1685 case GNU_AK_NMI_HANDLER:
1686 case GNU_AK_NESTING:
1690 case GNU_AK_EIGTHBIT_DATA:
1691 case GNU_AK_TINY_DATA:
1692 case GNU_AK_SAVEALL:
1693 case GNU_AK_FLATTEN:
1694 case GNU_AK_SSEREGPARM:
1695 case GNU_AK_EXTERNALLY_VISIBLE:
1696 case GNU_AK_RETURN_TWICE:
1697 case GNU_AK_MAY_ALIAS:
1698 case GNU_AK_MS_STRUCT:
1699 case GNU_AK_GCC_STRUCT:
1702 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1703 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1704 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1705 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1706 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1707 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1708 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1709 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1710 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1711 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1712 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1713 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1714 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1715 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1716 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1717 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1718 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1720 case GNU_AK_ALIGNED:
1721 /* __align__ may be used without an argument */
1722 if (attribute->have_arguments) {
1723 parse_gnu_attribute_const_arg(attribute);
1727 case GNU_AK_FORMAT_ARG:
1728 case GNU_AK_REGPARM:
1729 case GNU_AK_TRAP_EXIT:
1730 if (!attribute->have_arguments) {
1731 /* should have arguments */
1732 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1733 attribute->invalid = true;
1735 parse_gnu_attribute_const_arg(attribute);
1738 case GNU_AK_SECTION:
1739 case GNU_AK_SP_SWITCH:
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_string_arg(attribute, &attribute->u.string);
1748 if (!attribute->have_arguments) {
1749 /* should have arguments */
1750 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1751 attribute->invalid = true;
1753 parse_gnu_attribute_format_args(attribute);
1755 case GNU_AK_WEAKREF:
1756 /* may have one string argument */
1757 if (attribute->have_arguments)
1758 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1760 case GNU_AK_NONNULL:
1761 if (attribute->have_arguments)
1762 parse_gnu_attribute_const_arg_list(attribute);
1764 case GNU_AK_TLS_MODEL:
1765 if (!attribute->have_arguments) {
1766 /* should have arguments */
1767 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1769 parse_gnu_attribute_tls_model_arg(attribute);
1771 case GNU_AK_VISIBILITY:
1772 if (!attribute->have_arguments) {
1773 /* should have arguments */
1774 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1776 parse_gnu_attribute_visibility_arg(attribute);
1779 if (!attribute->have_arguments) {
1780 /* should have arguments */
1781 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1783 parse_gnu_attribute_model_arg(attribute);
1787 if (!attribute->have_arguments) {
1788 /* should have arguments */
1789 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1791 parse_gnu_attribute_mode_arg(attribute);
1794 case GNU_AK_INTERRUPT:
1795 /* may have one string argument */
1796 if (attribute->have_arguments)
1797 parse_gnu_attribute_interrupt_arg(attribute);
1799 case GNU_AK_SENTINEL:
1800 /* may have one string argument */
1801 if (attribute->have_arguments)
1802 parse_gnu_attribute_const_arg(attribute);
1805 /* already handled */
1809 check_no_argument(attribute, name);
1812 if (attribute != NULL) {
1814 last->next = attribute;
1817 head = last = attribute;
1821 if (token.type != ',')
1835 * Parse GNU attributes.
1837 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1839 decl_modifiers_t modifiers = 0;
1842 switch(token.type) {
1843 case T___attribute__:
1844 modifiers |= parse_gnu_attribute(attributes);
1850 if (token.type != T_STRING_LITERAL) {
1851 parse_error_expected("while parsing assembler attribute",
1852 T_STRING_LITERAL, NULL);
1853 eat_until_matching_token('(');
1856 parse_string_literals();
1861 case T_cdecl: modifiers |= DM_CDECL; break;
1862 case T__fastcall: modifiers |= DM_FASTCALL; break;
1863 case T__stdcall: modifiers |= DM_STDCALL; break;
1866 /* TODO record modifier */
1867 warningf(HERE, "Ignoring declaration modifier %K", &token);
1871 default: return modifiers;
1878 static designator_t *parse_designation(void)
1880 designator_t *result = NULL;
1881 designator_t *last = NULL;
1884 designator_t *designator;
1885 switch(token.type) {
1887 designator = allocate_ast_zero(sizeof(designator[0]));
1888 designator->source_position = token.source_position;
1890 add_anchor_token(']');
1891 designator->array_index = parse_constant_expression();
1892 rem_anchor_token(']');
1896 designator = allocate_ast_zero(sizeof(designator[0]));
1897 designator->source_position = token.source_position;
1899 if (token.type != T_IDENTIFIER) {
1900 parse_error_expected("while parsing designator",
1901 T_IDENTIFIER, NULL);
1904 designator->symbol = token.v.symbol;
1912 assert(designator != NULL);
1914 last->next = designator;
1916 result = designator;
1924 static initializer_t *initializer_from_string(array_type_t *type,
1925 const string_t *const string)
1927 /* TODO: check len vs. size of array type */
1930 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1931 initializer->string.string = *string;
1936 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1937 wide_string_t *const string)
1939 /* TODO: check len vs. size of array type */
1942 initializer_t *const initializer =
1943 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1944 initializer->wide_string.string = *string;
1950 * Build an initializer from a given expression.
1952 static initializer_t *initializer_from_expression(type_t *orig_type,
1953 expression_t *expression)
1955 /* TODO check that expression is a constant expression */
1957 /* § 6.7.8.14/15 char array may be initialized by string literals */
1958 type_t *type = skip_typeref(orig_type);
1959 type_t *expr_type_orig = expression->base.type;
1960 type_t *expr_type = skip_typeref(expr_type_orig);
1961 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1962 array_type_t *const array_type = &type->array;
1963 type_t *const element_type = skip_typeref(array_type->element_type);
1965 if (element_type->kind == TYPE_ATOMIC) {
1966 atomic_type_kind_t akind = element_type->atomic.akind;
1967 switch (expression->kind) {
1968 case EXPR_STRING_LITERAL:
1969 if (akind == ATOMIC_TYPE_CHAR
1970 || akind == ATOMIC_TYPE_SCHAR
1971 || akind == ATOMIC_TYPE_UCHAR) {
1972 return initializer_from_string(array_type,
1973 &expression->string.value);
1976 case EXPR_WIDE_STRING_LITERAL: {
1977 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1978 if (get_unqualified_type(element_type) == bare_wchar_type) {
1979 return initializer_from_wide_string(array_type,
1980 &expression->wide_string.value);
1990 assign_error_t error = semantic_assign(type, expression);
1991 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1993 report_assign_error(error, type, expression, "initializer",
1994 &expression->base.source_position);
1996 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1997 result->value.value = create_implicit_cast(expression, type);
2003 * Checks if a given expression can be used as an constant initializer.
2005 static bool is_initializer_constant(const expression_t *expression)
2007 return is_constant_expression(expression)
2008 || is_address_constant(expression);
2012 * Parses an scalar initializer.
2014 * § 6.7.8.11; eat {} without warning
2016 static initializer_t *parse_scalar_initializer(type_t *type,
2017 bool must_be_constant)
2019 /* there might be extra {} hierarchies */
2021 if (token.type == '{') {
2022 warningf(HERE, "extra curly braces around scalar initializer");
2026 } while (token.type == '{');
2029 expression_t *expression = parse_assignment_expression();
2030 if (must_be_constant && !is_initializer_constant(expression)) {
2031 errorf(&expression->base.source_position,
2032 "Initialisation expression '%E' is not constant\n",
2036 initializer_t *initializer = initializer_from_expression(type, expression);
2038 if (initializer == NULL) {
2039 errorf(&expression->base.source_position,
2040 "expression '%E' (type '%T') doesn't match expected type '%T'",
2041 expression, expression->base.type, type);
2046 bool additional_warning_displayed = false;
2047 while (braces > 0) {
2048 if (token.type == ',') {
2051 if (token.type != '}') {
2052 if (!additional_warning_displayed) {
2053 warningf(HERE, "additional elements in scalar initializer");
2054 additional_warning_displayed = true;
2065 * An entry in the type path.
2067 typedef struct type_path_entry_t type_path_entry_t;
2068 struct type_path_entry_t {
2069 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2071 size_t index; /**< For array types: the current index. */
2072 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2077 * A type path expression a position inside compound or array types.
2079 typedef struct type_path_t type_path_t;
2080 struct type_path_t {
2081 type_path_entry_t *path; /**< An flexible array containing the current path. */
2082 type_t *top_type; /**< type of the element the path points */
2083 size_t max_index; /**< largest index in outermost array */
2087 * Prints a type path for debugging.
2089 static __attribute__((unused)) void debug_print_type_path(
2090 const type_path_t *path)
2092 size_t len = ARR_LEN(path->path);
2094 for(size_t i = 0; i < len; ++i) {
2095 const type_path_entry_t *entry = & path->path[i];
2097 type_t *type = skip_typeref(entry->type);
2098 if (is_type_compound(type)) {
2099 /* in gcc mode structs can have no members */
2100 if (entry->v.compound_entry == NULL) {
2104 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2105 } else if (is_type_array(type)) {
2106 fprintf(stderr, "[%zu]", entry->v.index);
2108 fprintf(stderr, "-INVALID-");
2111 if (path->top_type != NULL) {
2112 fprintf(stderr, " (");
2113 print_type(path->top_type);
2114 fprintf(stderr, ")");
2119 * Return the top type path entry, ie. in a path
2120 * (type).a.b returns the b.
2122 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2124 size_t len = ARR_LEN(path->path);
2126 return &path->path[len-1];
2130 * Enlarge the type path by an (empty) element.
2132 static type_path_entry_t *append_to_type_path(type_path_t *path)
2134 size_t len = ARR_LEN(path->path);
2135 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2137 type_path_entry_t *result = & path->path[len];
2138 memset(result, 0, sizeof(result[0]));
2143 * Descending into a sub-type. Enter the scope of the current
2146 static void descend_into_subtype(type_path_t *path)
2148 type_t *orig_top_type = path->top_type;
2149 type_t *top_type = skip_typeref(orig_top_type);
2151 type_path_entry_t *top = append_to_type_path(path);
2152 top->type = top_type;
2154 if (is_type_compound(top_type)) {
2155 declaration_t *declaration = top_type->compound.declaration;
2156 declaration_t *entry = declaration->scope.declarations;
2157 top->v.compound_entry = entry;
2159 if (entry != NULL) {
2160 path->top_type = entry->type;
2162 path->top_type = NULL;
2164 } else if (is_type_array(top_type)) {
2166 path->top_type = top_type->array.element_type;
2168 assert(!is_type_valid(top_type));
2173 * Pop an entry from the given type path, ie. returning from
2174 * (type).a.b to (type).a
2176 static void ascend_from_subtype(type_path_t *path)
2178 type_path_entry_t *top = get_type_path_top(path);
2180 path->top_type = top->type;
2182 size_t len = ARR_LEN(path->path);
2183 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2187 * Pop entries from the given type path until the given
2188 * path level is reached.
2190 static void ascend_to(type_path_t *path, size_t top_path_level)
2192 size_t len = ARR_LEN(path->path);
2194 while (len > top_path_level) {
2195 ascend_from_subtype(path);
2196 len = ARR_LEN(path->path);
2200 static bool walk_designator(type_path_t *path, const designator_t *designator,
2201 bool used_in_offsetof)
2203 for( ; designator != NULL; designator = designator->next) {
2204 type_path_entry_t *top = get_type_path_top(path);
2205 type_t *orig_type = top->type;
2207 type_t *type = skip_typeref(orig_type);
2209 if (designator->symbol != NULL) {
2210 symbol_t *symbol = designator->symbol;
2211 if (!is_type_compound(type)) {
2212 if (is_type_valid(type)) {
2213 errorf(&designator->source_position,
2214 "'.%Y' designator used for non-compound type '%T'",
2220 declaration_t *declaration = type->compound.declaration;
2221 declaration_t *iter = declaration->scope.declarations;
2222 for( ; iter != NULL; iter = iter->next) {
2223 if (iter->symbol == symbol) {
2228 errorf(&designator->source_position,
2229 "'%T' has no member named '%Y'", orig_type, symbol);
2232 if (used_in_offsetof) {
2233 type_t *real_type = skip_typeref(iter->type);
2234 if (real_type->kind == TYPE_BITFIELD) {
2235 errorf(&designator->source_position,
2236 "offsetof designator '%Y' may not specify bitfield",
2242 top->type = orig_type;
2243 top->v.compound_entry = iter;
2244 orig_type = iter->type;
2246 expression_t *array_index = designator->array_index;
2247 assert(designator->array_index != NULL);
2249 if (!is_type_array(type)) {
2250 if (is_type_valid(type)) {
2251 errorf(&designator->source_position,
2252 "[%E] designator used for non-array type '%T'",
2253 array_index, orig_type);
2257 if (!is_type_valid(array_index->base.type)) {
2261 long index = fold_constant(array_index);
2262 if (!used_in_offsetof) {
2264 errorf(&designator->source_position,
2265 "array index [%E] must be positive", array_index);
2268 if (type->array.size_constant == true) {
2269 long array_size = type->array.size;
2270 if (index >= array_size) {
2271 errorf(&designator->source_position,
2272 "designator [%E] (%d) exceeds array size %d",
2273 array_index, index, array_size);
2279 top->type = orig_type;
2280 top->v.index = (size_t) index;
2281 orig_type = type->array.element_type;
2283 path->top_type = orig_type;
2285 if (designator->next != NULL) {
2286 descend_into_subtype(path);
2295 static void advance_current_object(type_path_t *path, size_t top_path_level)
2297 type_path_entry_t *top = get_type_path_top(path);
2299 type_t *type = skip_typeref(top->type);
2300 if (is_type_union(type)) {
2301 /* in unions only the first element is initialized */
2302 top->v.compound_entry = NULL;
2303 } else if (is_type_struct(type)) {
2304 declaration_t *entry = top->v.compound_entry;
2306 entry = entry->next;
2307 top->v.compound_entry = entry;
2308 if (entry != NULL) {
2309 path->top_type = entry->type;
2313 assert(is_type_array(type));
2317 if (!type->array.size_constant || top->v.index < type->array.size) {
2322 /* we're past the last member of the current sub-aggregate, try if we
2323 * can ascend in the type hierarchy and continue with another subobject */
2324 size_t len = ARR_LEN(path->path);
2326 if (len > top_path_level) {
2327 ascend_from_subtype(path);
2328 advance_current_object(path, top_path_level);
2330 path->top_type = NULL;
2335 * skip until token is found.
2337 static void skip_until(int type)
2339 while (token.type != type) {
2340 if (token.type == T_EOF)
2347 * skip any {...} blocks until a closing bracket is reached.
2349 static void skip_initializers(void)
2351 if (token.type == '{')
2354 while (token.type != '}') {
2355 if (token.type == T_EOF)
2357 if (token.type == '{') {
2365 static initializer_t *create_empty_initializer(void)
2367 static initializer_t empty_initializer
2368 = { .list = { { INITIALIZER_LIST }, 0 } };
2369 return &empty_initializer;
2373 * Parse a part of an initialiser for a struct or union,
2375 static initializer_t *parse_sub_initializer(type_path_t *path,
2376 type_t *outer_type, size_t top_path_level,
2377 parse_initializer_env_t *env)
2379 if (token.type == '}') {
2380 /* empty initializer */
2381 return create_empty_initializer();
2384 type_t *orig_type = path->top_type;
2385 type_t *type = NULL;
2387 if (orig_type == NULL) {
2388 /* We are initializing an empty compound. */
2390 type = skip_typeref(orig_type);
2392 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2393 * initializers in this case. */
2394 if (!is_type_valid(type)) {
2395 skip_initializers();
2396 return create_empty_initializer();
2400 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2403 designator_t *designator = NULL;
2404 if (token.type == '.' || token.type == '[') {
2405 designator = parse_designation();
2406 goto finish_designator;
2407 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2408 /* GNU-style designator ("identifier: value") */
2409 designator = allocate_ast_zero(sizeof(designator[0]));
2410 designator->source_position = token.source_position;
2411 designator->symbol = token.v.symbol;
2416 /* reset path to toplevel, evaluate designator from there */
2417 ascend_to(path, top_path_level);
2418 if (!walk_designator(path, designator, false)) {
2419 /* can't continue after designation error */
2423 initializer_t *designator_initializer
2424 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2425 designator_initializer->designator.designator = designator;
2426 ARR_APP1(initializer_t*, initializers, designator_initializer);
2428 orig_type = path->top_type;
2429 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2434 if (token.type == '{') {
2435 if (type != NULL && is_type_scalar(type)) {
2436 sub = parse_scalar_initializer(type, env->must_be_constant);
2440 if (env->declaration != NULL) {
2441 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2442 env->declaration->symbol);
2444 errorf(HERE, "extra brace group at end of initializer");
2447 descend_into_subtype(path);
2449 add_anchor_token('}');
2450 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2452 rem_anchor_token('}');
2455 ascend_from_subtype(path);
2459 goto error_parse_next;
2463 /* must be an expression */
2464 expression_t *expression = parse_assignment_expression();
2466 if (env->must_be_constant && !is_initializer_constant(expression)) {
2467 errorf(&expression->base.source_position,
2468 "Initialisation expression '%E' is not constant\n",
2473 /* we are already outside, ... */
2474 if (is_type_compound(outer_type) &&
2475 !outer_type->compound.declaration->init.complete) {
2476 goto error_parse_next;
2481 /* handle { "string" } special case */
2482 if ((expression->kind == EXPR_STRING_LITERAL
2483 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2484 && outer_type != NULL) {
2485 sub = initializer_from_expression(outer_type, expression);
2487 if (token.type == ',') {
2490 if (token.type != '}') {
2491 warningf(HERE, "excessive elements in initializer for type '%T'",
2494 /* TODO: eat , ... */
2499 /* descend into subtypes until expression matches type */
2501 orig_type = path->top_type;
2502 type = skip_typeref(orig_type);
2504 sub = initializer_from_expression(orig_type, expression);
2508 if (!is_type_valid(type)) {
2511 if (is_type_scalar(type)) {
2512 errorf(&expression->base.source_position,
2513 "expression '%E' doesn't match expected type '%T'",
2514 expression, orig_type);
2518 descend_into_subtype(path);
2522 /* update largest index of top array */
2523 const type_path_entry_t *first = &path->path[0];
2524 type_t *first_type = first->type;
2525 first_type = skip_typeref(first_type);
2526 if (is_type_array(first_type)) {
2527 size_t index = first->v.index;
2528 if (index > path->max_index)
2529 path->max_index = index;
2533 /* append to initializers list */
2534 ARR_APP1(initializer_t*, initializers, sub);
2537 if (env->declaration != NULL)
2538 warningf(HERE, "excess elements in struct initializer for '%Y'",
2539 env->declaration->symbol);
2541 warningf(HERE, "excess elements in struct initializer");
2545 if (token.type == '}') {
2549 if (token.type == '}') {
2554 /* advance to the next declaration if we are not at the end */
2555 advance_current_object(path, top_path_level);
2556 orig_type = path->top_type;
2557 if (orig_type != NULL)
2558 type = skip_typeref(orig_type);
2564 size_t len = ARR_LEN(initializers);
2565 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2566 initializer_t *result = allocate_ast_zero(size);
2567 result->kind = INITIALIZER_LIST;
2568 result->list.len = len;
2569 memcpy(&result->list.initializers, initializers,
2570 len * sizeof(initializers[0]));
2572 DEL_ARR_F(initializers);
2573 ascend_to(path, top_path_level+1);
2578 skip_initializers();
2579 DEL_ARR_F(initializers);
2580 ascend_to(path, top_path_level+1);
2585 * Parses an initializer. Parsers either a compound literal
2586 * (env->declaration == NULL) or an initializer of a declaration.
2588 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2590 type_t *type = skip_typeref(env->type);
2591 initializer_t *result = NULL;
2594 if (is_type_scalar(type)) {
2595 result = parse_scalar_initializer(type, env->must_be_constant);
2596 } else if (token.type == '{') {
2600 memset(&path, 0, sizeof(path));
2601 path.top_type = env->type;
2602 path.path = NEW_ARR_F(type_path_entry_t, 0);
2604 descend_into_subtype(&path);
2606 add_anchor_token('}');
2607 result = parse_sub_initializer(&path, env->type, 1, env);
2608 rem_anchor_token('}');
2610 max_index = path.max_index;
2611 DEL_ARR_F(path.path);
2615 /* parse_scalar_initializer() also works in this case: we simply
2616 * have an expression without {} around it */
2617 result = parse_scalar_initializer(type, env->must_be_constant);
2620 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2621 * the array type size */
2622 if (is_type_array(type) && type->array.size_expression == NULL
2623 && result != NULL) {
2625 switch (result->kind) {
2626 case INITIALIZER_LIST:
2627 size = max_index + 1;
2630 case INITIALIZER_STRING:
2631 size = result->string.string.size;
2634 case INITIALIZER_WIDE_STRING:
2635 size = result->wide_string.string.size;
2638 case INITIALIZER_DESIGNATOR:
2639 case INITIALIZER_VALUE:
2640 /* can happen for parse errors */
2645 internal_errorf(HERE, "invalid initializer type");
2648 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2649 cnst->base.type = type_size_t;
2650 cnst->conste.v.int_value = size;
2652 type_t *new_type = duplicate_type(type);
2654 new_type->array.size_expression = cnst;
2655 new_type->array.size_constant = true;
2656 new_type->array.size = size;
2657 env->type = new_type;
2665 static declaration_t *append_declaration(declaration_t *declaration);
2667 static declaration_t *parse_compound_type_specifier(bool is_struct)
2669 gnu_attribute_t *attributes = NULL;
2670 decl_modifiers_t modifiers = 0;
2677 symbol_t *symbol = NULL;
2678 declaration_t *declaration = NULL;
2680 if (token.type == T___attribute__) {
2681 modifiers |= parse_attributes(&attributes);
2684 if (token.type == T_IDENTIFIER) {
2685 symbol = token.v.symbol;
2688 namespace_t const namespc =
2689 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2690 declaration = get_declaration(symbol, namespc);
2691 if (declaration != NULL) {
2692 if (declaration->parent_scope != scope &&
2693 (token.type == '{' || token.type == ';')) {
2695 } else if (declaration->init.complete &&
2696 token.type == '{') {
2697 assert(symbol != NULL);
2698 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2699 is_struct ? "struct" : "union", symbol,
2700 &declaration->source_position);
2701 declaration->scope.declarations = NULL;
2704 } else if (token.type != '{') {
2706 parse_error_expected("while parsing struct type specifier",
2707 T_IDENTIFIER, '{', NULL);
2709 parse_error_expected("while parsing union type specifier",
2710 T_IDENTIFIER, '{', NULL);
2716 if (declaration == NULL) {
2717 declaration = allocate_declaration_zero();
2718 declaration->namespc =
2719 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2720 declaration->source_position = token.source_position;
2721 declaration->symbol = symbol;
2722 declaration->parent_scope = scope;
2723 if (symbol != NULL) {
2724 environment_push(declaration);
2726 append_declaration(declaration);
2729 if (token.type == '{') {
2730 declaration->init.complete = true;
2732 parse_compound_type_entries(declaration);
2733 modifiers |= parse_attributes(&attributes);
2736 declaration->modifiers |= modifiers;
2740 static void parse_enum_entries(type_t *const enum_type)
2744 if (token.type == '}') {
2746 errorf(HERE, "empty enum not allowed");
2750 add_anchor_token('}');
2752 if (token.type != T_IDENTIFIER) {
2753 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2755 rem_anchor_token('}');
2759 declaration_t *const entry = allocate_declaration_zero();
2760 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2761 entry->type = enum_type;
2762 entry->symbol = token.v.symbol;
2763 entry->source_position = token.source_position;
2766 if (token.type == '=') {
2768 expression_t *value = parse_constant_expression();
2770 value = create_implicit_cast(value, enum_type);
2771 entry->init.enum_value = value;
2776 record_declaration(entry, false);
2778 if (token.type != ',')
2781 } while (token.type != '}');
2782 rem_anchor_token('}');
2790 static type_t *parse_enum_specifier(void)
2792 gnu_attribute_t *attributes = NULL;
2793 declaration_t *declaration;
2797 if (token.type == T_IDENTIFIER) {
2798 symbol = token.v.symbol;
2801 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2802 } else if (token.type != '{') {
2803 parse_error_expected("while parsing enum type specifier",
2804 T_IDENTIFIER, '{', NULL);
2811 if (declaration == NULL) {
2812 declaration = allocate_declaration_zero();
2813 declaration->namespc = NAMESPACE_ENUM;
2814 declaration->source_position = token.source_position;
2815 declaration->symbol = symbol;
2816 declaration->parent_scope = scope;
2819 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2820 type->enumt.declaration = declaration;
2822 if (token.type == '{') {
2823 if (declaration->init.complete) {
2824 errorf(HERE, "multiple definitions of enum %Y", symbol);
2826 if (symbol != NULL) {
2827 environment_push(declaration);
2829 append_declaration(declaration);
2830 declaration->init.complete = true;
2832 parse_enum_entries(type);
2833 parse_attributes(&attributes);
2840 * if a symbol is a typedef to another type, return true
2842 static bool is_typedef_symbol(symbol_t *symbol)
2844 const declaration_t *const declaration =
2845 get_declaration(symbol, NAMESPACE_NORMAL);
2847 declaration != NULL &&
2848 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2851 static type_t *parse_typeof(void)
2858 add_anchor_token(')');
2860 expression_t *expression = NULL;
2862 bool old_type_prop = in_type_prop;
2863 bool old_gcc_extension = in_gcc_extension;
2864 in_type_prop = true;
2866 while (token.type == T___extension__) {
2867 /* This can be a prefix to a typename or an expression. */
2869 in_gcc_extension = true;
2871 switch (token.type) {
2873 if (is_typedef_symbol(token.v.symbol)) {
2874 type = parse_typename();
2876 expression = parse_expression();
2877 type = expression->base.type;
2882 type = parse_typename();
2886 expression = parse_expression();
2887 type = expression->base.type;
2890 in_type_prop = old_type_prop;
2891 in_gcc_extension = old_gcc_extension;
2893 rem_anchor_token(')');
2896 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2897 typeof_type->typeoft.expression = expression;
2898 typeof_type->typeoft.typeof_type = type;
2905 typedef enum specifiers_t {
2906 SPECIFIER_SIGNED = 1 << 0,
2907 SPECIFIER_UNSIGNED = 1 << 1,
2908 SPECIFIER_LONG = 1 << 2,
2909 SPECIFIER_INT = 1 << 3,
2910 SPECIFIER_DOUBLE = 1 << 4,
2911 SPECIFIER_CHAR = 1 << 5,
2912 SPECIFIER_SHORT = 1 << 6,
2913 SPECIFIER_LONG_LONG = 1 << 7,
2914 SPECIFIER_FLOAT = 1 << 8,
2915 SPECIFIER_BOOL = 1 << 9,
2916 SPECIFIER_VOID = 1 << 10,
2917 SPECIFIER_INT8 = 1 << 11,
2918 SPECIFIER_INT16 = 1 << 12,
2919 SPECIFIER_INT32 = 1 << 13,
2920 SPECIFIER_INT64 = 1 << 14,
2921 SPECIFIER_INT128 = 1 << 15,
2922 SPECIFIER_COMPLEX = 1 << 16,
2923 SPECIFIER_IMAGINARY = 1 << 17,
2926 static type_t *create_builtin_type(symbol_t *const symbol,
2927 type_t *const real_type)
2929 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2930 type->builtin.symbol = symbol;
2931 type->builtin.real_type = real_type;
2933 type_t *result = typehash_insert(type);
2934 if (type != result) {
2941 static type_t *get_typedef_type(symbol_t *symbol)
2943 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2944 if (declaration == NULL ||
2945 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2948 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2949 type->typedeft.declaration = declaration;
2955 * check for the allowed MS alignment values.
2957 static bool check_alignment_value(long long intvalue)
2959 if (intvalue < 1 || intvalue > 8192) {
2960 errorf(HERE, "illegal alignment value");
2963 unsigned v = (unsigned)intvalue;
2964 for (unsigned i = 1; i <= 8192; i += i) {
2968 errorf(HERE, "alignment must be power of two");
2972 #define DET_MOD(name, tag) do { \
2973 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2974 *modifiers |= tag; \
2977 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2979 decl_modifiers_t *modifiers = &specifiers->modifiers;
2982 if (token.type == T_restrict) {
2984 DET_MOD(restrict, DM_RESTRICT);
2986 } else if (token.type != T_IDENTIFIER)
2988 symbol_t *symbol = token.v.symbol;
2989 if (symbol == sym_align) {
2992 if (token.type != T_INTEGER)
2994 if (check_alignment_value(token.v.intvalue)) {
2995 if (specifiers->alignment != 0)
2996 warningf(HERE, "align used more than once");
2997 specifiers->alignment = (unsigned char)token.v.intvalue;
3001 } else if (symbol == sym_allocate) {
3004 if (token.type != T_IDENTIFIER)
3006 (void)token.v.symbol;
3008 } else if (symbol == sym_dllimport) {
3010 DET_MOD(dllimport, DM_DLLIMPORT);
3011 } else if (symbol == sym_dllexport) {
3013 DET_MOD(dllexport, DM_DLLEXPORT);
3014 } else if (symbol == sym_thread) {
3016 DET_MOD(thread, DM_THREAD);
3017 } else if (symbol == sym_naked) {
3019 DET_MOD(naked, DM_NAKED);
3020 } else if (symbol == sym_noinline) {
3022 DET_MOD(noinline, DM_NOINLINE);
3023 } else if (symbol == sym_noreturn) {
3025 DET_MOD(noreturn, DM_NORETURN);
3026 } else if (symbol == sym_nothrow) {
3028 DET_MOD(nothrow, DM_NOTHROW);
3029 } else if (symbol == sym_novtable) {
3031 DET_MOD(novtable, DM_NOVTABLE);
3032 } else if (symbol == sym_property) {
3036 bool is_get = false;
3037 if (token.type != T_IDENTIFIER)
3039 if (token.v.symbol == sym_get) {
3041 } else if (token.v.symbol == sym_put) {
3043 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3048 if (token.type != T_IDENTIFIER)
3051 if (specifiers->get_property_sym != NULL) {
3052 errorf(HERE, "get property name already specified");
3054 specifiers->get_property_sym = token.v.symbol;
3057 if (specifiers->put_property_sym != NULL) {
3058 errorf(HERE, "put property name already specified");
3060 specifiers->put_property_sym = token.v.symbol;
3064 if (token.type == ',') {
3071 } else if (symbol == sym_selectany) {
3073 DET_MOD(selectany, DM_SELECTANY);
3074 } else if (symbol == sym_uuid) {
3077 if (token.type != T_STRING_LITERAL)
3081 } else if (symbol == sym_deprecated) {
3083 if (specifiers->deprecated != 0)
3084 warningf(HERE, "deprecated used more than once");
3085 specifiers->deprecated = 1;
3086 if (token.type == '(') {
3088 if (token.type == T_STRING_LITERAL) {
3089 specifiers->deprecated_string = token.v.string.begin;
3092 errorf(HERE, "string literal expected");
3096 } else if (symbol == sym_noalias) {
3098 DET_MOD(noalias, DM_NOALIAS);
3100 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3102 if (token.type == '(')
3106 if (token.type == ',')
3113 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3115 declaration_t *const decl = allocate_declaration_zero();
3116 decl->source_position = *HERE;
3117 decl->declared_storage_class = storage_class;
3118 decl->storage_class =
3119 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3120 storage_class : STORAGE_CLASS_AUTO;
3121 decl->symbol = symbol;
3122 decl->implicit = true;
3123 record_declaration(decl, false);
3128 * Finish the construction of a struct type by calculating
3129 * its size, offsets, alignment.
3131 static void finish_struct_type(compound_type_t *type) {
3132 if (type->declaration == NULL)
3134 declaration_t *struct_decl = type->declaration;
3135 if (! struct_decl->init.complete)
3140 il_alignment_t alignment = 1;
3141 bool need_pad = false;
3143 declaration_t *entry = struct_decl->scope.declarations;
3144 for (; entry != NULL; entry = entry->next) {
3145 if (entry->namespc != NAMESPACE_NORMAL)
3148 type_t *m_type = skip_typeref(entry->type);
3149 if (! is_type_valid(m_type)) {
3150 /* simply ignore errors here */
3153 il_alignment_t m_alignment = m_type->base.alignment;
3154 if (m_alignment > alignment)
3155 alignment = m_alignment;
3157 offset = (size + m_alignment - 1) & -m_alignment;
3161 entry->offset = offset;
3162 size = offset + m_type->base.size;
3164 if (type->base.alignment != 0) {
3165 alignment = type->base.alignment;
3168 offset = (size + alignment - 1) & -alignment;
3172 if (warning.padded && need_pad) {
3173 warningf(&struct_decl->source_position,
3174 "'%#T' needs padding", type, struct_decl->symbol);
3176 if (warning.packed && !need_pad) {
3177 warningf(&struct_decl->source_position,
3178 "superfluous packed attribute on '%#T'",
3179 type, struct_decl->symbol);
3182 type->base.size = offset;
3183 type->base.alignment = alignment;
3187 * Finish the construction of an union type by calculating
3188 * its size and alignment.
3190 static void finish_union_type(compound_type_t *type) {
3191 if (type->declaration == NULL)
3193 declaration_t *union_decl = type->declaration;
3194 if (! union_decl->init.complete)
3198 il_alignment_t alignment = 1;
3200 declaration_t *entry = union_decl->scope.declarations;
3201 for (; entry != NULL; entry = entry->next) {
3202 if (entry->namespc != NAMESPACE_NORMAL)
3205 type_t *m_type = skip_typeref(entry->type);
3206 if (! is_type_valid(m_type))
3210 if (m_type->base.size > size)
3211 size = m_type->base.size;
3212 if (m_type->base.alignment > alignment)
3213 alignment = m_type->base.alignment;
3215 if (type->base.alignment != 0) {
3216 alignment = type->base.alignment;
3218 size = (size + alignment - 1) & -alignment;
3219 type->base.size = size;
3220 type->base.alignment = alignment;
3223 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3225 type_t *type = NULL;
3226 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3227 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3228 unsigned type_specifiers = 0;
3229 bool newtype = false;
3230 bool saw_error = false;
3231 bool old_gcc_extension = in_gcc_extension;
3233 specifiers->source_position = token.source_position;
3236 specifiers->modifiers
3237 |= parse_attributes(&specifiers->gnu_attributes);
3238 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3239 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3241 switch (token.type) {
3244 #define MATCH_STORAGE_CLASS(token, class) \
3246 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3247 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3249 specifiers->declared_storage_class = class; \
3253 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3254 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3255 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3256 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3257 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3262 add_anchor_token(')');
3263 parse_microsoft_extended_decl_modifier(specifiers);
3264 rem_anchor_token(')');
3269 switch (specifiers->declared_storage_class) {
3270 case STORAGE_CLASS_NONE:
3271 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3274 case STORAGE_CLASS_EXTERN:
3275 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3278 case STORAGE_CLASS_STATIC:
3279 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3283 errorf(HERE, "multiple storage classes in declaration specifiers");
3289 /* type qualifiers */
3290 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3292 qualifiers |= qualifier; \
3296 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3297 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3298 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3299 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3300 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3301 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3302 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3303 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3305 case T___extension__:
3307 in_gcc_extension = true;
3310 /* type specifiers */
3311 #define MATCH_SPECIFIER(token, specifier, name) \
3314 if (type_specifiers & specifier) { \
3315 errorf(HERE, "multiple " name " type specifiers given"); \
3317 type_specifiers |= specifier; \
3321 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3322 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3323 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3324 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3325 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3326 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3327 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3328 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3329 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3330 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3331 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3332 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3333 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3334 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3335 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3336 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3338 case T__forceinline:
3339 /* only in microsoft mode */
3340 specifiers->modifiers |= DM_FORCEINLINE;
3345 specifiers->is_inline = true;
3350 if (type_specifiers & SPECIFIER_LONG_LONG) {
3351 errorf(HERE, "multiple type specifiers given");
3352 } else if (type_specifiers & SPECIFIER_LONG) {
3353 type_specifiers |= SPECIFIER_LONG_LONG;
3355 type_specifiers |= SPECIFIER_LONG;
3360 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3362 type->compound.declaration = parse_compound_type_specifier(true);
3363 finish_struct_type(&type->compound);
3367 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3368 type->compound.declaration = parse_compound_type_specifier(false);
3369 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3370 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3372 finish_union_type(&type->compound);
3375 type = parse_enum_specifier();
3378 type = parse_typeof();
3380 case T___builtin_va_list:
3381 type = duplicate_type(type_valist);
3385 case T_IDENTIFIER: {
3386 /* only parse identifier if we haven't found a type yet */
3387 if (type != NULL || type_specifiers != 0) {
3388 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3389 * declaration, so it doesn't generate errors about expecting '(' or
3391 switch (look_ahead(1)->type) {
3398 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3401 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3406 goto finish_specifiers;
3410 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3411 if (typedef_type == NULL) {
3412 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3413 * declaration, so it doesn't generate 'implicit int' followed by more
3414 * errors later on. */
3415 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3420 errorf(HERE, "%K does not name a type", &token);
3422 declaration_t *const decl =
3423 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3425 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3426 type->typedeft.declaration = decl;
3430 if (la1_type == '*')
3431 goto finish_specifiers;
3436 goto finish_specifiers;
3441 type = typedef_type;
3445 /* function specifier */
3447 goto finish_specifiers;
3452 in_gcc_extension = old_gcc_extension;
3454 if (type == NULL || (saw_error && type_specifiers != 0)) {
3455 atomic_type_kind_t atomic_type;
3457 /* match valid basic types */
3458 switch(type_specifiers) {
3459 case SPECIFIER_VOID:
3460 atomic_type = ATOMIC_TYPE_VOID;
3462 case SPECIFIER_CHAR:
3463 atomic_type = ATOMIC_TYPE_CHAR;
3465 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3466 atomic_type = ATOMIC_TYPE_SCHAR;
3468 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3469 atomic_type = ATOMIC_TYPE_UCHAR;
3471 case SPECIFIER_SHORT:
3472 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3473 case SPECIFIER_SHORT | SPECIFIER_INT:
3474 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3475 atomic_type = ATOMIC_TYPE_SHORT;
3477 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3478 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3479 atomic_type = ATOMIC_TYPE_USHORT;
3482 case SPECIFIER_SIGNED:
3483 case SPECIFIER_SIGNED | SPECIFIER_INT:
3484 atomic_type = ATOMIC_TYPE_INT;
3486 case SPECIFIER_UNSIGNED:
3487 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3488 atomic_type = ATOMIC_TYPE_UINT;
3490 case SPECIFIER_LONG:
3491 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3492 case SPECIFIER_LONG | SPECIFIER_INT:
3493 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3494 atomic_type = ATOMIC_TYPE_LONG;
3496 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3497 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3498 atomic_type = ATOMIC_TYPE_ULONG;
3501 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3502 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3503 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3504 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3506 atomic_type = ATOMIC_TYPE_LONGLONG;
3507 goto warn_about_long_long;
3509 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3510 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3512 atomic_type = ATOMIC_TYPE_ULONGLONG;
3513 warn_about_long_long:
3514 if (warning.long_long) {
3515 warningf(&specifiers->source_position,
3516 "ISO C90 does not support 'long long'");
3520 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3521 atomic_type = unsigned_int8_type_kind;
3524 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3525 atomic_type = unsigned_int16_type_kind;
3528 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3529 atomic_type = unsigned_int32_type_kind;
3532 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3533 atomic_type = unsigned_int64_type_kind;
3536 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3537 atomic_type = unsigned_int128_type_kind;
3540 case SPECIFIER_INT8:
3541 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3542 atomic_type = int8_type_kind;
3545 case SPECIFIER_INT16:
3546 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3547 atomic_type = int16_type_kind;
3550 case SPECIFIER_INT32:
3551 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3552 atomic_type = int32_type_kind;
3555 case SPECIFIER_INT64:
3556 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3557 atomic_type = int64_type_kind;
3560 case SPECIFIER_INT128:
3561 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3562 atomic_type = int128_type_kind;
3565 case SPECIFIER_FLOAT:
3566 atomic_type = ATOMIC_TYPE_FLOAT;
3568 case SPECIFIER_DOUBLE:
3569 atomic_type = ATOMIC_TYPE_DOUBLE;
3571 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3572 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3574 case SPECIFIER_BOOL:
3575 atomic_type = ATOMIC_TYPE_BOOL;
3577 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3578 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3579 atomic_type = ATOMIC_TYPE_FLOAT;
3581 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3582 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3583 atomic_type = ATOMIC_TYPE_DOUBLE;
3585 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3586 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3587 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3590 /* invalid specifier combination, give an error message */
3591 if (type_specifiers == 0) {
3596 if (warning.implicit_int) {
3597 warningf(HERE, "no type specifiers in declaration, using 'int'");
3599 atomic_type = ATOMIC_TYPE_INT;
3602 errorf(HERE, "no type specifiers given in declaration");
3604 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3605 (type_specifiers & SPECIFIER_UNSIGNED)) {
3606 errorf(HERE, "signed and unsigned specifiers given");
3607 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3608 errorf(HERE, "only integer types can be signed or unsigned");
3610 errorf(HERE, "multiple datatypes in declaration");
3615 if (type_specifiers & SPECIFIER_COMPLEX) {
3616 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3617 type->complex.akind = atomic_type;
3618 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3619 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3620 type->imaginary.akind = atomic_type;
3622 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3623 type->atomic.akind = atomic_type;
3626 } else if (type_specifiers != 0) {
3627 errorf(HERE, "multiple datatypes in declaration");
3630 /* FIXME: check type qualifiers here */
3632 type->base.qualifiers = qualifiers;
3633 type->base.modifiers = modifiers;
3635 type_t *result = typehash_insert(type);
3636 if (newtype && result != type) {
3640 specifiers->type = result;
3644 specifiers->type = type_error_type;
3648 static type_qualifiers_t parse_type_qualifiers(void)
3650 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3653 switch(token.type) {
3654 /* type qualifiers */
3655 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3656 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3657 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3658 /* microsoft extended type modifiers */
3659 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3660 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3661 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3662 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3663 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3672 * Parses an K&R identifier list and return a list of declarations.
3674 * @param last points to the last declaration in the list
3675 * @return the list of declarations
3677 static declaration_t *parse_identifier_list(declaration_t **last)
3679 declaration_t *declarations = NULL;
3680 declaration_t *last_declaration = NULL;
3682 declaration_t *const declaration = allocate_declaration_zero();
3683 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3684 declaration->source_position = token.source_position;
3685 declaration->symbol = token.v.symbol;
3688 if (last_declaration != NULL) {
3689 last_declaration->next = declaration;
3691 declarations = declaration;
3693 last_declaration = declaration;
3695 if (token.type != ',') {
3699 } while (token.type == T_IDENTIFIER);
3701 *last = last_declaration;
3702 return declarations;
3705 static type_t *automatic_type_conversion(type_t *orig_type);
3707 static void semantic_parameter(declaration_t *declaration)
3709 /* TODO: improve error messages */
3710 source_position_t const* const pos = &declaration->source_position;
3712 switch (declaration->declared_storage_class) {
3713 case STORAGE_CLASS_TYPEDEF:
3714 errorf(pos, "typedef not allowed in parameter list");
3717 /* Allowed storage classes */
3718 case STORAGE_CLASS_NONE:
3719 case STORAGE_CLASS_REGISTER:
3723 errorf(pos, "parameter may only have none or register storage class");
3727 type_t *const orig_type = declaration->type;
3728 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3729 * sugar. Turn it into a pointer.
3730 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3731 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3733 type_t *const type = automatic_type_conversion(orig_type);
3734 declaration->type = type;
3736 if (is_type_incomplete(skip_typeref(type))) {
3737 errorf(pos, "parameter '%#T' is of incomplete type",
3738 orig_type, declaration->symbol);
3742 static declaration_t *parse_parameter(void)
3744 declaration_specifiers_t specifiers;
3745 memset(&specifiers, 0, sizeof(specifiers));
3747 parse_declaration_specifiers(&specifiers);
3749 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3755 * Parses a function type parameter list and return a list of declarations.
3757 * @param last point to the last element of the list
3758 * @return the parameter list
3760 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
3762 declaration_t *declarations = NULL;
3765 add_anchor_token(')');
3766 int saved_comma_state = save_and_reset_anchor_state(',');
3768 if (token.type == T_IDENTIFIER &&
3769 !is_typedef_symbol(token.v.symbol)) {
3770 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3771 if (la1_type == ',' || la1_type == ')') {
3772 type->kr_style_parameters = true;
3773 declarations = parse_identifier_list(last);
3774 goto parameters_finished;
3778 if (token.type == ')') {
3779 type->unspecified_parameters = 1;
3780 goto parameters_finished;
3783 declaration_t *declaration;
3784 declaration_t *last_declaration = NULL;
3785 function_parameter_t *parameter;
3786 function_parameter_t *last_parameter = NULL;
3789 switch(token.type) {
3793 goto parameters_finished;
3796 case T___extension__:
3798 declaration = parse_parameter();
3800 /* func(void) is not a parameter */
3801 if (last_parameter == NULL
3802 && token.type == ')'
3803 && declaration->symbol == NULL
3804 && skip_typeref(declaration->type) == type_void) {
3805 goto parameters_finished;
3807 semantic_parameter(declaration);
3809 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3810 memset(parameter, 0, sizeof(parameter[0]));
3811 parameter->type = declaration->type;
3813 if (last_parameter != NULL) {
3814 last_declaration->next = declaration;
3815 last_parameter->next = parameter;
3817 type->parameters = parameter;
3818 declarations = declaration;
3820 last_parameter = parameter;
3821 last_declaration = declaration;
3825 goto parameters_finished;
3827 if (token.type != ',') {
3828 goto parameters_finished;
3834 parameters_finished:
3835 rem_anchor_token(')');
3838 restore_anchor_state(',', saved_comma_state);
3839 *last = last_declaration;
3840 return declarations;
3843 restore_anchor_state(',', saved_comma_state);
3848 typedef enum construct_type_kind_t {
3853 } construct_type_kind_t;
3855 typedef struct construct_type_t construct_type_t;
3856 struct construct_type_t {
3857 construct_type_kind_t kind;
3858 construct_type_t *next;
3861 typedef struct parsed_pointer_t parsed_pointer_t;
3862 struct parsed_pointer_t {
3863 construct_type_t construct_type;
3864 type_qualifiers_t type_qualifiers;
3867 typedef struct construct_function_type_t construct_function_type_t;
3868 struct construct_function_type_t {
3869 construct_type_t construct_type;
3870 type_t *function_type;
3873 typedef struct parsed_array_t parsed_array_t;
3874 struct parsed_array_t {
3875 construct_type_t construct_type;
3876 type_qualifiers_t type_qualifiers;
3882 typedef struct construct_base_type_t construct_base_type_t;
3883 struct construct_base_type_t {
3884 construct_type_t construct_type;
3888 static construct_type_t *parse_pointer_declarator(void)
3892 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3893 memset(pointer, 0, sizeof(pointer[0]));
3894 pointer->construct_type.kind = CONSTRUCT_POINTER;
3895 pointer->type_qualifiers = parse_type_qualifiers();
3897 return (construct_type_t*) pointer;
3900 static construct_type_t *parse_array_declarator(void)
3903 add_anchor_token(']');
3905 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3906 memset(array, 0, sizeof(array[0]));
3907 array->construct_type.kind = CONSTRUCT_ARRAY;
3909 if (token.type == T_static) {
3910 array->is_static = true;
3914 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3915 if (type_qualifiers != 0) {
3916 if (token.type == T_static) {
3917 array->is_static = true;
3921 array->type_qualifiers = type_qualifiers;
3923 if (token.type == '*' && look_ahead(1)->type == ']') {
3924 array->is_variable = true;
3926 } else if (token.type != ']') {
3927 array->size = parse_assignment_expression();
3930 rem_anchor_token(']');
3934 return (construct_type_t*) array;
3937 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3940 if (declaration != NULL) {
3941 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3943 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3945 if (mask & (mask-1)) {
3946 const char *first = NULL, *second = NULL;
3948 /* more than one calling convention set */
3949 if (declaration->modifiers & DM_CDECL) {
3950 if (first == NULL) first = "cdecl";
3951 else if (second == NULL) second = "cdecl";
3953 if (declaration->modifiers & DM_STDCALL) {
3954 if (first == NULL) first = "stdcall";
3955 else if (second == NULL) second = "stdcall";
3957 if (declaration->modifiers & DM_FASTCALL) {
3958 if (first == NULL) first = "fastcall";
3959 else if (second == NULL) second = "fastcall";
3961 if (declaration->modifiers & DM_THISCALL) {
3962 if (first == NULL) first = "thiscall";
3963 else if (second == NULL) second = "thiscall";
3965 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3968 if (declaration->modifiers & DM_CDECL)
3969 type->function.calling_convention = CC_CDECL;
3970 else if (declaration->modifiers & DM_STDCALL)
3971 type->function.calling_convention = CC_STDCALL;
3972 else if (declaration->modifiers & DM_FASTCALL)
3973 type->function.calling_convention = CC_FASTCALL;
3974 else if (declaration->modifiers & DM_THISCALL)
3975 type->function.calling_convention = CC_THISCALL;
3977 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3980 declaration_t *last;
3981 declaration_t *parameters = parse_parameters(&type->function, &last);
3982 if (declaration != NULL) {
3983 declaration->scope.declarations = parameters;
3984 declaration->scope.last_declaration = last;
3985 declaration->scope.is_parameter = true;
3988 construct_function_type_t *construct_function_type =
3989 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3990 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3991 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3992 construct_function_type->function_type = type;
3994 return &construct_function_type->construct_type;
3997 static void fix_declaration_type(declaration_t *declaration)
3999 decl_modifiers_t declaration_modifiers = declaration->modifiers;
4000 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
4002 if (declaration_modifiers & DM_TRANSPARENT_UNION)
4003 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4005 if (declaration->type->base.modifiers == type_modifiers)
4008 type_t *copy = duplicate_type(declaration->type);
4009 copy->base.modifiers = type_modifiers;
4011 type_t *result = typehash_insert(copy);
4012 if (result != copy) {
4013 obstack_free(type_obst, copy);
4016 declaration->type = result;
4019 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4020 bool may_be_abstract)
4022 /* construct a single linked list of construct_type_t's which describe
4023 * how to construct the final declarator type */
4024 construct_type_t *first = NULL;
4025 construct_type_t *last = NULL;
4026 gnu_attribute_t *attributes = NULL;
4028 decl_modifiers_t modifiers = parse_attributes(&attributes);
4031 while (token.type == '*') {
4032 construct_type_t *type = parse_pointer_declarator();
4042 /* TODO: find out if this is correct */
4043 modifiers |= parse_attributes(&attributes);
4046 if (declaration != NULL)
4047 declaration->modifiers |= modifiers;
4049 construct_type_t *inner_types = NULL;
4051 switch(token.type) {
4053 if (declaration == NULL) {
4054 errorf(HERE, "no identifier expected in typename");
4056 declaration->symbol = token.v.symbol;
4057 declaration->source_position = token.source_position;
4063 add_anchor_token(')');
4064 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4065 if (inner_types != NULL) {
4066 /* All later declarators only modify the return type, not declaration */
4069 rem_anchor_token(')');
4073 if (may_be_abstract)
4075 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4080 construct_type_t *p = last;
4083 construct_type_t *type;
4084 switch(token.type) {
4086 type = parse_function_declarator(declaration);
4089 type = parse_array_declarator();
4092 goto declarator_finished;
4095 /* insert in the middle of the list (behind p) */
4097 type->next = p->next;
4108 declarator_finished:
4109 /* append inner_types at the end of the list, we don't to set last anymore
4110 * as it's not needed anymore */
4112 assert(first == NULL);
4113 first = inner_types;
4115 last->next = inner_types;
4123 static void parse_declaration_attributes(declaration_t *declaration)
4125 gnu_attribute_t *attributes = NULL;
4126 decl_modifiers_t modifiers = parse_attributes(&attributes);
4128 if (declaration == NULL)
4131 declaration->modifiers |= modifiers;
4132 /* check if we have these stupid mode attributes... */
4133 type_t *old_type = declaration->type;
4134 if (old_type == NULL)
4137 gnu_attribute_t *attribute = attributes;
4138 for ( ; attribute != NULL; attribute = attribute->next) {
4139 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4142 atomic_type_kind_t akind = attribute->u.akind;
4143 if (!is_type_signed(old_type)) {
4145 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4146 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4147 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4148 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4150 panic("invalid akind in mode attribute");
4154 = make_atomic_type(akind, old_type->base.qualifiers);
4158 static type_t *construct_declarator_type(construct_type_t *construct_list,
4161 construct_type_t *iter = construct_list;
4162 for( ; iter != NULL; iter = iter->next) {
4163 switch(iter->kind) {
4164 case CONSTRUCT_INVALID:
4165 internal_errorf(HERE, "invalid type construction found");
4166 case CONSTRUCT_FUNCTION: {
4167 construct_function_type_t *construct_function_type
4168 = (construct_function_type_t*) iter;
4170 type_t *function_type = construct_function_type->function_type;
4172 function_type->function.return_type = type;
4174 type_t *skipped_return_type = skip_typeref(type);
4176 if (is_type_function(skipped_return_type)) {
4177 errorf(HERE, "function returning function is not allowed");
4178 } else if (is_type_array(skipped_return_type)) {
4179 errorf(HERE, "function returning array is not allowed");
4181 if (skipped_return_type->base.qualifiers != 0) {
4183 "type qualifiers in return type of function type are meaningless");
4187 type = function_type;
4191 case CONSTRUCT_POINTER: {
4192 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4193 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4194 pointer_type->pointer.points_to = type;
4195 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4197 type = pointer_type;
4201 case CONSTRUCT_ARRAY: {
4202 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4203 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4205 expression_t *size_expression = parsed_array->size;
4206 if (size_expression != NULL) {
4208 = create_implicit_cast(size_expression, type_size_t);
4211 array_type->base.qualifiers = parsed_array->type_qualifiers;
4212 array_type->array.element_type = type;
4213 array_type->array.is_static = parsed_array->is_static;
4214 array_type->array.is_variable = parsed_array->is_variable;
4215 array_type->array.size_expression = size_expression;
4217 if (size_expression != NULL) {
4218 if (is_constant_expression(size_expression)) {
4219 array_type->array.size_constant = true;
4220 array_type->array.size
4221 = fold_constant(size_expression);
4223 array_type->array.is_vla = true;
4227 type_t *skipped_type = skip_typeref(type);
4229 if (is_type_incomplete(skipped_type)) {
4230 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4231 } else if (is_type_function(skipped_type)) {
4232 errorf(HERE, "array of functions is not allowed");
4239 type_t *hashed_type = typehash_insert(type);
4240 if (hashed_type != type) {
4241 /* the function type was constructed earlier freeing it here will
4242 * destroy other types... */
4243 if (iter->kind != CONSTRUCT_FUNCTION) {
4253 static declaration_t *parse_declarator(
4254 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4256 declaration_t *const declaration = allocate_declaration_zero();
4257 declaration->source_position = specifiers->source_position;
4258 declaration->declared_storage_class = specifiers->declared_storage_class;
4259 declaration->modifiers = specifiers->modifiers;
4260 declaration->deprecated_string = specifiers->deprecated_string;
4261 declaration->get_property_sym = specifiers->get_property_sym;
4262 declaration->put_property_sym = specifiers->put_property_sym;
4263 declaration->is_inline = specifiers->is_inline;
4265 declaration->storage_class = specifiers->declared_storage_class;
4266 if (declaration->storage_class == STORAGE_CLASS_NONE
4267 && scope != global_scope) {
4268 declaration->storage_class = STORAGE_CLASS_AUTO;
4271 if (specifiers->alignment != 0) {
4272 /* TODO: add checks here */
4273 declaration->alignment = specifiers->alignment;
4276 construct_type_t *construct_type
4277 = parse_inner_declarator(declaration, may_be_abstract);
4278 type_t *const type = specifiers->type;
4279 declaration->type = construct_declarator_type(construct_type, type);
4281 parse_declaration_attributes(declaration);
4283 fix_declaration_type(declaration);
4285 if (construct_type != NULL) {
4286 obstack_free(&temp_obst, construct_type);
4292 static type_t *parse_abstract_declarator(type_t *base_type)
4294 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4296 type_t *result = construct_declarator_type(construct_type, base_type);
4297 if (construct_type != NULL) {
4298 obstack_free(&temp_obst, construct_type);
4304 static declaration_t *append_declaration(declaration_t* const declaration)
4306 if (last_declaration != NULL) {
4307 last_declaration->next = declaration;
4309 scope->declarations = declaration;
4311 last_declaration = declaration;
4316 * Check if the declaration of main is suspicious. main should be a
4317 * function with external linkage, returning int, taking either zero
4318 * arguments, two, or three arguments of appropriate types, ie.
4320 * int main([ int argc, char **argv [, char **env ] ]).
4322 * @param decl the declaration to check
4323 * @param type the function type of the declaration
4325 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4327 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4328 warningf(&decl->source_position,
4329 "'main' is normally a non-static function");
4331 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4332 warningf(&decl->source_position,
4333 "return type of 'main' should be 'int', but is '%T'",
4334 func_type->return_type);
4336 const function_parameter_t *parm = func_type->parameters;
4338 type_t *const first_type = parm->type;
4339 if (!types_compatible(skip_typeref(first_type), type_int)) {
4340 warningf(&decl->source_position,
4341 "first argument of 'main' should be 'int', but is '%T'", first_type);
4345 type_t *const second_type = parm->type;
4346 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4347 warningf(&decl->source_position,
4348 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4352 type_t *const third_type = parm->type;
4353 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4354 warningf(&decl->source_position,
4355 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4359 goto warn_arg_count;
4363 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4369 * Check if a symbol is the equal to "main".
4371 static bool is_sym_main(const symbol_t *const sym)
4373 return strcmp(sym->string, "main") == 0;
4376 static declaration_t *record_declaration(
4377 declaration_t *const declaration,
4378 const bool is_definition)
4380 const symbol_t *const symbol = declaration->symbol;
4381 const namespace_t namespc = (namespace_t)declaration->namespc;
4383 assert(symbol != NULL);
4384 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4386 type_t *const orig_type = declaration->type;
4387 type_t *const type = skip_typeref(orig_type);
4388 if (is_type_function(type) &&
4389 type->function.unspecified_parameters &&
4390 warning.strict_prototypes &&
4391 previous_declaration == NULL) {
4392 warningf(&declaration->source_position,
4393 "function declaration '%#T' is not a prototype",
4397 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4398 check_type_of_main(declaration, &type->function);
4401 if (warning.nested_externs &&
4402 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4403 scope != global_scope) {
4404 warningf(&declaration->source_position,
4405 "nested extern declaration of '%#T'", declaration->type, symbol);
4408 assert(declaration != previous_declaration);
4409 if (previous_declaration != NULL &&
4410 previous_declaration->parent_scope->is_parameter &&
4411 scope->depth == previous_declaration->parent_scope->depth + 1) {
4412 errorf(&declaration->source_position,
4413 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4414 orig_type, symbol, previous_declaration->type, symbol,
4415 &previous_declaration->source_position);
4418 if (previous_declaration != NULL &&
4419 previous_declaration->parent_scope == scope) {
4420 /* can happen for K&R style declarations */
4421 if (previous_declaration->type == NULL) {
4422 previous_declaration->type = declaration->type;
4425 const type_t *prev_type = skip_typeref(previous_declaration->type);
4426 if (!types_compatible(type, prev_type)) {
4427 errorf(&declaration->source_position,
4428 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4429 orig_type, symbol, previous_declaration->type, symbol,
4430 &previous_declaration->source_position);
4432 unsigned old_storage_class = previous_declaration->storage_class;
4433 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4434 errorf(&declaration->source_position,
4435 "redeclaration of enum entry '%Y' (declared %P)",
4436 symbol, &previous_declaration->source_position);
4437 return previous_declaration;
4440 if (warning.redundant_decls &&
4442 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4443 !(previous_declaration->modifiers & DM_USED) &&
4444 !previous_declaration->used) {
4445 warningf(&previous_declaration->source_position,
4446 "unnecessary static forward declaration for '%#T'",
4447 previous_declaration->type, symbol);
4450 unsigned new_storage_class = declaration->storage_class;
4452 if (is_type_incomplete(prev_type)) {
4453 previous_declaration->type = type;
4457 /* pretend no storage class means extern for function
4458 * declarations (except if the previous declaration is neither
4459 * none nor extern) */
4460 if (is_type_function(type)) {
4461 if (prev_type->function.unspecified_parameters) {
4462 previous_declaration->type = type;
4466 switch (old_storage_class) {
4467 case STORAGE_CLASS_NONE:
4468 old_storage_class = STORAGE_CLASS_EXTERN;
4471 case STORAGE_CLASS_EXTERN:
4472 if (is_definition) {
4473 if (warning.missing_prototypes &&
4474 prev_type->function.unspecified_parameters &&
4475 !is_sym_main(symbol)) {
4476 warningf(&declaration->source_position,
4477 "no previous prototype for '%#T'",
4480 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4481 new_storage_class = STORAGE_CLASS_EXTERN;
4490 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4491 new_storage_class == STORAGE_CLASS_EXTERN) {
4492 warn_redundant_declaration:
4493 if (!is_definition &&
4494 warning.redundant_decls &&
4495 is_type_valid(prev_type) &&
4496 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4497 warningf(&declaration->source_position,
4498 "redundant declaration for '%Y' (declared %P)",
4499 symbol, &previous_declaration->source_position);
4501 } else if (current_function == NULL) {
4502 if (old_storage_class != STORAGE_CLASS_STATIC &&
4503 new_storage_class == STORAGE_CLASS_STATIC) {
4504 errorf(&declaration->source_position,
4505 "static declaration of '%Y' follows non-static declaration (declared %P)",
4506 symbol, &previous_declaration->source_position);
4507 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4508 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4509 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4511 goto warn_redundant_declaration;
4513 } else if (is_type_valid(prev_type)) {
4514 if (old_storage_class == new_storage_class) {
4515 errorf(&declaration->source_position,
4516 "redeclaration of '%Y' (declared %P)",
4517 symbol, &previous_declaration->source_position);
4519 errorf(&declaration->source_position,
4520 "redeclaration of '%Y' with different linkage (declared %P)",
4521 symbol, &previous_declaration->source_position);
4526 previous_declaration->modifiers |= declaration->modifiers;
4527 previous_declaration->is_inline |= declaration->is_inline;
4528 return previous_declaration;
4529 } else if (is_type_function(type)) {
4530 if (is_definition &&
4531 declaration->storage_class != STORAGE_CLASS_STATIC) {
4532 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4533 warningf(&declaration->source_position,
4534 "no previous prototype for '%#T'", orig_type, symbol);
4535 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4536 warningf(&declaration->source_position,
4537 "no previous declaration for '%#T'", orig_type,
4542 if (warning.missing_declarations &&
4543 scope == global_scope && (
4544 declaration->storage_class == STORAGE_CLASS_NONE ||
4545 declaration->storage_class == STORAGE_CLASS_THREAD
4547 warningf(&declaration->source_position,
4548 "no previous declaration for '%#T'", orig_type, symbol);
4552 assert(declaration->parent_scope == NULL);
4553 assert(scope != NULL);
4555 declaration->parent_scope = scope;
4557 environment_push(declaration);
4558 return append_declaration(declaration);
4561 static void parser_error_multiple_definition(declaration_t *declaration,
4562 const source_position_t *source_position)
4564 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4565 declaration->symbol, &declaration->source_position);
4568 static bool is_declaration_specifier(const token_t *token,
4569 bool only_specifiers_qualifiers)
4571 switch (token->type) {
4576 return is_typedef_symbol(token->v.symbol);
4578 case T___extension__:
4580 return !only_specifiers_qualifiers;
4587 static void parse_init_declarator_rest(declaration_t *declaration)
4591 type_t *orig_type = declaration->type;
4592 type_t *type = skip_typeref(orig_type);
4594 if (declaration->init.initializer != NULL) {
4595 parser_error_multiple_definition(declaration, HERE);
4598 bool must_be_constant = false;
4599 if (declaration->storage_class == STORAGE_CLASS_STATIC
4600 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4601 || declaration->parent_scope == global_scope) {
4602 must_be_constant = true;
4605 if (is_type_function(type)) {
4606 errorf(&declaration->source_position,
4607 "function '%#T' is initialized like a variable",
4608 orig_type, declaration->symbol);
4609 orig_type = type_error_type;
4612 parse_initializer_env_t env;
4613 env.type = orig_type;
4614 env.must_be_constant = must_be_constant;
4615 env.declaration = current_init_decl = declaration;
4617 initializer_t *initializer = parse_initializer(&env);
4618 current_init_decl = NULL;
4620 if (!is_type_function(type)) {
4621 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4622 * the array type size */
4623 declaration->type = env.type;
4624 declaration->init.initializer = initializer;
4628 /* parse rest of a declaration without any declarator */
4629 static void parse_anonymous_declaration_rest(
4630 const declaration_specifiers_t *specifiers)
4634 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4635 warningf(&specifiers->source_position,
4636 "useless storage class in empty declaration");
4639 type_t *type = specifiers->type;
4640 switch (type->kind) {
4641 case TYPE_COMPOUND_STRUCT:
4642 case TYPE_COMPOUND_UNION: {
4643 if (type->compound.declaration->symbol == NULL) {
4644 warningf(&specifiers->source_position,
4645 "unnamed struct/union that defines no instances");
4654 warningf(&specifiers->source_position, "empty declaration");
4658 #ifdef RECORD_EMPTY_DECLARATIONS
4659 declaration_t *const declaration = allocate_declaration_zero();
4660 declaration->type = specifiers->type;
4661 declaration->declared_storage_class = specifiers->declared_storage_class;
4662 declaration->source_position = specifiers->source_position;
4663 declaration->modifiers = specifiers->modifiers;
4664 declaration->storage_class = STORAGE_CLASS_NONE;
4666 append_declaration(declaration);
4670 static void parse_declaration_rest(declaration_t *ndeclaration,
4671 const declaration_specifiers_t *specifiers,
4672 parsed_declaration_func finished_declaration)
4674 add_anchor_token(';');
4675 add_anchor_token(',');
4677 declaration_t *declaration =
4678 finished_declaration(ndeclaration, token.type == '=');
4680 type_t *orig_type = declaration->type;
4681 type_t *type = skip_typeref(orig_type);
4683 if (type->kind != TYPE_FUNCTION &&
4684 declaration->is_inline &&
4685 is_type_valid(type)) {
4686 warningf(&declaration->source_position,
4687 "variable '%Y' declared 'inline'\n", declaration->symbol);
4690 if (token.type == '=') {
4691 parse_init_declarator_rest(declaration);
4694 if (token.type != ',')
4698 add_anchor_token('=');
4699 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4700 rem_anchor_token('=');
4705 rem_anchor_token(';');
4706 rem_anchor_token(',');
4709 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4711 symbol_t *symbol = declaration->symbol;
4712 if (symbol == NULL) {
4713 errorf(HERE, "anonymous declaration not valid as function parameter");
4716 namespace_t namespc = (namespace_t) declaration->namespc;
4717 if (namespc != NAMESPACE_NORMAL) {
4718 return record_declaration(declaration, false);
4721 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4722 if (previous_declaration == NULL ||
4723 previous_declaration->parent_scope != scope) {
4724 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4729 if (is_definition) {
4730 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4733 if (previous_declaration->type == NULL) {
4734 previous_declaration->type = declaration->type;
4735 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4736 previous_declaration->storage_class = declaration->storage_class;
4737 previous_declaration->parent_scope = scope;
4738 return previous_declaration;
4740 return record_declaration(declaration, false);
4744 static void parse_declaration(parsed_declaration_func finished_declaration)
4746 declaration_specifiers_t specifiers;
4747 memset(&specifiers, 0, sizeof(specifiers));
4749 add_anchor_token(';');
4750 parse_declaration_specifiers(&specifiers);
4751 rem_anchor_token(';');
4753 if (token.type == ';') {
4754 parse_anonymous_declaration_rest(&specifiers);
4756 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4757 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4761 static type_t *get_default_promoted_type(type_t *orig_type)
4763 type_t *result = orig_type;
4765 type_t *type = skip_typeref(orig_type);
4766 if (is_type_integer(type)) {
4767 result = promote_integer(type);
4768 } else if (type == type_float) {
4769 result = type_double;
4775 static void parse_kr_declaration_list(declaration_t *declaration)
4777 type_t *type = skip_typeref(declaration->type);
4778 if (!is_type_function(type))
4781 if (!type->function.kr_style_parameters)
4784 add_anchor_token('{');
4786 /* push function parameters */
4787 size_t const top = environment_top();
4788 scope_push(&declaration->scope);
4790 declaration_t *parameter = declaration->scope.declarations;
4791 for ( ; parameter != NULL; parameter = parameter->next) {
4792 assert(parameter->parent_scope == NULL);
4793 parameter->parent_scope = scope;
4794 environment_push(parameter);
4797 /* parse declaration list */
4798 while (is_declaration_specifier(&token, false)) {
4799 parse_declaration(finished_kr_declaration);
4802 /* pop function parameters */
4803 assert(scope == &declaration->scope);
4805 environment_pop_to(top);
4807 /* update function type */
4808 type_t *new_type = duplicate_type(type);
4810 function_parameter_t *parameters = NULL;
4811 function_parameter_t *last_parameter = NULL;
4813 declaration_t *parameter_declaration = declaration->scope.declarations;
4814 for( ; parameter_declaration != NULL;
4815 parameter_declaration = parameter_declaration->next) {
4816 type_t *parameter_type = parameter_declaration->type;
4817 if (parameter_type == NULL) {
4819 errorf(HERE, "no type specified for function parameter '%Y'",
4820 parameter_declaration->symbol);
4822 if (warning.implicit_int) {
4823 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4824 parameter_declaration->symbol);
4826 parameter_type = type_int;
4827 parameter_declaration->type = parameter_type;
4831 semantic_parameter(parameter_declaration);
4832 parameter_type = parameter_declaration->type;
4835 * we need the default promoted types for the function type
4837 parameter_type = get_default_promoted_type(parameter_type);
4839 function_parameter_t *function_parameter
4840 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4841 memset(function_parameter, 0, sizeof(function_parameter[0]));
4843 function_parameter->type = parameter_type;
4844 if (last_parameter != NULL) {
4845 last_parameter->next = function_parameter;
4847 parameters = function_parameter;
4849 last_parameter = function_parameter;
4852 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4854 new_type->function.parameters = parameters;
4855 new_type->function.unspecified_parameters = true;
4857 type = typehash_insert(new_type);
4858 if (type != new_type) {
4859 obstack_free(type_obst, new_type);
4862 declaration->type = type;
4864 rem_anchor_token('{');
4867 static bool first_err = true;
4870 * When called with first_err set, prints the name of the current function,
4873 static void print_in_function(void)
4877 diagnosticf("%s: In function '%Y':\n",
4878 current_function->source_position.input_name,
4879 current_function->symbol);
4884 * Check if all labels are defined in the current function.
4885 * Check if all labels are used in the current function.
4887 static void check_labels(void)
4889 for (const goto_statement_t *goto_statement = goto_first;
4890 goto_statement != NULL;
4891 goto_statement = goto_statement->next) {
4892 /* skip computed gotos */
4893 if (goto_statement->expression != NULL)
4896 declaration_t *label = goto_statement->label;
4899 if (label->source_position.input_name == NULL) {
4900 print_in_function();
4901 errorf(&goto_statement->base.source_position,
4902 "label '%Y' used but not defined", label->symbol);
4905 goto_first = goto_last = NULL;
4907 if (warning.unused_label) {
4908 for (const label_statement_t *label_statement = label_first;
4909 label_statement != NULL;
4910 label_statement = label_statement->next) {
4911 const declaration_t *label = label_statement->label;
4913 if (! label->used) {
4914 print_in_function();
4915 warningf(&label_statement->base.source_position,
4916 "label '%Y' defined but not used", label->symbol);
4920 label_first = label_last = NULL;
4924 * Check declarations of current_function for unused entities.
4926 static void check_declarations(void)
4928 if (warning.unused_parameter) {
4929 const scope_t *scope = ¤t_function->scope;
4931 if (is_sym_main(current_function->symbol)) {
4932 /* do not issue unused warnings for main */
4935 const declaration_t *parameter = scope->declarations;
4936 for (; parameter != NULL; parameter = parameter->next) {
4937 if (! parameter->used) {
4938 print_in_function();
4939 warningf(¶meter->source_position,
4940 "unused parameter '%Y'", parameter->symbol);
4944 if (warning.unused_variable) {
4948 static int determine_truth(expression_t const* const cond)
4951 !is_constant_expression(cond) ? 0 :
4952 fold_constant(cond) != 0 ? 1 :
4956 static bool noreturn_candidate;
4958 static void check_reachable(statement_t *const stmt)
4960 if (stmt->base.reachable)
4962 if (stmt->kind != STATEMENT_DO_WHILE)
4963 stmt->base.reachable = true;
4965 statement_t *last = stmt;
4967 switch (stmt->kind) {
4968 case STATEMENT_INVALID:
4969 case STATEMENT_EMPTY:
4970 case STATEMENT_DECLARATION:
4972 next = stmt->base.next;
4975 case STATEMENT_COMPOUND:
4976 next = stmt->compound.statements;
4979 case STATEMENT_RETURN:
4980 noreturn_candidate = false;
4983 case STATEMENT_IF: {
4984 if_statement_t const* const ifs = &stmt->ifs;
4985 int const val = determine_truth(ifs->condition);
4988 check_reachable(ifs->true_statement);
4993 if (ifs->false_statement != NULL) {
4994 check_reachable(ifs->false_statement);
4998 next = stmt->base.next;
5002 case STATEMENT_SWITCH: {
5003 switch_statement_t const *const switchs = &stmt->switchs;
5004 expression_t const *const expr = switchs->expression;
5006 if (is_constant_expression(expr)) {
5007 long const val = fold_constant(expr);
5008 case_label_statement_t * defaults = NULL;
5009 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5010 if (i->expression == NULL) {
5015 if (i->first_case <= val && val <= i->last_case) {
5016 check_reachable((statement_t*)i);
5021 if (defaults != NULL) {
5022 check_reachable((statement_t*)defaults);
5026 bool has_default = false;
5027 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5028 if (i->expression == NULL)
5031 check_reachable((statement_t*)i);
5038 next = stmt->base.next;
5042 case STATEMENT_EXPRESSION: {
5043 /* Check for noreturn function call */
5044 expression_t const *const expr = stmt->expression.expression;
5045 if (expr->kind == EXPR_CALL) {
5046 expression_t const *const func = expr->call.function;
5047 if (func->kind == EXPR_REFERENCE) {
5048 declaration_t const *const decl = func->reference.declaration;
5049 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5055 next = stmt->base.next;
5059 case STATEMENT_CONTINUE: {
5060 statement_t *parent = stmt;
5062 parent = parent->base.parent;
5063 if (parent == NULL) /* continue not within loop */
5067 switch (parent->kind) {
5068 case STATEMENT_WHILE: goto continue_while;
5069 case STATEMENT_DO_WHILE: goto continue_do_while;
5070 case STATEMENT_FOR: goto continue_for;
5077 case STATEMENT_BREAK: {
5078 statement_t *parent = stmt;
5080 parent = parent->base.parent;
5081 if (parent == NULL) /* break not within loop/switch */
5084 switch (parent->kind) {
5085 case STATEMENT_SWITCH:
5086 case STATEMENT_WHILE:
5087 case STATEMENT_DO_WHILE:
5090 next = parent->base.next;
5091 goto found_break_parent;
5100 case STATEMENT_GOTO:
5101 if (stmt->gotos.expression) {
5102 statement_t *parent = stmt->base.parent;
5103 if (parent == NULL) /* top level goto */
5107 next = stmt->gotos.label->init.statement;
5108 if (next == NULL) /* missing label */
5113 case STATEMENT_LABEL:
5114 next = stmt->label.statement;
5117 case STATEMENT_CASE_LABEL:
5118 next = stmt->case_label.statement;
5121 case STATEMENT_WHILE: {
5122 while_statement_t const *const whiles = &stmt->whiles;
5123 int const val = determine_truth(whiles->condition);
5126 check_reachable(whiles->body);
5131 next = stmt->base.next;
5135 case STATEMENT_DO_WHILE:
5136 next = stmt->do_while.body;
5139 case STATEMENT_FOR: {
5140 for_statement_t *const fors = &stmt->fors;
5142 if (fors->condition_reachable)
5144 fors->condition_reachable = true;
5146 expression_t const *const cond = fors->condition;
5148 cond == NULL ? 1 : determine_truth(cond);
5151 check_reachable(fors->body);
5156 next = stmt->base.next;
5160 case STATEMENT_MS_TRY: {
5161 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5162 check_reachable(ms_try->try_statement);
5163 next = ms_try->final_statement;
5167 case STATEMENT_LEAVE: {
5168 statement_t *parent = stmt;
5170 parent = parent->base.parent;
5171 if (parent == NULL) /* __leave not within __try */
5174 if (parent->kind == STATEMENT_MS_TRY) {
5176 next = parent->ms_try.final_statement;
5184 while (next == NULL) {
5185 next = last->base.parent;
5187 noreturn_candidate = false;
5189 type_t *const type = current_function->type;
5190 assert(is_type_function(type));
5191 type_t *const ret = skip_typeref(type->function.return_type);
5192 if (warning.return_type &&
5193 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5194 is_type_valid(ret) &&
5195 !is_sym_main(current_function->symbol)) {
5196 warningf(&stmt->base.source_position,
5197 "control reaches end of non-void function");
5202 switch (next->kind) {
5203 case STATEMENT_INVALID:
5204 case STATEMENT_EMPTY:
5205 case STATEMENT_DECLARATION:
5206 case STATEMENT_EXPRESSION:
5208 case STATEMENT_RETURN:
5209 case STATEMENT_CONTINUE:
5210 case STATEMENT_BREAK:
5211 case STATEMENT_GOTO:
5212 case STATEMENT_LEAVE:
5213 panic("invalid control flow in function");
5215 case STATEMENT_COMPOUND:
5217 case STATEMENT_SWITCH:
5218 case STATEMENT_LABEL:
5219 case STATEMENT_CASE_LABEL:
5221 next = next->base.next;
5224 case STATEMENT_WHILE: {
5226 if (next->base.reachable)
5228 next->base.reachable = true;
5230 while_statement_t const *const whiles = &next->whiles;
5231 int const val = determine_truth(whiles->condition);
5234 check_reachable(whiles->body);
5240 next = next->base.next;
5244 case STATEMENT_DO_WHILE: {
5246 if (next->base.reachable)
5248 next->base.reachable = true;
5250 do_while_statement_t const *const dw = &next->do_while;
5251 int const val = determine_truth(dw->condition);
5254 check_reachable(dw->body);
5260 next = next->base.next;
5264 case STATEMENT_FOR: {
5266 for_statement_t *const fors = &next->fors;
5268 fors->step_reachable = true;
5270 if (fors->condition_reachable)
5272 fors->condition_reachable = true;
5274 expression_t const *const cond = fors->condition;
5276 cond == NULL ? 1 : determine_truth(cond);
5279 check_reachable(fors->body);
5285 next = next->base.next;
5289 case STATEMENT_MS_TRY:
5291 next = next->ms_try.final_statement;
5297 next = stmt->base.parent;
5299 warningf(&stmt->base.source_position,
5300 "control reaches end of non-void function");
5304 check_reachable(next);
5307 static void check_unreachable(statement_t const* const stmt)
5309 if (!stmt->base.reachable &&
5310 stmt->kind != STATEMENT_DO_WHILE &&
5311 stmt->kind != STATEMENT_FOR &&
5312 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5313 warningf(&stmt->base.source_position, "statement is unreachable");
5316 switch (stmt->kind) {
5317 case STATEMENT_INVALID:
5318 case STATEMENT_EMPTY:
5319 case STATEMENT_RETURN:
5320 case STATEMENT_DECLARATION:
5321 case STATEMENT_EXPRESSION:
5322 case STATEMENT_CONTINUE:
5323 case STATEMENT_BREAK:
5324 case STATEMENT_GOTO:
5326 case STATEMENT_LEAVE:
5329 case STATEMENT_COMPOUND:
5330 if (stmt->compound.statements)
5331 check_unreachable(stmt->compound.statements);
5335 check_unreachable(stmt->ifs.true_statement);
5336 if (stmt->ifs.false_statement != NULL)
5337 check_unreachable(stmt->ifs.false_statement);
5340 case STATEMENT_SWITCH:
5341 check_unreachable(stmt->switchs.body);
5344 case STATEMENT_LABEL:
5345 check_unreachable(stmt->label.statement);
5348 case STATEMENT_CASE_LABEL:
5349 check_unreachable(stmt->case_label.statement);
5352 case STATEMENT_WHILE:
5353 check_unreachable(stmt->whiles.body);
5356 case STATEMENT_DO_WHILE:
5357 check_unreachable(stmt->do_while.body);
5358 if (!stmt->base.reachable) {
5359 expression_t const *const cond = stmt->do_while.condition;
5360 if (determine_truth(cond) >= 0) {
5361 warningf(&cond->base.source_position,
5362 "condition of do-while-loop is unreachable");
5367 case STATEMENT_FOR: {
5368 for_statement_t const* const fors = &stmt->fors;
5370 // if init and step are unreachable, cond is unreachable, too
5371 if (!stmt->base.reachable && !fors->step_reachable) {
5372 warningf(&stmt->base.source_position, "statement is unreachable");
5374 if (!stmt->base.reachable && fors->initialisation != NULL) {
5375 warningf(&fors->initialisation->base.source_position,
5376 "initialisation of for-statement is unreachable");
5379 if (!fors->condition_reachable && fors->condition != NULL) {
5380 warningf(&fors->condition->base.source_position,
5381 "condition of for-statement is unreachable");
5384 if (!fors->step_reachable && fors->step != NULL) {
5385 warningf(&fors->step->base.source_position,
5386 "step of for-statement is unreachable");
5390 check_unreachable(fors->body);
5394 case STATEMENT_MS_TRY: {
5395 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5396 check_unreachable(ms_try->try_statement);
5397 check_unreachable(ms_try->final_statement);
5401 if (stmt->base.next)
5402 check_unreachable(stmt->base.next);
5405 static void parse_external_declaration(void)
5407 /* function-definitions and declarations both start with declaration
5409 declaration_specifiers_t specifiers;
5410 memset(&specifiers, 0, sizeof(specifiers));
5412 add_anchor_token(';');
5413 parse_declaration_specifiers(&specifiers);
5414 rem_anchor_token(';');
5416 /* must be a declaration */
5417 if (token.type == ';') {
5418 parse_anonymous_declaration_rest(&specifiers);
5422 add_anchor_token(',');
5423 add_anchor_token('=');
5424 add_anchor_token(';');
5425 add_anchor_token('{');
5427 /* declarator is common to both function-definitions and declarations */
5428 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5430 rem_anchor_token('{');
5431 rem_anchor_token(';');
5432 rem_anchor_token('=');
5433 rem_anchor_token(',');
5435 /* must be a declaration */
5436 switch (token.type) {
5440 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5444 /* must be a function definition */
5445 parse_kr_declaration_list(ndeclaration);
5447 if (token.type != '{') {
5448 parse_error_expected("while parsing function definition", '{', NULL);
5449 eat_until_matching_token(';');
5453 type_t *type = ndeclaration->type;
5455 /* note that we don't skip typerefs: the standard doesn't allow them here
5456 * (so we can't use is_type_function here) */
5457 if (type->kind != TYPE_FUNCTION) {
5458 if (is_type_valid(type)) {
5459 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5460 type, ndeclaration->symbol);
5466 if (warning.aggregate_return &&
5467 is_type_compound(skip_typeref(type->function.return_type))) {
5468 warningf(HERE, "function '%Y' returns an aggregate",
5469 ndeclaration->symbol);
5471 if (warning.traditional && !type->function.unspecified_parameters) {
5472 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5473 ndeclaration->symbol);
5475 if (warning.old_style_definition && type->function.unspecified_parameters) {
5476 warningf(HERE, "old-style function definition '%Y'",
5477 ndeclaration->symbol);
5480 /* § 6.7.5.3 (14) a function definition with () means no
5481 * parameters (and not unspecified parameters) */
5482 if (type->function.unspecified_parameters
5483 && type->function.parameters == NULL
5484 && !type->function.kr_style_parameters) {
5485 type_t *duplicate = duplicate_type(type);
5486 duplicate->function.unspecified_parameters = false;
5488 type = typehash_insert(duplicate);
5489 if (type != duplicate) {
5490 obstack_free(type_obst, duplicate);
5492 ndeclaration->type = type;
5495 declaration_t *const declaration = record_declaration(ndeclaration, true);
5496 if (ndeclaration != declaration) {
5497 declaration->scope = ndeclaration->scope;
5499 type = skip_typeref(declaration->type);
5501 /* push function parameters and switch scope */
5502 size_t const top = environment_top();
5503 scope_push(&declaration->scope);
5505 declaration_t *parameter = declaration->scope.declarations;
5506 for( ; parameter != NULL; parameter = parameter->next) {
5507 if (parameter->parent_scope == &ndeclaration->scope) {
5508 parameter->parent_scope = scope;
5510 assert(parameter->parent_scope == NULL
5511 || parameter->parent_scope == scope);
5512 parameter->parent_scope = scope;
5513 if (parameter->symbol == NULL) {
5514 errorf(¶meter->source_position, "parameter name omitted");
5517 environment_push(parameter);
5520 if (declaration->init.statement != NULL) {
5521 parser_error_multiple_definition(declaration, HERE);
5524 /* parse function body */
5525 int label_stack_top = label_top();
5526 declaration_t *old_current_function = current_function;
5527 current_function = declaration;
5528 current_parent = NULL;
5530 statement_t *const body = parse_compound_statement(false);
5531 declaration->init.statement = body;
5534 check_declarations();
5535 if (warning.return_type ||
5536 warning.unreachable_code ||
5537 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5538 noreturn_candidate = true;
5539 check_reachable(body);
5540 if (warning.unreachable_code)
5541 check_unreachable(body);
5542 if (warning.missing_noreturn &&
5543 noreturn_candidate &&
5544 !(declaration->modifiers & DM_NORETURN)) {
5545 warningf(&body->base.source_position,
5546 "function '%#T' is candidate for attribute 'noreturn'",
5547 type, declaration->symbol);
5551 assert(current_parent == NULL);
5552 assert(current_function == declaration);
5553 current_function = old_current_function;
5554 label_pop_to(label_stack_top);
5557 assert(scope == &declaration->scope);
5559 environment_pop_to(top);
5562 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5563 source_position_t *source_position,
5564 const symbol_t *symbol)
5566 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5568 type->bitfield.base_type = base_type;
5569 type->bitfield.size_expression = size;
5572 type_t *skipped_type = skip_typeref(base_type);
5573 if (!is_type_integer(skipped_type)) {
5574 errorf(HERE, "bitfield base type '%T' is not an integer type",
5578 bit_size = skipped_type->base.size * 8;
5581 if (is_constant_expression(size)) {
5582 long v = fold_constant(size);
5585 errorf(source_position, "negative width in bit-field '%Y'",
5587 } else if (v == 0) {
5588 errorf(source_position, "zero width for bit-field '%Y'",
5590 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5591 errorf(source_position, "width of '%Y' exceeds its type",
5594 type->bitfield.bit_size = v;
5601 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5604 declaration_t *iter = compound_declaration->scope.declarations;
5605 for( ; iter != NULL; iter = iter->next) {
5606 if (iter->namespc != NAMESPACE_NORMAL)
5609 if (iter->symbol == NULL) {
5610 type_t *type = skip_typeref(iter->type);
5611 if (is_type_compound(type)) {
5612 declaration_t *result
5613 = find_compound_entry(type->compound.declaration, symbol);
5620 if (iter->symbol == symbol) {
5628 static void parse_compound_declarators(declaration_t *struct_declaration,
5629 const declaration_specifiers_t *specifiers)
5631 declaration_t *last_declaration = struct_declaration->scope.declarations;
5632 if (last_declaration != NULL) {
5633 while (last_declaration->next != NULL) {
5634 last_declaration = last_declaration->next;
5639 declaration_t *declaration;
5641 if (token.type == ':') {
5642 source_position_t source_position = *HERE;
5645 type_t *base_type = specifiers->type;
5646 expression_t *size = parse_constant_expression();
5648 type_t *type = make_bitfield_type(base_type, size,
5649 &source_position, sym_anonymous);
5651 declaration = allocate_declaration_zero();
5652 declaration->namespc = NAMESPACE_NORMAL;
5653 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5654 declaration->storage_class = STORAGE_CLASS_NONE;
5655 declaration->source_position = source_position;
5656 declaration->modifiers = specifiers->modifiers;
5657 declaration->type = type;
5659 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5661 type_t *orig_type = declaration->type;
5662 type_t *type = skip_typeref(orig_type);
5664 if (token.type == ':') {
5665 source_position_t source_position = *HERE;
5667 expression_t *size = parse_constant_expression();
5669 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5670 &source_position, declaration->symbol);
5671 declaration->type = bitfield_type;
5673 /* TODO we ignore arrays for now... what is missing is a check
5674 * that they're at the end of the struct */
5675 if (is_type_incomplete(type) && !is_type_array(type)) {
5677 "compound member '%Y' has incomplete type '%T'",
5678 declaration->symbol, orig_type);
5679 } else if (is_type_function(type)) {
5680 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5681 declaration->symbol, orig_type);
5686 /* make sure we don't define a symbol multiple times */
5687 symbol_t *symbol = declaration->symbol;
5688 if (symbol != NULL) {
5689 declaration_t *prev_decl
5690 = find_compound_entry(struct_declaration, symbol);
5692 if (prev_decl != NULL) {
5693 assert(prev_decl->symbol == symbol);
5694 errorf(&declaration->source_position,
5695 "multiple declarations of symbol '%Y' (declared %P)",
5696 symbol, &prev_decl->source_position);
5700 /* append declaration */
5701 if (last_declaration != NULL) {
5702 last_declaration->next = declaration;
5704 struct_declaration->scope.declarations = declaration;
5706 last_declaration = declaration;
5708 if (token.type != ',')
5718 static void parse_compound_type_entries(declaration_t *compound_declaration)
5721 add_anchor_token('}');
5723 while (token.type != '}' && token.type != T_EOF) {
5724 declaration_specifiers_t specifiers;
5725 memset(&specifiers, 0, sizeof(specifiers));
5726 parse_declaration_specifiers(&specifiers);
5728 parse_compound_declarators(compound_declaration, &specifiers);
5730 rem_anchor_token('}');
5732 if (token.type == T_EOF) {
5733 errorf(HERE, "EOF while parsing struct");
5738 static type_t *parse_typename(void)
5740 declaration_specifiers_t specifiers;
5741 memset(&specifiers, 0, sizeof(specifiers));
5742 parse_declaration_specifiers(&specifiers);
5743 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5744 /* TODO: improve error message, user does probably not know what a
5745 * storage class is...
5747 errorf(HERE, "typename may not have a storage class");
5750 type_t *result = parse_abstract_declarator(specifiers.type);
5758 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5759 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5760 expression_t *left);
5762 typedef struct expression_parser_function_t expression_parser_function_t;
5763 struct expression_parser_function_t {
5764 unsigned precedence;
5765 parse_expression_function parser;
5766 unsigned infix_precedence;
5767 parse_expression_infix_function infix_parser;
5770 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5773 * Prints an error message if an expression was expected but not read
5775 static expression_t *expected_expression_error(void)
5777 /* skip the error message if the error token was read */
5778 if (token.type != T_ERROR) {
5779 errorf(HERE, "expected expression, got token '%K'", &token);
5783 return create_invalid_expression();
5787 * Parse a string constant.
5789 static expression_t *parse_string_const(void)
5792 if (token.type == T_STRING_LITERAL) {
5793 string_t res = token.v.string;
5795 while (token.type == T_STRING_LITERAL) {
5796 res = concat_strings(&res, &token.v.string);
5799 if (token.type != T_WIDE_STRING_LITERAL) {
5800 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5801 /* note: that we use type_char_ptr here, which is already the
5802 * automatic converted type. revert_automatic_type_conversion
5803 * will construct the array type */
5804 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5805 cnst->string.value = res;
5809 wres = concat_string_wide_string(&res, &token.v.wide_string);
5811 wres = token.v.wide_string;
5816 switch (token.type) {
5817 case T_WIDE_STRING_LITERAL:
5818 wres = concat_wide_strings(&wres, &token.v.wide_string);
5821 case T_STRING_LITERAL:
5822 wres = concat_wide_string_string(&wres, &token.v.string);
5826 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5827 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5828 cnst->wide_string.value = wres;
5837 * Parse an integer constant.
5839 static expression_t *parse_int_const(void)
5841 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5842 cnst->base.source_position = *HERE;
5843 cnst->base.type = token.datatype;
5844 cnst->conste.v.int_value = token.v.intvalue;
5852 * Parse a character constant.
5854 static expression_t *parse_character_constant(void)
5856 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5858 cnst->base.source_position = *HERE;
5859 cnst->base.type = token.datatype;
5860 cnst->conste.v.character = token.v.string;
5862 if (cnst->conste.v.character.size != 1) {
5863 if (warning.multichar && GNU_MODE) {
5864 warningf(HERE, "multi-character character constant");
5866 errorf(HERE, "more than 1 characters in character constant");
5875 * Parse a wide character constant.
5877 static expression_t *parse_wide_character_constant(void)
5879 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5881 cnst->base.source_position = *HERE;
5882 cnst->base.type = token.datatype;
5883 cnst->conste.v.wide_character = token.v.wide_string;
5885 if (cnst->conste.v.wide_character.size != 1) {
5886 if (warning.multichar && GNU_MODE) {
5887 warningf(HERE, "multi-character character constant");
5889 errorf(HERE, "more than 1 characters in character constant");
5898 * Parse a float constant.
5900 static expression_t *parse_float_const(void)
5902 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5903 cnst->base.type = token.datatype;
5904 cnst->conste.v.float_value = token.v.floatvalue;
5911 static declaration_t *create_implicit_function(symbol_t *symbol,
5912 const source_position_t *source_position)
5914 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5915 ntype->function.return_type = type_int;
5916 ntype->function.unspecified_parameters = true;
5918 type_t *type = typehash_insert(ntype);
5919 if (type != ntype) {
5923 declaration_t *const declaration = allocate_declaration_zero();
5924 declaration->storage_class = STORAGE_CLASS_EXTERN;
5925 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5926 declaration->type = type;
5927 declaration->symbol = symbol;
5928 declaration->source_position = *source_position;
5929 declaration->implicit = true;
5931 bool strict_prototypes_old = warning.strict_prototypes;
5932 warning.strict_prototypes = false;
5933 record_declaration(declaration, false);
5934 warning.strict_prototypes = strict_prototypes_old;
5940 * Creates a return_type (func)(argument_type) function type if not
5943 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5944 type_t *argument_type2)
5946 function_parameter_t *parameter2
5947 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5948 memset(parameter2, 0, sizeof(parameter2[0]));
5949 parameter2->type = argument_type2;
5951 function_parameter_t *parameter1
5952 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5953 memset(parameter1, 0, sizeof(parameter1[0]));
5954 parameter1->type = argument_type1;
5955 parameter1->next = parameter2;
5957 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5958 type->function.return_type = return_type;
5959 type->function.parameters = parameter1;
5961 type_t *result = typehash_insert(type);
5962 if (result != type) {
5970 * Creates a return_type (func)(argument_type) function type if not
5973 * @param return_type the return type
5974 * @param argument_type the argument type
5976 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5978 function_parameter_t *parameter
5979 = obstack_alloc(type_obst, sizeof(parameter[0]));
5980 memset(parameter, 0, sizeof(parameter[0]));
5981 parameter->type = argument_type;
5983 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5984 type->function.return_type = return_type;
5985 type->function.parameters = parameter;
5987 type_t *result = typehash_insert(type);
5988 if (result != type) {
5995 static type_t *make_function_0_type(type_t *return_type)
5997 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5998 type->function.return_type = return_type;
5999 type->function.parameters = NULL;
6001 type_t *result = typehash_insert(type);
6002 if (result != type) {
6010 * Creates a function type for some function like builtins.
6012 * @param symbol the symbol describing the builtin
6014 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6016 switch(symbol->ID) {
6017 case T___builtin_alloca:
6018 return make_function_1_type(type_void_ptr, type_size_t);
6019 case T___builtin_huge_val:
6020 return make_function_0_type(type_double);
6021 case T___builtin_nan:
6022 return make_function_1_type(type_double, type_char_ptr);
6023 case T___builtin_nanf:
6024 return make_function_1_type(type_float, type_char_ptr);
6025 case T___builtin_nand:
6026 return make_function_1_type(type_long_double, type_char_ptr);
6027 case T___builtin_va_end:
6028 return make_function_1_type(type_void, type_valist);
6029 case T___builtin_expect:
6030 return make_function_2_type(type_long, type_long, type_long);
6032 internal_errorf(HERE, "not implemented builtin symbol found");
6037 * Performs automatic type cast as described in § 6.3.2.1.
6039 * @param orig_type the original type
6041 static type_t *automatic_type_conversion(type_t *orig_type)
6043 type_t *type = skip_typeref(orig_type);
6044 if (is_type_array(type)) {
6045 array_type_t *array_type = &type->array;
6046 type_t *element_type = array_type->element_type;
6047 unsigned qualifiers = array_type->base.qualifiers;
6049 return make_pointer_type(element_type, qualifiers);
6052 if (is_type_function(type)) {
6053 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6060 * reverts the automatic casts of array to pointer types and function
6061 * to function-pointer types as defined § 6.3.2.1
6063 type_t *revert_automatic_type_conversion(const expression_t *expression)
6065 switch (expression->kind) {
6066 case EXPR_REFERENCE: return expression->reference.declaration->type;
6069 return get_qualified_type(expression->select.compound_entry->type,
6070 expression->base.type->base.qualifiers);
6072 case EXPR_UNARY_DEREFERENCE: {
6073 const expression_t *const value = expression->unary.value;
6074 type_t *const type = skip_typeref(value->base.type);
6075 assert(is_type_pointer(type));
6076 return type->pointer.points_to;
6079 case EXPR_BUILTIN_SYMBOL:
6080 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6082 case EXPR_ARRAY_ACCESS: {
6083 const expression_t *array_ref = expression->array_access.array_ref;
6084 type_t *type_left = skip_typeref(array_ref->base.type);
6085 if (!is_type_valid(type_left))
6087 assert(is_type_pointer(type_left));
6088 return type_left->pointer.points_to;
6091 case EXPR_STRING_LITERAL: {
6092 size_t size = expression->string.value.size;
6093 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6096 case EXPR_WIDE_STRING_LITERAL: {
6097 size_t size = expression->wide_string.value.size;
6098 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6101 case EXPR_COMPOUND_LITERAL:
6102 return expression->compound_literal.type;
6107 return expression->base.type;
6110 static expression_t *parse_reference(void)
6112 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6114 reference_expression_t *ref = &expression->reference;
6115 symbol_t *const symbol = token.v.symbol;
6117 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6119 if (declaration == NULL) {
6120 if (!strict_mode && look_ahead(1)->type == '(') {
6121 /* an implicitly declared function */
6122 if (warning.implicit_function_declaration) {
6123 warningf(HERE, "implicit declaration of function '%Y'",
6127 declaration = create_implicit_function(symbol, HERE);
6129 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6130 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6134 type_t *orig_type = declaration->type;
6136 /* we always do the auto-type conversions; the & and sizeof parser contains
6137 * code to revert this! */
6138 type_t *type = automatic_type_conversion(orig_type);
6140 ref->declaration = declaration;
6141 ref->base.type = type;
6143 /* this declaration is used */
6144 declaration->used = true;
6146 if (declaration->parent_scope != global_scope &&
6147 declaration->parent_scope->depth < current_function->scope.depth &&
6148 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6149 /* access of a variable from an outer function */
6150 declaration->address_taken = true;
6151 ref->is_outer_ref = true;
6152 current_function->need_closure = true;
6155 /* check for deprecated functions */
6156 if (warning.deprecated_declarations &&
6157 declaration->modifiers & DM_DEPRECATED) {
6158 char const *const prefix = is_type_function(declaration->type) ?
6159 "function" : "variable";
6161 if (declaration->deprecated_string != NULL) {
6162 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6163 prefix, declaration->symbol, &declaration->source_position,
6164 declaration->deprecated_string);
6166 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6167 declaration->symbol, &declaration->source_position);
6170 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6171 current_init_decl = NULL;
6172 warningf(HERE, "variable '%#T' is initialized by itself",
6173 declaration->type, declaration->symbol);
6180 static bool semantic_cast(expression_t *cast)
6182 expression_t *expression = cast->unary.value;
6183 type_t *orig_dest_type = cast->base.type;
6184 type_t *orig_type_right = expression->base.type;
6185 type_t const *dst_type = skip_typeref(orig_dest_type);
6186 type_t const *src_type = skip_typeref(orig_type_right);
6187 source_position_t const *pos = &cast->base.source_position;
6189 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6190 if (dst_type == type_void)
6193 /* only integer and pointer can be casted to pointer */
6194 if (is_type_pointer(dst_type) &&
6195 !is_type_pointer(src_type) &&
6196 !is_type_integer(src_type) &&
6197 is_type_valid(src_type)) {
6198 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6202 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6203 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6207 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6208 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6212 if (warning.cast_qual &&
6213 is_type_pointer(src_type) &&
6214 is_type_pointer(dst_type)) {
6215 type_t *src = skip_typeref(src_type->pointer.points_to);
6216 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6217 unsigned missing_qualifiers =
6218 src->base.qualifiers & ~dst->base.qualifiers;
6219 if (missing_qualifiers != 0) {
6221 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6222 missing_qualifiers, orig_type_right);
6228 static expression_t *parse_compound_literal(type_t *type)
6230 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6232 parse_initializer_env_t env;
6234 env.declaration = NULL;
6235 env.must_be_constant = false;
6236 initializer_t *initializer = parse_initializer(&env);
6239 expression->compound_literal.initializer = initializer;
6240 expression->compound_literal.type = type;
6241 expression->base.type = automatic_type_conversion(type);
6247 * Parse a cast expression.
6249 static expression_t *parse_cast(void)
6251 add_anchor_token(')');
6253 source_position_t source_position = token.source_position;
6255 type_t *type = parse_typename();
6257 rem_anchor_token(')');
6260 if (token.type == '{') {
6261 return parse_compound_literal(type);
6264 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6265 cast->base.source_position = source_position;
6267 expression_t *value = parse_sub_expression(20);
6268 cast->base.type = type;
6269 cast->unary.value = value;
6271 if (! semantic_cast(cast)) {
6272 /* TODO: record the error in the AST. else it is impossible to detect it */
6277 return create_invalid_expression();
6281 * Parse a statement expression.
6283 static expression_t *parse_statement_expression(void)
6285 add_anchor_token(')');
6287 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6289 statement_t *statement = parse_compound_statement(true);
6290 expression->statement.statement = statement;
6291 expression->base.source_position = statement->base.source_position;
6293 /* find last statement and use its type */
6294 type_t *type = type_void;
6295 const statement_t *stmt = statement->compound.statements;
6297 while (stmt->base.next != NULL)
6298 stmt = stmt->base.next;
6300 if (stmt->kind == STATEMENT_EXPRESSION) {
6301 type = stmt->expression.expression->base.type;
6304 warningf(&expression->base.source_position, "empty statement expression ({})");
6306 expression->base.type = type;
6308 rem_anchor_token(')');
6316 * Parse a parenthesized expression.
6318 static expression_t *parse_parenthesized_expression(void)
6322 switch(token.type) {
6324 /* gcc extension: a statement expression */
6325 return parse_statement_expression();
6329 return parse_cast();
6331 if (is_typedef_symbol(token.v.symbol)) {
6332 return parse_cast();
6336 add_anchor_token(')');
6337 expression_t *result = parse_expression();
6338 rem_anchor_token(')');
6345 static expression_t *parse_function_keyword(void)
6350 if (current_function == NULL) {
6351 errorf(HERE, "'__func__' used outside of a function");
6354 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6355 expression->base.type = type_char_ptr;
6356 expression->funcname.kind = FUNCNAME_FUNCTION;
6361 static expression_t *parse_pretty_function_keyword(void)
6363 eat(T___PRETTY_FUNCTION__);
6365 if (current_function == NULL) {
6366 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6369 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6370 expression->base.type = type_char_ptr;
6371 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6376 static expression_t *parse_funcsig_keyword(void)
6380 if (current_function == NULL) {
6381 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6384 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6385 expression->base.type = type_char_ptr;
6386 expression->funcname.kind = FUNCNAME_FUNCSIG;
6391 static expression_t *parse_funcdname_keyword(void)
6393 eat(T___FUNCDNAME__);
6395 if (current_function == NULL) {
6396 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6399 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6400 expression->base.type = type_char_ptr;
6401 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6406 static designator_t *parse_designator(void)
6408 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6409 result->source_position = *HERE;
6411 if (token.type != T_IDENTIFIER) {
6412 parse_error_expected("while parsing member designator",
6413 T_IDENTIFIER, NULL);
6416 result->symbol = token.v.symbol;
6419 designator_t *last_designator = result;
6421 if (token.type == '.') {
6423 if (token.type != T_IDENTIFIER) {
6424 parse_error_expected("while parsing member designator",
6425 T_IDENTIFIER, NULL);
6428 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6429 designator->source_position = *HERE;
6430 designator->symbol = token.v.symbol;
6433 last_designator->next = designator;
6434 last_designator = designator;
6437 if (token.type == '[') {
6439 add_anchor_token(']');
6440 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6441 designator->source_position = *HERE;
6442 designator->array_index = parse_expression();
6443 rem_anchor_token(']');
6445 if (designator->array_index == NULL) {
6449 last_designator->next = designator;
6450 last_designator = designator;
6462 * Parse the __builtin_offsetof() expression.
6464 static expression_t *parse_offsetof(void)
6466 eat(T___builtin_offsetof);
6468 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6469 expression->base.type = type_size_t;
6472 add_anchor_token(',');
6473 type_t *type = parse_typename();
6474 rem_anchor_token(',');
6476 add_anchor_token(')');
6477 designator_t *designator = parse_designator();
6478 rem_anchor_token(')');
6481 expression->offsetofe.type = type;
6482 expression->offsetofe.designator = designator;
6485 memset(&path, 0, sizeof(path));
6486 path.top_type = type;
6487 path.path = NEW_ARR_F(type_path_entry_t, 0);
6489 descend_into_subtype(&path);
6491 if (!walk_designator(&path, designator, true)) {
6492 return create_invalid_expression();
6495 DEL_ARR_F(path.path);
6499 return create_invalid_expression();
6503 * Parses a _builtin_va_start() expression.
6505 static expression_t *parse_va_start(void)
6507 eat(T___builtin_va_start);
6509 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6512 add_anchor_token(',');
6513 expression->va_starte.ap = parse_assignment_expression();
6514 rem_anchor_token(',');
6516 expression_t *const expr = parse_assignment_expression();
6517 if (expr->kind == EXPR_REFERENCE) {
6518 declaration_t *const decl = expr->reference.declaration;
6519 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6520 errorf(&expr->base.source_position,
6521 "second argument of 'va_start' must be last parameter of the current function");
6523 expression->va_starte.parameter = decl;
6529 return create_invalid_expression();
6533 * Parses a _builtin_va_arg() expression.
6535 static expression_t *parse_va_arg(void)
6537 eat(T___builtin_va_arg);
6539 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6542 expression->va_arge.ap = parse_assignment_expression();
6544 expression->base.type = parse_typename();
6549 return create_invalid_expression();
6552 static expression_t *parse_builtin_symbol(void)
6554 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6556 symbol_t *symbol = token.v.symbol;
6558 expression->builtin_symbol.symbol = symbol;
6561 type_t *type = get_builtin_symbol_type(symbol);
6562 type = automatic_type_conversion(type);
6564 expression->base.type = type;
6569 * Parses a __builtin_constant() expression.
6571 static expression_t *parse_builtin_constant(void)
6573 eat(T___builtin_constant_p);
6575 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6578 add_anchor_token(')');
6579 expression->builtin_constant.value = parse_assignment_expression();
6580 rem_anchor_token(')');
6582 expression->base.type = type_int;
6586 return create_invalid_expression();
6590 * Parses a __builtin_prefetch() expression.
6592 static expression_t *parse_builtin_prefetch(void)
6594 eat(T___builtin_prefetch);
6596 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6599 add_anchor_token(')');
6600 expression->builtin_prefetch.adr = parse_assignment_expression();
6601 if (token.type == ',') {
6603 expression->builtin_prefetch.rw = parse_assignment_expression();
6605 if (token.type == ',') {
6607 expression->builtin_prefetch.locality = parse_assignment_expression();
6609 rem_anchor_token(')');
6611 expression->base.type = type_void;
6615 return create_invalid_expression();
6619 * Parses a __builtin_is_*() compare expression.
6621 static expression_t *parse_compare_builtin(void)
6623 expression_t *expression;
6625 switch(token.type) {
6626 case T___builtin_isgreater:
6627 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6629 case T___builtin_isgreaterequal:
6630 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6632 case T___builtin_isless:
6633 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6635 case T___builtin_islessequal:
6636 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6638 case T___builtin_islessgreater:
6639 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6641 case T___builtin_isunordered:
6642 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6645 internal_errorf(HERE, "invalid compare builtin found");
6648 expression->base.source_position = *HERE;
6652 expression->binary.left = parse_assignment_expression();
6654 expression->binary.right = parse_assignment_expression();
6657 type_t *const orig_type_left = expression->binary.left->base.type;
6658 type_t *const orig_type_right = expression->binary.right->base.type;
6660 type_t *const type_left = skip_typeref(orig_type_left);
6661 type_t *const type_right = skip_typeref(orig_type_right);
6662 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6663 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6664 type_error_incompatible("invalid operands in comparison",
6665 &expression->base.source_position, orig_type_left, orig_type_right);
6668 semantic_comparison(&expression->binary);
6673 return create_invalid_expression();
6678 * Parses a __builtin_expect() expression.
6680 static expression_t *parse_builtin_expect(void)
6682 eat(T___builtin_expect);
6684 expression_t *expression
6685 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6688 expression->binary.left = parse_assignment_expression();
6690 expression->binary.right = parse_constant_expression();
6693 expression->base.type = expression->binary.left->base.type;
6697 return create_invalid_expression();
6702 * Parses a MS assume() expression.
6704 static expression_t *parse_assume(void)
6708 expression_t *expression
6709 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6712 add_anchor_token(')');
6713 expression->unary.value = parse_assignment_expression();
6714 rem_anchor_token(')');
6717 expression->base.type = type_void;
6720 return create_invalid_expression();
6724 * Return the declaration for a given label symbol or create a new one.
6726 * @param symbol the symbol of the label
6728 static declaration_t *get_label(symbol_t *symbol)
6730 declaration_t *candidate;
6731 assert(current_function != NULL);
6733 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6734 /* if we found a local label, we already created the declaration */
6735 if (candidate != NULL) {
6736 if (candidate->parent_scope != scope) {
6737 assert(candidate->parent_scope->depth < scope->depth);
6738 current_function->goto_to_outer = true;
6743 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6744 /* if we found a label in the same function, then we already created the
6746 if (candidate != NULL
6747 && candidate->parent_scope == ¤t_function->scope) {
6751 /* otherwise we need to create a new one */
6752 declaration_t *const declaration = allocate_declaration_zero();
6753 declaration->namespc = NAMESPACE_LABEL;
6754 declaration->symbol = symbol;
6756 label_push(declaration);
6762 * Parses a GNU && label address expression.
6764 static expression_t *parse_label_address(void)
6766 source_position_t source_position = token.source_position;
6768 if (token.type != T_IDENTIFIER) {
6769 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6772 symbol_t *symbol = token.v.symbol;
6775 declaration_t *label = get_label(symbol);
6778 label->address_taken = true;
6780 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6781 expression->base.source_position = source_position;
6783 /* label address is threaten as a void pointer */
6784 expression->base.type = type_void_ptr;
6785 expression->label_address.declaration = label;
6788 return create_invalid_expression();
6792 * Parse a microsoft __noop expression.
6794 static expression_t *parse_noop_expression(void)
6796 source_position_t source_position = *HERE;
6799 if (token.type == '(') {
6800 /* parse arguments */
6802 add_anchor_token(')');
6803 add_anchor_token(',');
6805 if (token.type != ')') {
6807 (void)parse_assignment_expression();
6808 if (token.type != ',')
6814 rem_anchor_token(',');
6815 rem_anchor_token(')');
6818 /* the result is a (int)0 */
6819 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6820 cnst->base.source_position = source_position;
6821 cnst->base.type = type_int;
6822 cnst->conste.v.int_value = 0;
6823 cnst->conste.is_ms_noop = true;
6828 return create_invalid_expression();
6832 * Parses a primary expression.
6834 static expression_t *parse_primary_expression(void)
6836 switch (token.type) {
6837 case T_INTEGER: return parse_int_const();
6838 case T_CHARACTER_CONSTANT: return parse_character_constant();
6839 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6840 case T_FLOATINGPOINT: return parse_float_const();
6841 case T_STRING_LITERAL:
6842 case T_WIDE_STRING_LITERAL: return parse_string_const();
6843 case T_IDENTIFIER: return parse_reference();
6844 case T___FUNCTION__:
6845 case T___func__: return parse_function_keyword();
6846 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6847 case T___FUNCSIG__: return parse_funcsig_keyword();
6848 case T___FUNCDNAME__: return parse_funcdname_keyword();
6849 case T___builtin_offsetof: return parse_offsetof();
6850 case T___builtin_va_start: return parse_va_start();
6851 case T___builtin_va_arg: return parse_va_arg();
6852 case T___builtin_expect:
6853 case T___builtin_alloca:
6854 case T___builtin_nan:
6855 case T___builtin_nand:
6856 case T___builtin_nanf:
6857 case T___builtin_huge_val:
6858 case T___builtin_va_end: return parse_builtin_symbol();
6859 case T___builtin_isgreater:
6860 case T___builtin_isgreaterequal:
6861 case T___builtin_isless:
6862 case T___builtin_islessequal:
6863 case T___builtin_islessgreater:
6864 case T___builtin_isunordered: return parse_compare_builtin();
6865 case T___builtin_constant_p: return parse_builtin_constant();
6866 case T___builtin_prefetch: return parse_builtin_prefetch();
6867 case T__assume: return parse_assume();
6870 return parse_label_address();
6873 case '(': return parse_parenthesized_expression();
6874 case T___noop: return parse_noop_expression();
6877 errorf(HERE, "unexpected token %K, expected an expression", &token);
6878 return create_invalid_expression();
6882 * Check if the expression has the character type and issue a warning then.
6884 static void check_for_char_index_type(const expression_t *expression)
6886 type_t *const type = expression->base.type;
6887 const type_t *const base_type = skip_typeref(type);
6889 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6890 warning.char_subscripts) {
6891 warningf(&expression->base.source_position,
6892 "array subscript has type '%T'", type);
6896 static expression_t *parse_array_expression(unsigned precedence,
6902 add_anchor_token(']');
6904 expression_t *inside = parse_expression();
6906 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6908 array_access_expression_t *array_access = &expression->array_access;
6910 type_t *const orig_type_left = left->base.type;
6911 type_t *const orig_type_inside = inside->base.type;
6913 type_t *const type_left = skip_typeref(orig_type_left);
6914 type_t *const type_inside = skip_typeref(orig_type_inside);
6916 type_t *return_type;
6917 if (is_type_pointer(type_left)) {
6918 return_type = type_left->pointer.points_to;
6919 array_access->array_ref = left;
6920 array_access->index = inside;
6921 check_for_char_index_type(inside);
6922 } else if (is_type_pointer(type_inside)) {
6923 return_type = type_inside->pointer.points_to;
6924 array_access->array_ref = inside;
6925 array_access->index = left;
6926 array_access->flipped = true;
6927 check_for_char_index_type(left);
6929 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6931 "array access on object with non-pointer types '%T', '%T'",
6932 orig_type_left, orig_type_inside);
6934 return_type = type_error_type;
6935 array_access->array_ref = left;
6936 array_access->index = inside;
6939 expression->base.type = automatic_type_conversion(return_type);
6941 rem_anchor_token(']');
6942 if (token.type == ']') {
6945 parse_error_expected("Problem while parsing array access", ']', NULL);
6950 static expression_t *parse_typeprop(expression_kind_t const kind,
6951 source_position_t const pos,
6952 unsigned const precedence)
6954 expression_t *tp_expression = allocate_expression_zero(kind);
6955 tp_expression->base.type = type_size_t;
6956 tp_expression->base.source_position = pos;
6958 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6960 /* we only refer to a type property, mark this case */
6961 bool old = in_type_prop;
6962 in_type_prop = true;
6963 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6965 add_anchor_token(')');
6966 type_t* const orig_type = parse_typename();
6967 tp_expression->typeprop.type = orig_type;
6969 type_t const* const type = skip_typeref(orig_type);
6970 char const* const wrong_type =
6971 is_type_incomplete(type) ? "incomplete" :
6972 type->kind == TYPE_FUNCTION ? "function designator" :
6973 type->kind == TYPE_BITFIELD ? "bitfield" :
6975 if (wrong_type != NULL) {
6976 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6977 what, wrong_type, type);
6980 rem_anchor_token(')');
6983 expression_t *expression = parse_sub_expression(precedence);
6985 type_t* const orig_type = revert_automatic_type_conversion(expression);
6986 expression->base.type = orig_type;
6988 type_t const* const type = skip_typeref(orig_type);
6989 char const* const wrong_type =
6990 is_type_incomplete(type) ? "incomplete" :
6991 type->kind == TYPE_FUNCTION ? "function designator" :
6992 type->kind == TYPE_BITFIELD ? "bitfield" :
6994 if (wrong_type != NULL) {
6995 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6998 tp_expression->typeprop.type = expression->base.type;
6999 tp_expression->typeprop.tp_expression = expression;
7004 return tp_expression;
7007 static expression_t *parse_sizeof(unsigned precedence)
7009 source_position_t pos = *HERE;
7011 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
7014 static expression_t *parse_alignof(unsigned precedence)
7016 source_position_t pos = *HERE;
7018 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
7021 static expression_t *parse_select_expression(unsigned precedence,
7022 expression_t *compound)
7025 assert(token.type == '.' || token.type == T_MINUSGREATER);
7027 bool is_pointer = (token.type == T_MINUSGREATER);
7030 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7031 select->select.compound = compound;
7033 if (token.type != T_IDENTIFIER) {
7034 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7037 symbol_t *symbol = token.v.symbol;
7040 type_t *const orig_type = compound->base.type;
7041 type_t *const type = skip_typeref(orig_type);
7044 bool saw_error = false;
7045 if (is_type_pointer(type)) {
7048 "request for member '%Y' in something not a struct or union, but '%T'",
7052 type_left = skip_typeref(type->pointer.points_to);
7054 if (is_pointer && is_type_valid(type)) {
7055 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7061 declaration_t *entry;
7062 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7063 type_left->kind == TYPE_COMPOUND_UNION) {
7064 declaration_t *const declaration = type_left->compound.declaration;
7066 if (!declaration->init.complete) {
7067 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7069 goto create_error_entry;
7072 entry = find_compound_entry(declaration, symbol);
7073 if (entry == NULL) {
7074 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7075 goto create_error_entry;
7078 if (is_type_valid(type_left) && !saw_error) {
7080 "request for member '%Y' in something not a struct or union, but '%T'",
7084 entry = allocate_declaration_zero();
7085 entry->symbol = symbol;
7088 select->select.compound_entry = entry;
7090 type_t *const res_type =
7091 get_qualified_type(entry->type, type_left->base.qualifiers);
7093 /* we always do the auto-type conversions; the & and sizeof parser contains
7094 * code to revert this! */
7095 select->base.type = automatic_type_conversion(res_type);
7097 type_t *skipped = skip_typeref(res_type);
7098 if (skipped->kind == TYPE_BITFIELD) {
7099 select->base.type = skipped->bitfield.base_type;
7105 static void check_call_argument(const function_parameter_t *parameter,
7106 call_argument_t *argument, unsigned pos)
7108 type_t *expected_type = parameter->type;
7109 type_t *expected_type_skip = skip_typeref(expected_type);
7110 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7111 expression_t *arg_expr = argument->expression;
7112 type_t *arg_type = skip_typeref(arg_expr->base.type);
7114 /* handle transparent union gnu extension */
7115 if (is_type_union(expected_type_skip)
7116 && (expected_type_skip->base.modifiers
7117 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7118 declaration_t *union_decl = expected_type_skip->compound.declaration;
7120 declaration_t *declaration = union_decl->scope.declarations;
7121 type_t *best_type = NULL;
7122 for ( ; declaration != NULL; declaration = declaration->next) {
7123 type_t *decl_type = declaration->type;
7124 error = semantic_assign(decl_type, arg_expr);
7125 if (error == ASSIGN_ERROR_INCOMPATIBLE
7126 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7129 if (error == ASSIGN_SUCCESS) {
7130 best_type = decl_type;
7131 } else if (best_type == NULL) {
7132 best_type = decl_type;
7136 if (best_type != NULL) {
7137 expected_type = best_type;
7141 error = semantic_assign(expected_type, arg_expr);
7142 argument->expression = create_implicit_cast(argument->expression,
7145 if (error != ASSIGN_SUCCESS) {
7146 /* report exact scope in error messages (like "in argument 3") */
7148 snprintf(buf, sizeof(buf), "call argument %u", pos);
7149 report_assign_error(error, expected_type, arg_expr, buf,
7150 &arg_expr->base.source_position);
7151 } else if (warning.traditional || warning.conversion) {
7152 type_t *const promoted_type = get_default_promoted_type(arg_type);
7153 if (!types_compatible(expected_type_skip, promoted_type) &&
7154 !types_compatible(expected_type_skip, type_void_ptr) &&
7155 !types_compatible(type_void_ptr, promoted_type)) {
7156 /* Deliberately show the skipped types in this warning */
7157 warningf(&arg_expr->base.source_position,
7158 "passing call argument %u as '%T' rather than '%T' due to prototype",
7159 pos, expected_type_skip, promoted_type);
7165 * Parse a call expression, ie. expression '( ... )'.
7167 * @param expression the function address
7169 static expression_t *parse_call_expression(unsigned precedence,
7170 expression_t *expression)
7173 expression_t *result = allocate_expression_zero(EXPR_CALL);
7174 result->base.source_position = expression->base.source_position;
7176 call_expression_t *call = &result->call;
7177 call->function = expression;
7179 type_t *const orig_type = expression->base.type;
7180 type_t *const type = skip_typeref(orig_type);
7182 function_type_t *function_type = NULL;
7183 if (is_type_pointer(type)) {
7184 type_t *const to_type = skip_typeref(type->pointer.points_to);
7186 if (is_type_function(to_type)) {
7187 function_type = &to_type->function;
7188 call->base.type = function_type->return_type;
7192 if (function_type == NULL && is_type_valid(type)) {
7193 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7196 /* parse arguments */
7198 add_anchor_token(')');
7199 add_anchor_token(',');
7201 if (token.type != ')') {
7202 call_argument_t *last_argument = NULL;
7205 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7207 argument->expression = parse_assignment_expression();
7208 if (last_argument == NULL) {
7209 call->arguments = argument;
7211 last_argument->next = argument;
7213 last_argument = argument;
7215 if (token.type != ',')
7220 rem_anchor_token(',');
7221 rem_anchor_token(')');
7224 if (function_type == NULL)
7227 function_parameter_t *parameter = function_type->parameters;
7228 call_argument_t *argument = call->arguments;
7229 if (!function_type->unspecified_parameters) {
7230 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7231 parameter = parameter->next, argument = argument->next) {
7232 check_call_argument(parameter, argument, ++pos);
7235 if (parameter != NULL) {
7236 errorf(HERE, "too few arguments to function '%E'", expression);
7237 } else if (argument != NULL && !function_type->variadic) {
7238 errorf(HERE, "too many arguments to function '%E'", expression);
7242 /* do default promotion */
7243 for( ; argument != NULL; argument = argument->next) {
7244 type_t *type = argument->expression->base.type;
7246 type = get_default_promoted_type(type);
7248 argument->expression
7249 = create_implicit_cast(argument->expression, type);
7252 check_format(&result->call);
7254 if (warning.aggregate_return &&
7255 is_type_compound(skip_typeref(function_type->return_type))) {
7256 warningf(&result->base.source_position,
7257 "function call has aggregate value");
7264 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7266 static bool same_compound_type(const type_t *type1, const type_t *type2)
7269 is_type_compound(type1) &&
7270 type1->kind == type2->kind &&
7271 type1->compound.declaration == type2->compound.declaration;
7275 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7277 * @param expression the conditional expression
7279 static expression_t *parse_conditional_expression(unsigned precedence,
7280 expression_t *expression)
7282 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7284 conditional_expression_t *conditional = &result->conditional;
7285 conditional->base.source_position = *HERE;
7286 conditional->condition = expression;
7289 add_anchor_token(':');
7292 type_t *const condition_type_orig = expression->base.type;
7293 type_t *const condition_type = skip_typeref(condition_type_orig);
7294 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7295 type_error("expected a scalar type in conditional condition",
7296 &expression->base.source_position, condition_type_orig);
7299 expression_t *true_expression = expression;
7300 bool gnu_cond = false;
7301 if (GNU_MODE && token.type == ':') {
7304 true_expression = parse_expression();
7305 rem_anchor_token(':');
7307 expression_t *false_expression = parse_sub_expression(precedence);
7309 type_t *const orig_true_type = true_expression->base.type;
7310 type_t *const orig_false_type = false_expression->base.type;
7311 type_t *const true_type = skip_typeref(orig_true_type);
7312 type_t *const false_type = skip_typeref(orig_false_type);
7315 type_t *result_type;
7316 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7317 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7318 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7319 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7320 warningf(&conditional->base.source_position,
7321 "ISO C forbids conditional expression with only one void side");
7323 result_type = type_void;
7324 } else if (is_type_arithmetic(true_type)
7325 && is_type_arithmetic(false_type)) {
7326 result_type = semantic_arithmetic(true_type, false_type);
7328 true_expression = create_implicit_cast(true_expression, result_type);
7329 false_expression = create_implicit_cast(false_expression, result_type);
7331 conditional->true_expression = true_expression;
7332 conditional->false_expression = false_expression;
7333 conditional->base.type = result_type;
7334 } else if (same_compound_type(true_type, false_type)) {
7335 /* just take 1 of the 2 types */
7336 result_type = true_type;
7337 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7338 type_t *pointer_type;
7340 expression_t *other_expression;
7341 if (is_type_pointer(true_type) &&
7342 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7343 pointer_type = true_type;
7344 other_type = false_type;
7345 other_expression = false_expression;
7347 pointer_type = false_type;
7348 other_type = true_type;
7349 other_expression = true_expression;
7352 if (is_null_pointer_constant(other_expression)) {
7353 result_type = pointer_type;
7354 } else if (is_type_pointer(other_type)) {
7355 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7356 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7359 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7360 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7362 } else if (types_compatible(get_unqualified_type(to1),
7363 get_unqualified_type(to2))) {
7366 warningf(&conditional->base.source_position,
7367 "pointer types '%T' and '%T' in conditional expression are incompatible",
7368 true_type, false_type);
7372 type_t *const type =
7373 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7374 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7375 } else if (is_type_integer(other_type)) {
7376 warningf(&conditional->base.source_position,
7377 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7378 result_type = pointer_type;
7380 type_error_incompatible("while parsing conditional",
7381 &expression->base.source_position, true_type, false_type);
7382 result_type = type_error_type;
7385 /* TODO: one pointer to void*, other some pointer */
7387 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7388 type_error_incompatible("while parsing conditional",
7389 &conditional->base.source_position, true_type,
7392 result_type = type_error_type;
7395 conditional->true_expression
7396 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7397 conditional->false_expression
7398 = create_implicit_cast(false_expression, result_type);
7399 conditional->base.type = result_type;
7402 return create_invalid_expression();
7406 * Parse an extension expression.
7408 static expression_t *parse_extension(unsigned precedence)
7410 eat(T___extension__);
7412 bool old_gcc_extension = in_gcc_extension;
7413 in_gcc_extension = true;
7414 expression_t *expression = parse_sub_expression(precedence);
7415 in_gcc_extension = old_gcc_extension;
7420 * Parse a __builtin_classify_type() expression.
7422 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7424 eat(T___builtin_classify_type);
7426 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7427 result->base.type = type_int;
7430 add_anchor_token(')');
7431 expression_t *expression = parse_sub_expression(precedence);
7432 rem_anchor_token(')');
7434 result->classify_type.type_expression = expression;
7438 return create_invalid_expression();
7441 static bool check_pointer_arithmetic(const source_position_t *source_position,
7442 type_t *pointer_type,
7443 type_t *orig_pointer_type)
7445 type_t *points_to = pointer_type->pointer.points_to;
7446 points_to = skip_typeref(points_to);
7448 if (is_type_incomplete(points_to)) {
7449 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7450 errorf(source_position,
7451 "arithmetic with pointer to incomplete type '%T' not allowed",
7454 } else if (warning.pointer_arith) {
7455 warningf(source_position,
7456 "pointer of type '%T' used in arithmetic",
7459 } else if (is_type_function(points_to)) {
7461 errorf(source_position,
7462 "arithmetic with pointer to function type '%T' not allowed",
7465 } else if (warning.pointer_arith) {
7466 warningf(source_position,
7467 "pointer to a function '%T' used in arithmetic",
7474 static bool is_lvalue(const expression_t *expression)
7476 switch (expression->kind) {
7477 case EXPR_REFERENCE:
7478 case EXPR_ARRAY_ACCESS:
7480 case EXPR_UNARY_DEREFERENCE:
7488 static void semantic_incdec(unary_expression_t *expression)
7490 type_t *const orig_type = expression->value->base.type;
7491 type_t *const type = skip_typeref(orig_type);
7492 if (is_type_pointer(type)) {
7493 if (!check_pointer_arithmetic(&expression->base.source_position,
7497 } else if (!is_type_real(type) && is_type_valid(type)) {
7498 /* TODO: improve error message */
7499 errorf(&expression->base.source_position,
7500 "operation needs an arithmetic or pointer type");
7503 if (!is_lvalue(expression->value)) {
7504 /* TODO: improve error message */
7505 errorf(&expression->base.source_position, "lvalue required as operand");
7507 expression->base.type = orig_type;
7510 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7512 type_t *const orig_type = expression->value->base.type;
7513 type_t *const type = skip_typeref(orig_type);
7514 if (!is_type_arithmetic(type)) {
7515 if (is_type_valid(type)) {
7516 /* TODO: improve error message */
7517 errorf(&expression->base.source_position,
7518 "operation needs an arithmetic type");
7523 expression->base.type = orig_type;
7526 static void semantic_unexpr_plus(unary_expression_t *expression)
7528 semantic_unexpr_arithmetic(expression);
7529 if (warning.traditional)
7530 warningf(&expression->base.source_position,
7531 "traditional C rejects the unary plus operator");
7534 static expression_t const *get_reference_address(expression_t const *expr)
7536 bool regular_take_address = true;
7538 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7539 expr = expr->unary.value;
7541 regular_take_address = false;
7544 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7547 expr = expr->unary.value;
7550 if (expr->kind != EXPR_REFERENCE)
7553 if (!regular_take_address &&
7554 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7561 static void warn_function_address_as_bool(expression_t const* expr)
7563 if (!warning.address)
7566 expr = get_reference_address(expr);
7568 warningf(&expr->base.source_position,
7569 "the address of '%Y' will always evaluate as 'true'",
7570 expr->reference.declaration->symbol);
7574 static void semantic_not(unary_expression_t *expression)
7576 type_t *const orig_type = expression->value->base.type;
7577 type_t *const type = skip_typeref(orig_type);
7578 if (!is_type_scalar(type) && is_type_valid(type)) {
7579 errorf(&expression->base.source_position,
7580 "operand of ! must be of scalar type");
7583 warn_function_address_as_bool(expression->value);
7585 expression->base.type = type_int;
7588 static void semantic_unexpr_integer(unary_expression_t *expression)
7590 type_t *const orig_type = expression->value->base.type;
7591 type_t *const type = skip_typeref(orig_type);
7592 if (!is_type_integer(type)) {
7593 if (is_type_valid(type)) {
7594 errorf(&expression->base.source_position,
7595 "operand of ~ must be of integer type");
7600 expression->base.type = orig_type;
7603 static void semantic_dereference(unary_expression_t *expression)
7605 type_t *const orig_type = expression->value->base.type;
7606 type_t *const type = skip_typeref(orig_type);
7607 if (!is_type_pointer(type)) {
7608 if (is_type_valid(type)) {
7609 errorf(&expression->base.source_position,
7610 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7615 type_t *result_type = type->pointer.points_to;
7616 result_type = automatic_type_conversion(result_type);
7617 expression->base.type = result_type;
7621 * Record that an address is taken (expression represents an lvalue).
7623 * @param expression the expression
7624 * @param may_be_register if true, the expression might be an register
7626 static void set_address_taken(expression_t *expression, bool may_be_register)
7628 if (expression->kind != EXPR_REFERENCE)
7631 declaration_t *const declaration = expression->reference.declaration;
7632 /* happens for parse errors */
7633 if (declaration == NULL)
7636 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7637 errorf(&expression->base.source_position,
7638 "address of register variable '%Y' requested",
7639 declaration->symbol);
7641 declaration->address_taken = 1;
7646 * Check the semantic of the address taken expression.
7648 static void semantic_take_addr(unary_expression_t *expression)
7650 expression_t *value = expression->value;
7651 value->base.type = revert_automatic_type_conversion(value);
7653 type_t *orig_type = value->base.type;
7654 if (!is_type_valid(orig_type))
7657 set_address_taken(value, false);
7659 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7662 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7663 static expression_t *parse_##unexpression_type(unsigned precedence) \
7665 expression_t *unary_expression \
7666 = allocate_expression_zero(unexpression_type); \
7667 unary_expression->base.source_position = *HERE; \
7669 unary_expression->unary.value = parse_sub_expression(precedence); \
7671 sfunc(&unary_expression->unary); \
7673 return unary_expression; \
7676 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7677 semantic_unexpr_arithmetic)
7678 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7679 semantic_unexpr_plus)
7680 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7682 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7683 semantic_dereference)
7684 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7686 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7687 semantic_unexpr_integer)
7688 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7690 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7693 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7695 static expression_t *parse_##unexpression_type(unsigned precedence, \
7696 expression_t *left) \
7698 (void) precedence; \
7700 expression_t *unary_expression \
7701 = allocate_expression_zero(unexpression_type); \
7702 unary_expression->base.source_position = *HERE; \
7704 unary_expression->unary.value = left; \
7706 sfunc(&unary_expression->unary); \
7708 return unary_expression; \
7711 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7712 EXPR_UNARY_POSTFIX_INCREMENT,
7714 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7715 EXPR_UNARY_POSTFIX_DECREMENT,
7718 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7720 /* TODO: handle complex + imaginary types */
7722 type_left = get_unqualified_type(type_left);
7723 type_right = get_unqualified_type(type_right);
7725 /* § 6.3.1.8 Usual arithmetic conversions */
7726 if (type_left == type_long_double || type_right == type_long_double) {
7727 return type_long_double;
7728 } else if (type_left == type_double || type_right == type_double) {
7730 } else if (type_left == type_float || type_right == type_float) {
7734 type_left = promote_integer(type_left);
7735 type_right = promote_integer(type_right);
7737 if (type_left == type_right)
7740 bool const signed_left = is_type_signed(type_left);
7741 bool const signed_right = is_type_signed(type_right);
7742 int const rank_left = get_rank(type_left);
7743 int const rank_right = get_rank(type_right);
7745 if (signed_left == signed_right)
7746 return rank_left >= rank_right ? type_left : type_right;
7755 u_rank = rank_right;
7756 u_type = type_right;
7758 s_rank = rank_right;
7759 s_type = type_right;
7764 if (u_rank >= s_rank)
7767 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7769 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7770 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7774 case ATOMIC_TYPE_INT: return type_unsigned_int;
7775 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7776 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7778 default: panic("invalid atomic type");
7783 * Check the semantic restrictions for a binary expression.
7785 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7787 expression_t *const left = expression->left;
7788 expression_t *const right = expression->right;
7789 type_t *const orig_type_left = left->base.type;
7790 type_t *const orig_type_right = right->base.type;
7791 type_t *const type_left = skip_typeref(orig_type_left);
7792 type_t *const type_right = skip_typeref(orig_type_right);
7794 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7795 /* TODO: improve error message */
7796 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7797 errorf(&expression->base.source_position,
7798 "operation needs arithmetic types");
7803 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7804 expression->left = create_implicit_cast(left, arithmetic_type);
7805 expression->right = create_implicit_cast(right, arithmetic_type);
7806 expression->base.type = arithmetic_type;
7809 static void warn_div_by_zero(binary_expression_t const *const expression)
7811 if (!warning.div_by_zero ||
7812 !is_type_integer(expression->base.type))
7815 expression_t const *const right = expression->right;
7816 /* The type of the right operand can be different for /= */
7817 if (is_type_integer(right->base.type) &&
7818 is_constant_expression(right) &&
7819 fold_constant(right) == 0) {
7820 warningf(&expression->base.source_position, "division by zero");
7825 * Check the semantic restrictions for a div/mod expression.
7827 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7828 semantic_binexpr_arithmetic(expression);
7829 warn_div_by_zero(expression);
7832 static void semantic_shift_op(binary_expression_t *expression)
7834 expression_t *const left = expression->left;
7835 expression_t *const right = expression->right;
7836 type_t *const orig_type_left = left->base.type;
7837 type_t *const orig_type_right = right->base.type;
7838 type_t * type_left = skip_typeref(orig_type_left);
7839 type_t * type_right = skip_typeref(orig_type_right);
7841 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7842 /* TODO: improve error message */
7843 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7844 errorf(&expression->base.source_position,
7845 "operands of shift operation must have integer types");
7850 type_left = promote_integer(type_left);
7851 type_right = promote_integer(type_right);
7853 expression->left = create_implicit_cast(left, type_left);
7854 expression->right = create_implicit_cast(right, type_right);
7855 expression->base.type = type_left;
7858 static void semantic_add(binary_expression_t *expression)
7860 expression_t *const left = expression->left;
7861 expression_t *const right = expression->right;
7862 type_t *const orig_type_left = left->base.type;
7863 type_t *const orig_type_right = right->base.type;
7864 type_t *const type_left = skip_typeref(orig_type_left);
7865 type_t *const type_right = skip_typeref(orig_type_right);
7868 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7869 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7870 expression->left = create_implicit_cast(left, arithmetic_type);
7871 expression->right = create_implicit_cast(right, arithmetic_type);
7872 expression->base.type = arithmetic_type;
7874 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7875 check_pointer_arithmetic(&expression->base.source_position,
7876 type_left, orig_type_left);
7877 expression->base.type = type_left;
7878 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7879 check_pointer_arithmetic(&expression->base.source_position,
7880 type_right, orig_type_right);
7881 expression->base.type = type_right;
7882 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7883 errorf(&expression->base.source_position,
7884 "invalid operands to binary + ('%T', '%T')",
7885 orig_type_left, orig_type_right);
7889 static void semantic_sub(binary_expression_t *expression)
7891 expression_t *const left = expression->left;
7892 expression_t *const right = expression->right;
7893 type_t *const orig_type_left = left->base.type;
7894 type_t *const orig_type_right = right->base.type;
7895 type_t *const type_left = skip_typeref(orig_type_left);
7896 type_t *const type_right = skip_typeref(orig_type_right);
7897 source_position_t const *const pos = &expression->base.source_position;
7900 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7901 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7902 expression->left = create_implicit_cast(left, arithmetic_type);
7903 expression->right = create_implicit_cast(right, arithmetic_type);
7904 expression->base.type = arithmetic_type;
7906 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7907 check_pointer_arithmetic(&expression->base.source_position,
7908 type_left, orig_type_left);
7909 expression->base.type = type_left;
7910 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7911 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7912 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7913 if (!types_compatible(unqual_left, unqual_right)) {
7915 "subtracting pointers to incompatible types '%T' and '%T'",
7916 orig_type_left, orig_type_right);
7917 } else if (!is_type_object(unqual_left)) {
7918 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7919 warningf(pos, "subtracting pointers to void");
7921 errorf(pos, "subtracting pointers to non-object types '%T'",
7925 expression->base.type = type_ptrdiff_t;
7926 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7927 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7928 orig_type_left, orig_type_right);
7932 static void warn_string_literal_address(expression_t const* expr)
7934 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7935 expr = expr->unary.value;
7936 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7938 expr = expr->unary.value;
7941 if (expr->kind == EXPR_STRING_LITERAL ||
7942 expr->kind == EXPR_WIDE_STRING_LITERAL) {
7943 warningf(&expr->base.source_position,
7944 "comparison with string literal results in unspecified behaviour");
7949 * Check the semantics of comparison expressions.
7951 * @param expression The expression to check.
7953 static void semantic_comparison(binary_expression_t *expression)
7955 expression_t *left = expression->left;
7956 expression_t *right = expression->right;
7958 if (warning.address) {
7959 warn_string_literal_address(left);
7960 warn_string_literal_address(right);
7962 expression_t const* const func_left = get_reference_address(left);
7963 if (func_left != NULL && is_null_pointer_constant(right)) {
7964 warningf(&expression->base.source_position,
7965 "the address of '%Y' will never be NULL",
7966 func_left->reference.declaration->symbol);
7969 expression_t const* const func_right = get_reference_address(right);
7970 if (func_right != NULL && is_null_pointer_constant(right)) {
7971 warningf(&expression->base.source_position,
7972 "the address of '%Y' will never be NULL",
7973 func_right->reference.declaration->symbol);
7977 type_t *orig_type_left = left->base.type;
7978 type_t *orig_type_right = right->base.type;
7979 type_t *type_left = skip_typeref(orig_type_left);
7980 type_t *type_right = skip_typeref(orig_type_right);
7982 /* TODO non-arithmetic types */
7983 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7984 /* test for signed vs unsigned compares */
7985 if (warning.sign_compare &&
7986 (expression->base.kind != EXPR_BINARY_EQUAL &&
7987 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7988 (is_type_signed(type_left) != is_type_signed(type_right))) {
7990 /* check if 1 of the operands is a constant, in this case we just
7991 * check wether we can safely represent the resulting constant in
7992 * the type of the other operand. */
7993 expression_t *const_expr = NULL;
7994 expression_t *other_expr = NULL;
7996 if (is_constant_expression(left)) {
7999 } else if (is_constant_expression(right)) {
8004 if (const_expr != NULL) {
8005 type_t *other_type = skip_typeref(other_expr->base.type);
8006 long val = fold_constant(const_expr);
8007 /* TODO: check if val can be represented by other_type */
8011 warningf(&expression->base.source_position,
8012 "comparison between signed and unsigned");
8014 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8015 expression->left = create_implicit_cast(left, arithmetic_type);
8016 expression->right = create_implicit_cast(right, arithmetic_type);
8017 expression->base.type = arithmetic_type;
8018 if (warning.float_equal &&
8019 (expression->base.kind == EXPR_BINARY_EQUAL ||
8020 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8021 is_type_float(arithmetic_type)) {
8022 warningf(&expression->base.source_position,
8023 "comparing floating point with == or != is unsafe");
8025 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8026 /* TODO check compatibility */
8027 } else if (is_type_pointer(type_left)) {
8028 expression->right = create_implicit_cast(right, type_left);
8029 } else if (is_type_pointer(type_right)) {
8030 expression->left = create_implicit_cast(left, type_right);
8031 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8032 type_error_incompatible("invalid operands in comparison",
8033 &expression->base.source_position,
8034 type_left, type_right);
8036 expression->base.type = type_int;
8040 * Checks if a compound type has constant fields.
8042 static bool has_const_fields(const compound_type_t *type)
8044 const scope_t *scope = &type->declaration->scope;
8045 const declaration_t *declaration = scope->declarations;
8047 for (; declaration != NULL; declaration = declaration->next) {
8048 if (declaration->namespc != NAMESPACE_NORMAL)
8051 const type_t *decl_type = skip_typeref(declaration->type);
8052 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8059 static bool is_valid_assignment_lhs(expression_t const* const left)
8061 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8062 type_t *const type_left = skip_typeref(orig_type_left);
8064 if (!is_lvalue(left)) {
8065 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8070 if (is_type_array(type_left)) {
8071 errorf(HERE, "cannot assign to arrays ('%E')", left);
8074 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8075 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8079 if (is_type_incomplete(type_left)) {
8080 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8081 left, orig_type_left);
8084 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8085 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8086 left, orig_type_left);
8093 static void semantic_arithmetic_assign(binary_expression_t *expression)
8095 expression_t *left = expression->left;
8096 expression_t *right = expression->right;
8097 type_t *orig_type_left = left->base.type;
8098 type_t *orig_type_right = right->base.type;
8100 if (!is_valid_assignment_lhs(left))
8103 type_t *type_left = skip_typeref(orig_type_left);
8104 type_t *type_right = skip_typeref(orig_type_right);
8106 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8107 /* TODO: improve error message */
8108 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8109 errorf(&expression->base.source_position,
8110 "operation needs arithmetic types");
8115 /* combined instructions are tricky. We can't create an implicit cast on
8116 * the left side, because we need the uncasted form for the store.
8117 * The ast2firm pass has to know that left_type must be right_type
8118 * for the arithmetic operation and create a cast by itself */
8119 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8120 expression->right = create_implicit_cast(right, arithmetic_type);
8121 expression->base.type = type_left;
8124 static void semantic_divmod_assign(binary_expression_t *expression)
8126 semantic_arithmetic_assign(expression);
8127 warn_div_by_zero(expression);
8130 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8132 expression_t *const left = expression->left;
8133 expression_t *const right = expression->right;
8134 type_t *const orig_type_left = left->base.type;
8135 type_t *const orig_type_right = right->base.type;
8136 type_t *const type_left = skip_typeref(orig_type_left);
8137 type_t *const type_right = skip_typeref(orig_type_right);
8139 if (!is_valid_assignment_lhs(left))
8142 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8143 /* combined instructions are tricky. We can't create an implicit cast on
8144 * the left side, because we need the uncasted form for the store.
8145 * The ast2firm pass has to know that left_type must be right_type
8146 * for the arithmetic operation and create a cast by itself */
8147 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8148 expression->right = create_implicit_cast(right, arithmetic_type);
8149 expression->base.type = type_left;
8150 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8151 check_pointer_arithmetic(&expression->base.source_position,
8152 type_left, orig_type_left);
8153 expression->base.type = type_left;
8154 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8155 errorf(&expression->base.source_position,
8156 "incompatible types '%T' and '%T' in assignment",
8157 orig_type_left, orig_type_right);
8162 * Check the semantic restrictions of a logical expression.
8164 static void semantic_logical_op(binary_expression_t *expression)
8166 expression_t *const left = expression->left;
8167 expression_t *const right = expression->right;
8168 type_t *const orig_type_left = left->base.type;
8169 type_t *const orig_type_right = right->base.type;
8170 type_t *const type_left = skip_typeref(orig_type_left);
8171 type_t *const type_right = skip_typeref(orig_type_right);
8173 warn_function_address_as_bool(left);
8174 warn_function_address_as_bool(right);
8176 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8177 /* TODO: improve error message */
8178 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8179 errorf(&expression->base.source_position,
8180 "operation needs scalar types");
8185 expression->base.type = type_int;
8189 * Check the semantic restrictions of a binary assign expression.
8191 static void semantic_binexpr_assign(binary_expression_t *expression)
8193 expression_t *left = expression->left;
8194 type_t *orig_type_left = left->base.type;
8196 if (!is_valid_assignment_lhs(left))
8199 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8200 report_assign_error(error, orig_type_left, expression->right,
8201 "assignment", &left->base.source_position);
8202 expression->right = create_implicit_cast(expression->right, orig_type_left);
8203 expression->base.type = orig_type_left;
8207 * Determine if the outermost operation (or parts thereof) of the given
8208 * expression has no effect in order to generate a warning about this fact.
8209 * Therefore in some cases this only examines some of the operands of the
8210 * expression (see comments in the function and examples below).
8212 * f() + 23; // warning, because + has no effect
8213 * x || f(); // no warning, because x controls execution of f()
8214 * x ? y : f(); // warning, because y has no effect
8215 * (void)x; // no warning to be able to suppress the warning
8216 * This function can NOT be used for an "expression has definitely no effect"-
8218 static bool expression_has_effect(const expression_t *const expr)
8220 switch (expr->kind) {
8221 case EXPR_UNKNOWN: break;
8222 case EXPR_INVALID: return true; /* do NOT warn */
8223 case EXPR_REFERENCE: return false;
8224 /* suppress the warning for microsoft __noop operations */
8225 case EXPR_CONST: return expr->conste.is_ms_noop;
8226 case EXPR_CHARACTER_CONSTANT: return false;
8227 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8228 case EXPR_STRING_LITERAL: return false;
8229 case EXPR_WIDE_STRING_LITERAL: return false;
8230 case EXPR_LABEL_ADDRESS: return false;
8233 const call_expression_t *const call = &expr->call;
8234 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8237 switch (call->function->builtin_symbol.symbol->ID) {
8238 case T___builtin_va_end: return true;
8239 default: return false;
8243 /* Generate the warning if either the left or right hand side of a
8244 * conditional expression has no effect */
8245 case EXPR_CONDITIONAL: {
8246 const conditional_expression_t *const cond = &expr->conditional;
8248 expression_has_effect(cond->true_expression) &&
8249 expression_has_effect(cond->false_expression);
8252 case EXPR_SELECT: return false;
8253 case EXPR_ARRAY_ACCESS: return false;
8254 case EXPR_SIZEOF: return false;
8255 case EXPR_CLASSIFY_TYPE: return false;
8256 case EXPR_ALIGNOF: return false;
8258 case EXPR_FUNCNAME: return false;
8259 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8260 case EXPR_BUILTIN_CONSTANT_P: return false;
8261 case EXPR_BUILTIN_PREFETCH: return true;
8262 case EXPR_OFFSETOF: return false;
8263 case EXPR_VA_START: return true;
8264 case EXPR_VA_ARG: return true;
8265 case EXPR_STATEMENT: return true; // TODO
8266 case EXPR_COMPOUND_LITERAL: return false;
8268 case EXPR_UNARY_NEGATE: return false;
8269 case EXPR_UNARY_PLUS: return false;
8270 case EXPR_UNARY_BITWISE_NEGATE: return false;
8271 case EXPR_UNARY_NOT: return false;
8272 case EXPR_UNARY_DEREFERENCE: return false;
8273 case EXPR_UNARY_TAKE_ADDRESS: return false;
8274 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8275 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8276 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8277 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8279 /* Treat void casts as if they have an effect in order to being able to
8280 * suppress the warning */
8281 case EXPR_UNARY_CAST: {
8282 type_t *const type = skip_typeref(expr->base.type);
8283 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8286 case EXPR_UNARY_CAST_IMPLICIT: return true;
8287 case EXPR_UNARY_ASSUME: return true;
8289 case EXPR_BINARY_ADD: return false;
8290 case EXPR_BINARY_SUB: return false;
8291 case EXPR_BINARY_MUL: return false;
8292 case EXPR_BINARY_DIV: return false;
8293 case EXPR_BINARY_MOD: return false;
8294 case EXPR_BINARY_EQUAL: return false;
8295 case EXPR_BINARY_NOTEQUAL: return false;
8296 case EXPR_BINARY_LESS: return false;
8297 case EXPR_BINARY_LESSEQUAL: return false;
8298 case EXPR_BINARY_GREATER: return false;
8299 case EXPR_BINARY_GREATEREQUAL: return false;
8300 case EXPR_BINARY_BITWISE_AND: return false;
8301 case EXPR_BINARY_BITWISE_OR: return false;
8302 case EXPR_BINARY_BITWISE_XOR: return false;
8303 case EXPR_BINARY_SHIFTLEFT: return false;
8304 case EXPR_BINARY_SHIFTRIGHT: return false;
8305 case EXPR_BINARY_ASSIGN: return true;
8306 case EXPR_BINARY_MUL_ASSIGN: return true;
8307 case EXPR_BINARY_DIV_ASSIGN: return true;
8308 case EXPR_BINARY_MOD_ASSIGN: return true;
8309 case EXPR_BINARY_ADD_ASSIGN: return true;
8310 case EXPR_BINARY_SUB_ASSIGN: return true;
8311 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8312 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8313 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8314 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8315 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8317 /* Only examine the right hand side of && and ||, because the left hand
8318 * side already has the effect of controlling the execution of the right
8320 case EXPR_BINARY_LOGICAL_AND:
8321 case EXPR_BINARY_LOGICAL_OR:
8322 /* Only examine the right hand side of a comma expression, because the left
8323 * hand side has a separate warning */
8324 case EXPR_BINARY_COMMA:
8325 return expression_has_effect(expr->binary.right);
8327 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8328 case EXPR_BINARY_ISGREATER: return false;
8329 case EXPR_BINARY_ISGREATEREQUAL: return false;
8330 case EXPR_BINARY_ISLESS: return false;
8331 case EXPR_BINARY_ISLESSEQUAL: return false;
8332 case EXPR_BINARY_ISLESSGREATER: return false;
8333 case EXPR_BINARY_ISUNORDERED: return false;
8336 internal_errorf(HERE, "unexpected expression");
8339 static void semantic_comma(binary_expression_t *expression)
8341 if (warning.unused_value) {
8342 const expression_t *const left = expression->left;
8343 if (!expression_has_effect(left)) {
8344 warningf(&left->base.source_position,
8345 "left-hand operand of comma expression has no effect");
8348 expression->base.type = expression->right->base.type;
8351 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8352 static expression_t *parse_##binexpression_type(unsigned precedence, \
8353 expression_t *left) \
8355 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8356 binexpr->base.source_position = *HERE; \
8357 binexpr->binary.left = left; \
8360 expression_t *right = parse_sub_expression(precedence + lr); \
8362 binexpr->binary.right = right; \
8363 sfunc(&binexpr->binary); \
8368 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8369 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8370 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8371 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8372 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8373 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8374 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8375 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8376 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8378 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8379 semantic_comparison, 1)
8380 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8381 semantic_comparison, 1)
8382 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8383 semantic_comparison, 1)
8384 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8385 semantic_comparison, 1)
8387 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8388 semantic_binexpr_arithmetic, 1)
8389 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8390 semantic_binexpr_arithmetic, 1)
8391 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8392 semantic_binexpr_arithmetic, 1)
8393 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8394 semantic_logical_op, 1)
8395 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8396 semantic_logical_op, 1)
8397 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8398 semantic_shift_op, 1)
8399 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8400 semantic_shift_op, 1)
8401 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8402 semantic_arithmetic_addsubb_assign, 0)
8403 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8404 semantic_arithmetic_addsubb_assign, 0)
8405 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8406 semantic_arithmetic_assign, 0)
8407 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8408 semantic_divmod_assign, 0)
8409 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8410 semantic_divmod_assign, 0)
8411 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8412 semantic_arithmetic_assign, 0)
8413 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8414 semantic_arithmetic_assign, 0)
8415 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8416 semantic_arithmetic_assign, 0)
8417 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8418 semantic_arithmetic_assign, 0)
8419 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8420 semantic_arithmetic_assign, 0)
8422 static expression_t *parse_sub_expression(unsigned precedence)
8424 if (token.type < 0) {
8425 return expected_expression_error();
8428 expression_parser_function_t *parser
8429 = &expression_parsers[token.type];
8430 source_position_t source_position = token.source_position;
8433 if (parser->parser != NULL) {
8434 left = parser->parser(parser->precedence);
8436 left = parse_primary_expression();
8438 assert(left != NULL);
8439 left->base.source_position = source_position;
8442 if (token.type < 0) {
8443 return expected_expression_error();
8446 parser = &expression_parsers[token.type];
8447 if (parser->infix_parser == NULL)
8449 if (parser->infix_precedence < precedence)
8452 left = parser->infix_parser(parser->infix_precedence, left);
8454 assert(left != NULL);
8455 assert(left->kind != EXPR_UNKNOWN);
8456 left->base.source_position = source_position;
8463 * Parse an expression.
8465 static expression_t *parse_expression(void)
8467 return parse_sub_expression(1);
8471 * Register a parser for a prefix-like operator with given precedence.
8473 * @param parser the parser function
8474 * @param token_type the token type of the prefix token
8475 * @param precedence the precedence of the operator
8477 static void register_expression_parser(parse_expression_function parser,
8478 int token_type, unsigned precedence)
8480 expression_parser_function_t *entry = &expression_parsers[token_type];
8482 if (entry->parser != NULL) {
8483 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8484 panic("trying to register multiple expression parsers for a token");
8486 entry->parser = parser;
8487 entry->precedence = precedence;
8491 * Register a parser for an infix operator with given precedence.
8493 * @param parser the parser function
8494 * @param token_type the token type of the infix operator
8495 * @param precedence the precedence of the operator
8497 static void register_infix_parser(parse_expression_infix_function parser,
8498 int token_type, unsigned precedence)
8500 expression_parser_function_t *entry = &expression_parsers[token_type];
8502 if (entry->infix_parser != NULL) {
8503 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8504 panic("trying to register multiple infix expression parsers for a "
8507 entry->infix_parser = parser;
8508 entry->infix_precedence = precedence;
8512 * Initialize the expression parsers.
8514 static void init_expression_parsers(void)
8516 memset(&expression_parsers, 0, sizeof(expression_parsers));
8518 register_infix_parser(parse_array_expression, '[', 30);
8519 register_infix_parser(parse_call_expression, '(', 30);
8520 register_infix_parser(parse_select_expression, '.', 30);
8521 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8522 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8524 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8527 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8528 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8529 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8530 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8531 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8532 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8533 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8534 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8535 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8536 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8537 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8538 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8539 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8540 T_EXCLAMATIONMARKEQUAL, 13);
8541 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8542 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8543 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8544 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8545 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8546 register_infix_parser(parse_conditional_expression, '?', 7);
8547 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8548 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8549 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8550 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8551 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8552 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8553 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8554 T_LESSLESSEQUAL, 2);
8555 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8556 T_GREATERGREATEREQUAL, 2);
8557 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8559 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8561 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8564 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8566 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8567 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8568 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8569 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8570 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8571 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8572 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8574 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8576 register_expression_parser(parse_sizeof, T_sizeof, 25);
8577 register_expression_parser(parse_alignof, T___alignof__, 25);
8578 register_expression_parser(parse_extension, T___extension__, 25);
8579 register_expression_parser(parse_builtin_classify_type,
8580 T___builtin_classify_type, 25);
8584 * Parse a asm statement arguments specification.
8586 static asm_argument_t *parse_asm_arguments(bool is_out)
8588 asm_argument_t *result = NULL;
8589 asm_argument_t *last = NULL;
8591 while (token.type == T_STRING_LITERAL || token.type == '[') {
8592 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8593 memset(argument, 0, sizeof(argument[0]));
8595 if (token.type == '[') {
8597 if (token.type != T_IDENTIFIER) {
8598 parse_error_expected("while parsing asm argument",
8599 T_IDENTIFIER, NULL);
8602 argument->symbol = token.v.symbol;
8607 argument->constraints = parse_string_literals();
8609 add_anchor_token(')');
8610 expression_t *expression = parse_expression();
8611 rem_anchor_token(')');
8613 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8614 * change size or type representation (e.g. int -> long is ok, but
8615 * int -> float is not) */
8616 if (expression->kind == EXPR_UNARY_CAST) {
8617 type_t *const type = expression->base.type;
8618 type_kind_t const kind = type->kind;
8619 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8622 if (kind == TYPE_ATOMIC) {
8623 atomic_type_kind_t const akind = type->atomic.akind;
8624 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8625 size = get_atomic_type_size(akind);
8627 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8628 size = get_atomic_type_size(get_intptr_kind());
8632 expression_t *const value = expression->unary.value;
8633 type_t *const value_type = value->base.type;
8634 type_kind_t const value_kind = value_type->kind;
8636 unsigned value_flags;
8637 unsigned value_size;
8638 if (value_kind == TYPE_ATOMIC) {
8639 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8640 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8641 value_size = get_atomic_type_size(value_akind);
8642 } else if (value_kind == TYPE_POINTER) {
8643 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8644 value_size = get_atomic_type_size(get_intptr_kind());
8649 if (value_flags != flags || value_size != size)
8653 } while (expression->kind == EXPR_UNARY_CAST);
8657 if (!is_lvalue(expression)) {
8658 errorf(&expression->base.source_position,
8659 "asm output argument is not an lvalue");
8662 argument->expression = expression;
8665 set_address_taken(expression, true);
8668 last->next = argument;
8674 if (token.type != ',')
8685 * Parse a asm statement clobber specification.
8687 static asm_clobber_t *parse_asm_clobbers(void)
8689 asm_clobber_t *result = NULL;
8690 asm_clobber_t *last = NULL;
8692 while(token.type == T_STRING_LITERAL) {
8693 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8694 clobber->clobber = parse_string_literals();
8697 last->next = clobber;
8703 if (token.type != ',')
8712 * Parse an asm statement.
8714 static statement_t *parse_asm_statement(void)
8718 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8719 statement->base.source_position = token.source_position;
8721 asm_statement_t *asm_statement = &statement->asms;
8723 if (token.type == T_volatile) {
8725 asm_statement->is_volatile = true;
8729 add_anchor_token(')');
8730 add_anchor_token(':');
8731 asm_statement->asm_text = parse_string_literals();
8733 if (token.type != ':') {
8734 rem_anchor_token(':');
8739 asm_statement->outputs = parse_asm_arguments(true);
8740 if (token.type != ':') {
8741 rem_anchor_token(':');
8746 asm_statement->inputs = parse_asm_arguments(false);
8747 if (token.type != ':') {
8748 rem_anchor_token(':');
8751 rem_anchor_token(':');
8754 asm_statement->clobbers = parse_asm_clobbers();
8757 rem_anchor_token(')');
8761 if (asm_statement->outputs == NULL) {
8762 /* GCC: An 'asm' instruction without any output operands will be treated
8763 * identically to a volatile 'asm' instruction. */
8764 asm_statement->is_volatile = true;
8769 return create_invalid_statement();
8773 * Parse a case statement.
8775 static statement_t *parse_case_statement(void)
8779 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8780 source_position_t *const pos = &statement->base.source_position;
8782 *pos = token.source_position;
8783 expression_t *const expression = parse_expression();
8784 statement->case_label.expression = expression;
8785 if (!is_constant_expression(expression)) {
8786 /* This check does not prevent the error message in all cases of an
8787 * prior error while parsing the expression. At least it catches the
8788 * common case of a mistyped enum entry. */
8789 if (is_type_valid(expression->base.type)) {
8790 errorf(pos, "case label does not reduce to an integer constant");
8792 statement->case_label.is_bad = true;
8794 long const val = fold_constant(expression);
8795 statement->case_label.first_case = val;
8796 statement->case_label.last_case = val;
8800 if (token.type == T_DOTDOTDOT) {
8802 expression_t *const end_range = parse_expression();
8803 statement->case_label.end_range = end_range;
8804 if (!is_constant_expression(end_range)) {
8805 /* This check does not prevent the error message in all cases of an
8806 * prior error while parsing the expression. At least it catches the
8807 * common case of a mistyped enum entry. */
8808 if (is_type_valid(end_range->base.type)) {
8809 errorf(pos, "case range does not reduce to an integer constant");
8811 statement->case_label.is_bad = true;
8813 long const val = fold_constant(end_range);
8814 statement->case_label.last_case = val;
8816 if (val < statement->case_label.first_case) {
8817 statement->case_label.is_empty_range = true;
8818 warningf(pos, "empty range specified");
8824 PUSH_PARENT(statement);
8828 if (current_switch != NULL) {
8829 if (! statement->case_label.is_bad) {
8830 /* Check for duplicate case values */
8831 case_label_statement_t *c = &statement->case_label;
8832 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8833 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8836 if (c->last_case < l->first_case || c->first_case > l->last_case)
8839 errorf(pos, "duplicate case value (previously used %P)",
8840 &l->base.source_position);
8844 /* link all cases into the switch statement */
8845 if (current_switch->last_case == NULL) {
8846 current_switch->first_case = &statement->case_label;
8848 current_switch->last_case->next = &statement->case_label;
8850 current_switch->last_case = &statement->case_label;
8852 errorf(pos, "case label not within a switch statement");
8855 statement_t *const inner_stmt = parse_statement();
8856 statement->case_label.statement = inner_stmt;
8857 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8858 errorf(&inner_stmt->base.source_position, "declaration after case label");
8865 return create_invalid_statement();
8869 * Parse a default statement.
8871 static statement_t *parse_default_statement(void)
8875 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8876 statement->base.source_position = token.source_position;
8878 PUSH_PARENT(statement);
8881 if (current_switch != NULL) {
8882 const case_label_statement_t *def_label = current_switch->default_label;
8883 if (def_label != NULL) {
8884 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8885 &def_label->base.source_position);
8887 current_switch->default_label = &statement->case_label;
8889 /* link all cases into the switch statement */
8890 if (current_switch->last_case == NULL) {
8891 current_switch->first_case = &statement->case_label;
8893 current_switch->last_case->next = &statement->case_label;
8895 current_switch->last_case = &statement->case_label;
8898 errorf(&statement->base.source_position,
8899 "'default' label not within a switch statement");
8902 statement_t *const inner_stmt = parse_statement();
8903 statement->case_label.statement = inner_stmt;
8904 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8905 errorf(&inner_stmt->base.source_position, "declaration after default label");
8912 return create_invalid_statement();
8916 * Parse a label statement.
8918 static statement_t *parse_label_statement(void)
8920 assert(token.type == T_IDENTIFIER);
8921 symbol_t *symbol = token.v.symbol;
8924 declaration_t *label = get_label(symbol);
8926 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8927 statement->base.source_position = token.source_position;
8928 statement->label.label = label;
8930 PUSH_PARENT(statement);
8932 /* if statement is already set then the label is defined twice,
8933 * otherwise it was just mentioned in a goto/local label declaration so far */
8934 if (label->init.statement != NULL) {
8935 errorf(HERE, "duplicate label '%Y' (declared %P)",
8936 symbol, &label->source_position);
8938 label->source_position = token.source_position;
8939 label->init.statement = statement;
8944 if (token.type == '}') {
8945 /* TODO only warn? */
8947 warningf(HERE, "label at end of compound statement");
8948 statement->label.statement = create_empty_statement();
8950 errorf(HERE, "label at end of compound statement");
8951 statement->label.statement = create_invalid_statement();
8953 } else if (token.type == ';') {
8954 /* Eat an empty statement here, to avoid the warning about an empty
8955 * statement after a label. label:; is commonly used to have a label
8956 * before a closing brace. */
8957 statement->label.statement = create_empty_statement();
8960 statement_t *const inner_stmt = parse_statement();
8961 statement->label.statement = inner_stmt;
8962 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8963 errorf(&inner_stmt->base.source_position, "declaration after label");
8967 /* remember the labels in a list for later checking */
8968 if (label_last == NULL) {
8969 label_first = &statement->label;
8971 label_last->next = &statement->label;
8973 label_last = &statement->label;
8980 * Parse an if statement.
8982 static statement_t *parse_if(void)
8986 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8987 statement->base.source_position = token.source_position;
8989 PUSH_PARENT(statement);
8992 add_anchor_token(')');
8993 statement->ifs.condition = parse_expression();
8994 rem_anchor_token(')');
8997 add_anchor_token(T_else);
8998 statement->ifs.true_statement = parse_statement();
8999 rem_anchor_token(T_else);
9001 if (token.type == T_else) {
9003 statement->ifs.false_statement = parse_statement();
9010 return create_invalid_statement();
9014 * Check that all enums are handled in a switch.
9016 * @param statement the switch statement to check
9018 static void check_enum_cases(const switch_statement_t *statement) {
9019 const type_t *type = skip_typeref(statement->expression->base.type);
9020 if (! is_type_enum(type))
9022 const enum_type_t *enumt = &type->enumt;
9024 /* if we have a default, no warnings */
9025 if (statement->default_label != NULL)
9028 /* FIXME: calculation of value should be done while parsing */
9029 const declaration_t *declaration;
9030 long last_value = -1;
9031 for (declaration = enumt->declaration->next;
9032 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9033 declaration = declaration->next) {
9034 const expression_t *expression = declaration->init.enum_value;
9035 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9037 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9038 if (l->expression == NULL)
9040 if (l->first_case <= value && value <= l->last_case) {
9046 warningf(&statement->base.source_position,
9047 "enumeration value '%Y' not handled in switch", declaration->symbol);
9054 * Parse a switch statement.
9056 static statement_t *parse_switch(void)
9060 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9061 statement->base.source_position = token.source_position;
9063 PUSH_PARENT(statement);
9066 add_anchor_token(')');
9067 expression_t *const expr = parse_expression();
9068 type_t * type = skip_typeref(expr->base.type);
9069 if (is_type_integer(type)) {
9070 type = promote_integer(type);
9071 if (warning.traditional) {
9072 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9073 warningf(&expr->base.source_position,
9074 "'%T' switch expression not converted to '%T' in ISO C",
9078 } else if (is_type_valid(type)) {
9079 errorf(&expr->base.source_position,
9080 "switch quantity is not an integer, but '%T'", type);
9081 type = type_error_type;
9083 statement->switchs.expression = create_implicit_cast(expr, type);
9085 rem_anchor_token(')');
9087 switch_statement_t *rem = current_switch;
9088 current_switch = &statement->switchs;
9089 statement->switchs.body = parse_statement();
9090 current_switch = rem;
9092 if (warning.switch_default &&
9093 statement->switchs.default_label == NULL) {
9094 warningf(&statement->base.source_position, "switch has no default case");
9096 if (warning.switch_enum)
9097 check_enum_cases(&statement->switchs);
9103 return create_invalid_statement();
9106 static statement_t *parse_loop_body(statement_t *const loop)
9108 statement_t *const rem = current_loop;
9109 current_loop = loop;
9111 statement_t *const body = parse_statement();
9118 * Parse a while statement.
9120 static statement_t *parse_while(void)
9124 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9125 statement->base.source_position = token.source_position;
9127 PUSH_PARENT(statement);
9130 add_anchor_token(')');
9131 statement->whiles.condition = parse_expression();
9132 rem_anchor_token(')');
9135 statement->whiles.body = parse_loop_body(statement);
9141 return create_invalid_statement();
9145 * Parse a do statement.
9147 static statement_t *parse_do(void)
9151 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9152 statement->base.source_position = token.source_position;
9154 PUSH_PARENT(statement)
9156 add_anchor_token(T_while);
9157 statement->do_while.body = parse_loop_body(statement);
9158 rem_anchor_token(T_while);
9162 add_anchor_token(')');
9163 statement->do_while.condition = parse_expression();
9164 rem_anchor_token(')');
9172 return create_invalid_statement();
9176 * Parse a for statement.
9178 static statement_t *parse_for(void)
9182 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9183 statement->base.source_position = token.source_position;
9185 PUSH_PARENT(statement);
9187 size_t const top = environment_top();
9188 scope_push(&statement->fors.scope);
9191 add_anchor_token(')');
9193 if (token.type != ';') {
9194 if (is_declaration_specifier(&token, false)) {
9195 parse_declaration(record_declaration);
9197 add_anchor_token(';');
9198 expression_t *const init = parse_expression();
9199 statement->fors.initialisation = init;
9200 if (warning.unused_value && !expression_has_effect(init)) {
9201 warningf(&init->base.source_position,
9202 "initialisation of 'for'-statement has no effect");
9204 rem_anchor_token(';');
9211 if (token.type != ';') {
9212 add_anchor_token(';');
9213 statement->fors.condition = parse_expression();
9214 rem_anchor_token(';');
9217 if (token.type != ')') {
9218 expression_t *const step = parse_expression();
9219 statement->fors.step = step;
9220 if (warning.unused_value && !expression_has_effect(step)) {
9221 warningf(&step->base.source_position,
9222 "step of 'for'-statement has no effect");
9225 rem_anchor_token(')');
9227 statement->fors.body = parse_loop_body(statement);
9229 assert(scope == &statement->fors.scope);
9231 environment_pop_to(top);
9238 rem_anchor_token(')');
9239 assert(scope == &statement->fors.scope);
9241 environment_pop_to(top);
9243 return create_invalid_statement();
9247 * Parse a goto statement.
9249 static statement_t *parse_goto(void)
9251 source_position_t source_position = token.source_position;
9254 statement_t *statement;
9255 if (GNU_MODE && token.type == '*') {
9257 expression_t *expression = parse_expression();
9259 /* Argh: although documentation say the expression must be of type void *,
9260 * gcc excepts anything that can be casted into void * without error */
9261 type_t *type = expression->base.type;
9263 if (type != type_error_type) {
9264 if (!is_type_pointer(type) && !is_type_integer(type)) {
9265 errorf(&source_position, "cannot convert to a pointer type");
9266 } else if (type != type_void_ptr) {
9267 warningf(&source_position,
9268 "type of computed goto expression should be 'void*' not '%T'", type);
9270 expression = create_implicit_cast(expression, type_void_ptr);
9273 statement = allocate_statement_zero(STATEMENT_GOTO);
9274 statement->base.source_position = source_position;
9275 statement->gotos.expression = expression;
9277 if (token.type != T_IDENTIFIER) {
9279 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9281 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9285 symbol_t *symbol = token.v.symbol;
9288 statement = allocate_statement_zero(STATEMENT_GOTO);
9289 statement->base.source_position = source_position;
9290 statement->gotos.label = get_label(symbol);
9292 if (statement->gotos.label->parent_scope->depth < current_function->scope.depth) {
9293 statement->gotos.outer_fkt_jmp = true;
9297 /* remember the goto's in a list for later checking */
9298 if (goto_last == NULL) {
9299 goto_first = &statement->gotos;
9301 goto_last->next = &statement->gotos;
9303 goto_last = &statement->gotos;
9309 return create_invalid_statement();
9313 * Parse a continue statement.
9315 static statement_t *parse_continue(void)
9317 if (current_loop == NULL) {
9318 errorf(HERE, "continue statement not within loop");
9321 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9322 statement->base.source_position = token.source_position;
9332 * Parse a break statement.
9334 static statement_t *parse_break(void)
9336 if (current_switch == NULL && current_loop == NULL) {
9337 errorf(HERE, "break statement not within loop or switch");
9340 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9341 statement->base.source_position = token.source_position;
9351 * Parse a __leave statement.
9353 static statement_t *parse_leave_statement(void)
9355 if (current_try == NULL) {
9356 errorf(HERE, "__leave statement not within __try");
9359 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9360 statement->base.source_position = token.source_position;
9370 * Check if a given declaration represents a local variable.
9372 static bool is_local_var_declaration(const declaration_t *declaration)
9374 switch ((storage_class_tag_t) declaration->storage_class) {
9375 case STORAGE_CLASS_AUTO:
9376 case STORAGE_CLASS_REGISTER: {
9377 const type_t *type = skip_typeref(declaration->type);
9378 if (is_type_function(type)) {
9390 * Check if a given declaration represents a variable.
9392 static bool is_var_declaration(const declaration_t *declaration)
9394 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9397 const type_t *type = skip_typeref(declaration->type);
9398 return !is_type_function(type);
9402 * Check if a given expression represents a local variable.
9404 static bool is_local_variable(const expression_t *expression)
9406 if (expression->base.kind != EXPR_REFERENCE) {
9409 const declaration_t *declaration = expression->reference.declaration;
9410 return is_local_var_declaration(declaration);
9414 * Check if a given expression represents a local variable and
9415 * return its declaration then, else return NULL.
9417 declaration_t *expr_is_variable(const expression_t *expression)
9419 if (expression->base.kind != EXPR_REFERENCE) {
9422 declaration_t *declaration = expression->reference.declaration;
9423 if (is_var_declaration(declaration))
9429 * Parse a return statement.
9431 static statement_t *parse_return(void)
9433 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9434 statement->base.source_position = token.source_position;
9438 expression_t *return_value = NULL;
9439 if (token.type != ';') {
9440 return_value = parse_expression();
9443 const type_t *const func_type = current_function->type;
9444 assert(is_type_function(func_type));
9445 type_t *const return_type = skip_typeref(func_type->function.return_type);
9447 if (return_value != NULL) {
9448 type_t *return_value_type = skip_typeref(return_value->base.type);
9450 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9451 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9452 warningf(&statement->base.source_position,
9453 "'return' with a value, in function returning void");
9454 return_value = NULL;
9456 assign_error_t error = semantic_assign(return_type, return_value);
9457 report_assign_error(error, return_type, return_value, "'return'",
9458 &statement->base.source_position);
9459 return_value = create_implicit_cast(return_value, return_type);
9461 /* check for returning address of a local var */
9462 if (return_value != NULL &&
9463 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9464 const expression_t *expression = return_value->unary.value;
9465 if (is_local_variable(expression)) {
9466 warningf(&statement->base.source_position,
9467 "function returns address of local variable");
9471 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9472 warningf(&statement->base.source_position,
9473 "'return' without value, in function returning non-void");
9476 statement->returns.value = return_value;
9485 * Parse a declaration statement.
9487 static statement_t *parse_declaration_statement(void)
9489 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9491 statement->base.source_position = token.source_position;
9493 declaration_t *before = last_declaration;
9495 parse_external_declaration();
9497 parse_declaration(record_declaration);
9499 if (before == NULL) {
9500 statement->declaration.declarations_begin = scope->declarations;
9502 statement->declaration.declarations_begin = before->next;
9504 statement->declaration.declarations_end = last_declaration;
9510 * Parse an expression statement, ie. expr ';'.
9512 static statement_t *parse_expression_statement(void)
9514 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9516 statement->base.source_position = token.source_position;
9517 expression_t *const expr = parse_expression();
9518 statement->expression.expression = expr;
9527 * Parse a microsoft __try { } __finally { } or
9528 * __try{ } __except() { }
9530 static statement_t *parse_ms_try_statment(void)
9532 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9533 statement->base.source_position = token.source_position;
9536 PUSH_PARENT(statement);
9538 ms_try_statement_t *rem = current_try;
9539 current_try = &statement->ms_try;
9540 statement->ms_try.try_statement = parse_compound_statement(false);
9545 if (token.type == T___except) {
9548 add_anchor_token(')');
9549 expression_t *const expr = parse_expression();
9550 type_t * type = skip_typeref(expr->base.type);
9551 if (is_type_integer(type)) {
9552 type = promote_integer(type);
9553 } else if (is_type_valid(type)) {
9554 errorf(&expr->base.source_position,
9555 "__expect expression is not an integer, but '%T'", type);
9556 type = type_error_type;
9558 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9559 rem_anchor_token(')');
9561 statement->ms_try.final_statement = parse_compound_statement(false);
9562 } else if (token.type == T__finally) {
9564 statement->ms_try.final_statement = parse_compound_statement(false);
9566 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9567 return create_invalid_statement();
9571 return create_invalid_statement();
9574 static statement_t *parse_empty_statement(void)
9576 if (warning.empty_statement) {
9577 warningf(HERE, "statement is empty");
9579 statement_t *const statement = create_empty_statement();
9584 static statement_t *parse_local_label_declaration(void) {
9585 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9586 statement->base.source_position = token.source_position;
9590 declaration_t *begin = NULL, *end = NULL;
9593 if (token.type != T_IDENTIFIER) {
9594 parse_error_expected("while parsing local label declaration",
9595 T_IDENTIFIER, NULL);
9598 symbol_t *symbol = token.v.symbol;
9599 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9600 if (declaration != NULL) {
9601 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9602 symbol, &declaration->source_position);
9604 declaration = allocate_declaration_zero();
9605 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9606 declaration->source_position = token.source_position;
9607 declaration->symbol = symbol;
9608 declaration->parent_scope = scope;
9609 declaration->init.statement = NULL;
9612 end->next = declaration;
9615 begin = declaration;
9617 local_label_push(declaration);
9621 if (token.type != ',')
9627 statement->declaration.declarations_begin = begin;
9628 statement->declaration.declarations_end = end;
9633 * Parse a statement.
9634 * There's also parse_statement() which additionally checks for
9635 * "statement has no effect" warnings
9637 static statement_t *intern_parse_statement(void)
9639 statement_t *statement = NULL;
9641 /* declaration or statement */
9642 add_anchor_token(';');
9643 switch (token.type) {
9644 case T_IDENTIFIER: {
9645 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9646 if (la1_type == ':') {
9647 statement = parse_label_statement();
9648 } else if (is_typedef_symbol(token.v.symbol)) {
9649 statement = parse_declaration_statement();
9650 } else switch (la1_type) {
9652 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9653 goto expression_statment;
9658 statement = parse_declaration_statement();
9662 expression_statment:
9663 statement = parse_expression_statement();
9669 case T___extension__:
9670 /* This can be a prefix to a declaration or an expression statement.
9671 * We simply eat it now and parse the rest with tail recursion. */
9674 } while (token.type == T___extension__);
9675 bool old_gcc_extension = in_gcc_extension;
9676 in_gcc_extension = true;
9677 statement = parse_statement();
9678 in_gcc_extension = old_gcc_extension;
9682 statement = parse_declaration_statement();
9686 statement = parse_local_label_declaration();
9689 case ';': statement = parse_empty_statement(); break;
9690 case '{': statement = parse_compound_statement(false); break;
9691 case T___leave: statement = parse_leave_statement(); break;
9692 case T___try: statement = parse_ms_try_statment(); break;
9693 case T_asm: statement = parse_asm_statement(); break;
9694 case T_break: statement = parse_break(); break;
9695 case T_case: statement = parse_case_statement(); break;
9696 case T_continue: statement = parse_continue(); break;
9697 case T_default: statement = parse_default_statement(); break;
9698 case T_do: statement = parse_do(); break;
9699 case T_for: statement = parse_for(); break;
9700 case T_goto: statement = parse_goto(); break;
9701 case T_if: statement = parse_if (); break;
9702 case T_return: statement = parse_return(); break;
9703 case T_switch: statement = parse_switch(); break;
9704 case T_while: statement = parse_while(); break;
9714 case T_CHARACTER_CONSTANT:
9715 case T_FLOATINGPOINT:
9719 case T_STRING_LITERAL:
9720 case T_WIDE_CHARACTER_CONSTANT:
9721 case T_WIDE_STRING_LITERAL:
9722 case T___FUNCDNAME__:
9724 case T___FUNCTION__:
9725 case T___PRETTY_FUNCTION__:
9726 case T___builtin_alloca:
9727 case T___builtin_classify_type:
9728 case T___builtin_constant_p:
9729 case T___builtin_expect:
9730 case T___builtin_huge_val:
9731 case T___builtin_isgreater:
9732 case T___builtin_isgreaterequal:
9733 case T___builtin_isless:
9734 case T___builtin_islessequal:
9735 case T___builtin_islessgreater:
9736 case T___builtin_isunordered:
9737 case T___builtin_nan:
9738 case T___builtin_nand:
9739 case T___builtin_nanf:
9740 case T___builtin_offsetof:
9741 case T___builtin_prefetch:
9742 case T___builtin_va_arg:
9743 case T___builtin_va_end:
9744 case T___builtin_va_start:
9748 statement = parse_expression_statement();
9752 errorf(HERE, "unexpected token %K while parsing statement", &token);
9753 statement = create_invalid_statement();
9758 rem_anchor_token(';');
9760 assert(statement != NULL
9761 && statement->base.source_position.input_name != NULL);
9767 * parse a statement and emits "statement has no effect" warning if needed
9768 * (This is really a wrapper around intern_parse_statement with check for 1
9769 * single warning. It is needed, because for statement expressions we have
9770 * to avoid the warning on the last statement)
9772 static statement_t *parse_statement(void)
9774 statement_t *statement = intern_parse_statement();
9776 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9777 expression_t *expression = statement->expression.expression;
9778 if (!expression_has_effect(expression)) {
9779 warningf(&expression->base.source_position,
9780 "statement has no effect");
9788 * Parse a compound statement.
9790 static statement_t *parse_compound_statement(bool inside_expression_statement)
9792 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9793 statement->base.source_position = token.source_position;
9795 PUSH_PARENT(statement);
9798 add_anchor_token('}');
9800 size_t const top = environment_top();
9801 size_t const top_local = local_label_top();
9802 scope_push(&statement->compound.scope);
9804 statement_t **anchor = &statement->compound.statements;
9805 bool only_decls_so_far = true;
9806 while (token.type != '}' && token.type != T_EOF) {
9807 statement_t *sub_statement = intern_parse_statement();
9808 if (is_invalid_statement(sub_statement)) {
9809 /* an error occurred. if we are at an anchor, return */
9815 if (warning.declaration_after_statement) {
9816 if (sub_statement->kind != STATEMENT_DECLARATION) {
9817 only_decls_so_far = false;
9818 } else if (!only_decls_so_far) {
9819 warningf(&sub_statement->base.source_position,
9820 "ISO C90 forbids mixed declarations and code");
9824 *anchor = sub_statement;
9826 while (sub_statement->base.next != NULL)
9827 sub_statement = sub_statement->base.next;
9829 anchor = &sub_statement->base.next;
9832 if (token.type == '}') {
9835 errorf(&statement->base.source_position,
9836 "end of file while looking for closing '}'");
9839 /* look over all statements again to produce no effect warnings */
9840 if (warning.unused_value) {
9841 statement_t *sub_statement = statement->compound.statements;
9842 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9843 if (sub_statement->kind != STATEMENT_EXPRESSION)
9845 /* don't emit a warning for the last expression in an expression
9846 * statement as it has always an effect */
9847 if (inside_expression_statement && sub_statement->base.next == NULL)
9850 expression_t *expression = sub_statement->expression.expression;
9851 if (!expression_has_effect(expression)) {
9852 warningf(&expression->base.source_position,
9853 "statement has no effect");
9859 rem_anchor_token('}');
9860 assert(scope == &statement->compound.scope);
9862 environment_pop_to(top);
9863 local_label_pop_to(top_local);
9870 * Initialize builtin types.
9872 static void initialize_builtin_types(void)
9874 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9875 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9876 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9877 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9878 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9879 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9880 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9881 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9883 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9884 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9885 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9886 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9888 /* const version of wchar_t */
9889 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9890 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9891 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9893 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9897 * Check for unused global static functions and variables
9899 static void check_unused_globals(void)
9901 if (!warning.unused_function && !warning.unused_variable)
9904 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9906 decl->modifiers & DM_UNUSED ||
9907 decl->modifiers & DM_USED ||
9908 decl->storage_class != STORAGE_CLASS_STATIC)
9911 type_t *const type = decl->type;
9913 if (is_type_function(skip_typeref(type))) {
9914 if (!warning.unused_function || decl->is_inline)
9917 s = (decl->init.statement != NULL ? "defined" : "declared");
9919 if (!warning.unused_variable)
9925 warningf(&decl->source_position, "'%#T' %s but not used",
9926 type, decl->symbol, s);
9930 static void parse_global_asm(void)
9935 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9936 statement->base.source_position = token.source_position;
9937 statement->asms.asm_text = parse_string_literals();
9938 statement->base.next = unit->global_asm;
9939 unit->global_asm = statement;
9948 * Parse a translation unit.
9950 static void parse_translation_unit(void)
9954 bool anchor_leak = false;
9955 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9956 unsigned char count = token_anchor_set[i];
9958 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9962 if (in_gcc_extension) {
9963 errorf(HERE, "Leaked __extension__");
9971 switch (token.type) {
9974 case T___extension__:
9975 parse_external_declaration();
9986 /* TODO error in strict mode */
9987 warningf(HERE, "stray ';' outside of function");
9992 errorf(HERE, "stray %K outside of function", &token);
9993 if (token.type == '(' || token.type == '{' || token.type == '[')
9994 eat_until_matching_token(token.type);
10004 * @return the translation unit or NULL if errors occurred.
10006 void start_parsing(void)
10008 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10009 label_stack = NEW_ARR_F(stack_entry_t, 0);
10010 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10011 diagnostic_count = 0;
10015 type_set_output(stderr);
10016 ast_set_output(stderr);
10018 assert(unit == NULL);
10019 unit = allocate_ast_zero(sizeof(unit[0]));
10021 assert(global_scope == NULL);
10022 global_scope = &unit->scope;
10024 assert(scope == NULL);
10025 scope_push(&unit->scope);
10027 initialize_builtin_types();
10030 translation_unit_t *finish_parsing(void)
10032 /* do NOT use scope_pop() here, this will crash, will it by hand */
10033 assert(scope == &unit->scope);
10035 last_declaration = NULL;
10037 assert(global_scope == &unit->scope);
10038 check_unused_globals();
10039 global_scope = NULL;
10041 DEL_ARR_F(environment_stack);
10042 DEL_ARR_F(label_stack);
10043 DEL_ARR_F(local_label_stack);
10045 translation_unit_t *result = unit;
10052 lookahead_bufpos = 0;
10053 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10056 parse_translation_unit();
10060 * Initialize the parser.
10062 void init_parser(void)
10064 sym_anonymous = symbol_table_insert("<anonymous>");
10066 if (c_mode & _MS) {
10067 /* add predefined symbols for extended-decl-modifier */
10068 sym_align = symbol_table_insert("align");
10069 sym_allocate = symbol_table_insert("allocate");
10070 sym_dllimport = symbol_table_insert("dllimport");
10071 sym_dllexport = symbol_table_insert("dllexport");
10072 sym_naked = symbol_table_insert("naked");
10073 sym_noinline = symbol_table_insert("noinline");
10074 sym_noreturn = symbol_table_insert("noreturn");
10075 sym_nothrow = symbol_table_insert("nothrow");
10076 sym_novtable = symbol_table_insert("novtable");
10077 sym_property = symbol_table_insert("property");
10078 sym_get = symbol_table_insert("get");
10079 sym_put = symbol_table_insert("put");
10080 sym_selectany = symbol_table_insert("selectany");
10081 sym_thread = symbol_table_insert("thread");
10082 sym_uuid = symbol_table_insert("uuid");
10083 sym_deprecated = symbol_table_insert("deprecated");
10084 sym_restrict = symbol_table_insert("restrict");
10085 sym_noalias = symbol_table_insert("noalias");
10087 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10089 init_expression_parsers();
10090 obstack_init(&temp_obst);
10092 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10093 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10097 * Terminate the parser.
10099 void exit_parser(void)
10101 obstack_free(&temp_obst, NULL);