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 *iter = symbol->declaration;
766 symbol->declaration = declaration;
768 declaration_t *iter_last = NULL;
769 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
770 /* replace an entry? */
771 if (iter->namespc == namespc) {
772 if (iter_last == NULL) {
773 symbol->declaration = declaration;
775 iter_last->symbol_next = declaration;
777 declaration->symbol_next = iter->symbol_next;
782 assert(iter_last->symbol_next == NULL);
783 iter_last->symbol_next = declaration;
787 /* remember old declaration */
789 entry.symbol = symbol;
790 entry.old_declaration = iter;
791 entry.namespc = (unsigned short) namespc;
792 ARR_APP1(stack_entry_t, *stack_ptr, entry);
796 * Push a declaration on the environment stack.
798 * @param declaration the declaration
800 static void environment_push(declaration_t *declaration)
802 assert(declaration->source_position.input_name != NULL);
803 assert(declaration->parent_scope != NULL);
804 stack_push(&environment_stack, declaration);
808 * Push a declaration on the global label stack.
810 * @param declaration the declaration
812 static void label_push(declaration_t *declaration)
814 declaration->parent_scope = ¤t_function->scope;
815 stack_push(&label_stack, declaration);
819 * Push a declaration of the local label stack.
821 * @param declaration the declaration
823 static void local_label_push(declaration_t *declaration)
825 assert(declaration->parent_scope != NULL);
826 stack_push(&local_label_stack, declaration);
830 * pops symbols from the environment stack until @p new_top is the top element
832 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
834 stack_entry_t *stack = *stack_ptr;
835 size_t top = ARR_LEN(stack);
838 assert(new_top <= top);
842 for(i = top; i > new_top; --i) {
843 stack_entry_t *entry = &stack[i - 1];
845 declaration_t *old_declaration = entry->old_declaration;
846 symbol_t *symbol = entry->symbol;
847 namespace_t namespc = (namespace_t)entry->namespc;
849 /* replace/remove declaration */
850 declaration_t *declaration = symbol->declaration;
851 assert(declaration != NULL);
852 if (declaration->namespc == namespc) {
853 if (old_declaration == NULL) {
854 symbol->declaration = declaration->symbol_next;
856 symbol->declaration = old_declaration;
859 declaration_t *iter_last = declaration;
860 declaration_t *iter = declaration->symbol_next;
861 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
862 /* replace an entry? */
863 if (iter->namespc == namespc) {
864 assert(iter_last != NULL);
865 iter_last->symbol_next = old_declaration;
866 if (old_declaration != NULL) {
867 old_declaration->symbol_next = iter->symbol_next;
872 assert(iter != NULL);
876 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
880 * Pop all entries from the environment stack until the new_top
883 * @param new_top the new stack top
885 static void environment_pop_to(size_t new_top)
887 stack_pop_to(&environment_stack, new_top);
891 * Pop all entries from the global label stack until the new_top
894 * @param new_top the new stack top
896 static void label_pop_to(size_t new_top)
898 stack_pop_to(&label_stack, new_top);
902 * Pop all entries from the local label stack until the new_top
905 * @param new_top the new stack top
907 static void local_label_pop_to(size_t new_top)
909 stack_pop_to(&local_label_stack, new_top);
913 static int get_akind_rank(atomic_type_kind_t akind)
918 static int get_rank(const type_t *type)
920 assert(!is_typeref(type));
921 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
922 * and esp. footnote 108). However we can't fold constants (yet), so we
923 * can't decide whether unsigned int is possible, while int always works.
924 * (unsigned int would be preferable when possible... for stuff like
925 * struct { enum { ... } bla : 4; } ) */
926 if (type->kind == TYPE_ENUM)
927 return get_akind_rank(ATOMIC_TYPE_INT);
929 assert(type->kind == TYPE_ATOMIC);
930 return get_akind_rank(type->atomic.akind);
933 static type_t *promote_integer(type_t *type)
935 if (type->kind == TYPE_BITFIELD)
936 type = type->bitfield.base_type;
938 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
945 * Create a cast expression.
947 * @param expression the expression to cast
948 * @param dest_type the destination type
950 static expression_t *create_cast_expression(expression_t *expression,
953 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
955 cast->unary.value = expression;
956 cast->base.type = dest_type;
962 * Check if a given expression represents the 0 pointer constant.
964 static bool is_null_pointer_constant(const expression_t *expression)
966 /* skip void* cast */
967 if (expression->kind == EXPR_UNARY_CAST
968 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
969 expression = expression->unary.value;
972 /* TODO: not correct yet, should be any constant integer expression
973 * which evaluates to 0 */
974 if (expression->kind != EXPR_CONST)
977 type_t *const type = skip_typeref(expression->base.type);
978 if (!is_type_integer(type))
981 return expression->conste.v.int_value == 0;
985 * Create an implicit cast expression.
987 * @param expression the expression to cast
988 * @param dest_type the destination type
990 static expression_t *create_implicit_cast(expression_t *expression,
993 type_t *const source_type = expression->base.type;
995 if (source_type == dest_type)
998 return create_cast_expression(expression, dest_type);
1001 typedef enum assign_error_t {
1003 ASSIGN_ERROR_INCOMPATIBLE,
1004 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1005 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1006 ASSIGN_WARNING_POINTER_FROM_INT,
1007 ASSIGN_WARNING_INT_FROM_POINTER
1010 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1011 const expression_t *const right,
1012 const char *context,
1013 const source_position_t *source_position)
1015 type_t *const orig_type_right = right->base.type;
1016 type_t *const type_left = skip_typeref(orig_type_left);
1017 type_t *const type_right = skip_typeref(orig_type_right);
1020 case ASSIGN_SUCCESS:
1022 case ASSIGN_ERROR_INCOMPATIBLE:
1023 errorf(source_position,
1024 "destination type '%T' in %s is incompatible with type '%T'",
1025 orig_type_left, context, orig_type_right);
1028 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1029 type_t *points_to_left
1030 = skip_typeref(type_left->pointer.points_to);
1031 type_t *points_to_right
1032 = skip_typeref(type_right->pointer.points_to);
1034 /* the left type has all qualifiers from the right type */
1035 unsigned missing_qualifiers
1036 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1037 warningf(source_position,
1038 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1039 orig_type_left, context, orig_type_right, missing_qualifiers);
1043 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1044 warningf(source_position,
1045 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1046 orig_type_left, context, right, orig_type_right);
1049 case ASSIGN_WARNING_POINTER_FROM_INT:
1050 warningf(source_position,
1051 "%s makes pointer '%T' from integer '%T' without a cast",
1052 context, orig_type_left, orig_type_right);
1055 case ASSIGN_WARNING_INT_FROM_POINTER:
1056 warningf(source_position,
1057 "%s makes integer '%T' from pointer '%T' without a cast",
1058 context, orig_type_left, orig_type_right);
1062 panic("invalid error value");
1066 /** Implements the rules from § 6.5.16.1 */
1067 static assign_error_t semantic_assign(type_t *orig_type_left,
1068 const expression_t *const right)
1070 type_t *const orig_type_right = right->base.type;
1071 type_t *const type_left = skip_typeref(orig_type_left);
1072 type_t *const type_right = skip_typeref(orig_type_right);
1074 if (is_type_pointer(type_left)) {
1075 if (is_null_pointer_constant(right)) {
1076 return ASSIGN_SUCCESS;
1077 } else if (is_type_pointer(type_right)) {
1078 type_t *points_to_left
1079 = skip_typeref(type_left->pointer.points_to);
1080 type_t *points_to_right
1081 = skip_typeref(type_right->pointer.points_to);
1082 assign_error_t res = ASSIGN_SUCCESS;
1084 /* the left type has all qualifiers from the right type */
1085 unsigned missing_qualifiers
1086 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1087 if (missing_qualifiers != 0) {
1088 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1091 points_to_left = get_unqualified_type(points_to_left);
1092 points_to_right = get_unqualified_type(points_to_right);
1094 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1095 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1099 if (!types_compatible(points_to_left, points_to_right)) {
1100 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1104 } else if (is_type_integer(type_right)) {
1105 return ASSIGN_WARNING_POINTER_FROM_INT;
1107 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1108 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1109 && is_type_pointer(type_right))) {
1110 return ASSIGN_SUCCESS;
1111 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1112 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1113 type_t *const unqual_type_left = get_unqualified_type(type_left);
1114 type_t *const unqual_type_right = get_unqualified_type(type_right);
1115 if (types_compatible(unqual_type_left, unqual_type_right)) {
1116 return ASSIGN_SUCCESS;
1118 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1119 return ASSIGN_WARNING_INT_FROM_POINTER;
1122 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1123 return ASSIGN_SUCCESS;
1125 return ASSIGN_ERROR_INCOMPATIBLE;
1128 static expression_t *parse_constant_expression(void)
1130 /* start parsing at precedence 7 (conditional expression) */
1131 expression_t *result = parse_sub_expression(7);
1133 if (!is_constant_expression(result)) {
1134 errorf(&result->base.source_position,
1135 "expression '%E' is not constant\n", result);
1141 static expression_t *parse_assignment_expression(void)
1143 /* start parsing at precedence 2 (assignment expression) */
1144 return parse_sub_expression(2);
1147 static type_t *make_global_typedef(const char *name, type_t *type)
1149 symbol_t *const symbol = symbol_table_insert(name);
1151 declaration_t *const declaration = allocate_declaration_zero();
1152 declaration->namespc = NAMESPACE_NORMAL;
1153 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1154 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1155 declaration->type = type;
1156 declaration->symbol = symbol;
1157 declaration->source_position = builtin_source_position;
1158 declaration->implicit = true;
1160 record_declaration(declaration, false);
1162 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1163 typedef_type->typedeft.declaration = declaration;
1165 return typedef_type;
1168 static string_t parse_string_literals(void)
1170 assert(token.type == T_STRING_LITERAL);
1171 string_t result = token.v.string;
1175 while (token.type == T_STRING_LITERAL) {
1176 result = concat_strings(&result, &token.v.string);
1183 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1184 [GNU_AK_CONST] = "const",
1185 [GNU_AK_VOLATILE] = "volatile",
1186 [GNU_AK_CDECL] = "cdecl",
1187 [GNU_AK_STDCALL] = "stdcall",
1188 [GNU_AK_FASTCALL] = "fastcall",
1189 [GNU_AK_DEPRECATED] = "deprecated",
1190 [GNU_AK_NOINLINE] = "noinline",
1191 [GNU_AK_NORETURN] = "noreturn",
1192 [GNU_AK_NAKED] = "naked",
1193 [GNU_AK_PURE] = "pure",
1194 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1195 [GNU_AK_MALLOC] = "malloc",
1196 [GNU_AK_WEAK] = "weak",
1197 [GNU_AK_CONSTRUCTOR] = "constructor",
1198 [GNU_AK_DESTRUCTOR] = "destructor",
1199 [GNU_AK_NOTHROW] = "nothrow",
1200 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1201 [GNU_AK_COMMON] = "common",
1202 [GNU_AK_NOCOMMON] = "nocommon",
1203 [GNU_AK_PACKED] = "packed",
1204 [GNU_AK_SHARED] = "shared",
1205 [GNU_AK_NOTSHARED] = "notshared",
1206 [GNU_AK_USED] = "used",
1207 [GNU_AK_UNUSED] = "unused",
1208 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1209 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1210 [GNU_AK_LONGCALL] = "longcall",
1211 [GNU_AK_SHORTCALL] = "shortcall",
1212 [GNU_AK_LONG_CALL] = "long_call",
1213 [GNU_AK_SHORT_CALL] = "short_call",
1214 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1215 [GNU_AK_INTERRUPT] = "interrupt",
1216 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1217 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1218 [GNU_AK_NESTING] = "nesting",
1219 [GNU_AK_NEAR] = "near",
1220 [GNU_AK_FAR] = "far",
1221 [GNU_AK_SIGNAL] = "signal",
1222 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1223 [GNU_AK_TINY_DATA] = "tiny_data",
1224 [GNU_AK_SAVEALL] = "saveall",
1225 [GNU_AK_FLATTEN] = "flatten",
1226 [GNU_AK_SSEREGPARM] = "sseregparm",
1227 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1228 [GNU_AK_RETURN_TWICE] = "return_twice",
1229 [GNU_AK_MAY_ALIAS] = "may_alias",
1230 [GNU_AK_MS_STRUCT] = "ms_struct",
1231 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1232 [GNU_AK_DLLIMPORT] = "dllimport",
1233 [GNU_AK_DLLEXPORT] = "dllexport",
1234 [GNU_AK_ALIGNED] = "aligned",
1235 [GNU_AK_ALIAS] = "alias",
1236 [GNU_AK_SECTION] = "section",
1237 [GNU_AK_FORMAT] = "format",
1238 [GNU_AK_FORMAT_ARG] = "format_arg",
1239 [GNU_AK_WEAKREF] = "weakref",
1240 [GNU_AK_NONNULL] = "nonnull",
1241 [GNU_AK_TLS_MODEL] = "tls_model",
1242 [GNU_AK_VISIBILITY] = "visibility",
1243 [GNU_AK_REGPARM] = "regparm",
1244 [GNU_AK_MODE] = "mode",
1245 [GNU_AK_MODEL] = "model",
1246 [GNU_AK_TRAP_EXIT] = "trap_exit",
1247 [GNU_AK_SP_SWITCH] = "sp_switch",
1248 [GNU_AK_SENTINEL] = "sentinel"
1252 * compare two string, ignoring double underscores on the second.
1254 static int strcmp_underscore(const char *s1, const char *s2)
1256 if (s2[0] == '_' && s2[1] == '_') {
1257 size_t len2 = strlen(s2);
1258 size_t len1 = strlen(s1);
1259 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1260 return strncmp(s1, s2+2, len2-4);
1264 return strcmp(s1, s2);
1268 * Allocate a new gnu temporal attribute.
1270 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1272 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1273 attribute->kind = kind;
1274 attribute->next = NULL;
1275 attribute->invalid = false;
1276 attribute->have_arguments = false;
1282 * parse one constant expression argument.
1284 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1286 expression_t *expression;
1287 add_anchor_token(')');
1288 expression = parse_constant_expression();
1289 rem_anchor_token(')');
1291 attribute->u.argument = fold_constant(expression);
1294 attribute->invalid = true;
1298 * parse a list of constant expressions arguments.
1300 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1302 argument_list_t **list = &attribute->u.arguments;
1303 argument_list_t *entry;
1304 expression_t *expression;
1305 add_anchor_token(')');
1306 add_anchor_token(',');
1308 expression = parse_constant_expression();
1309 entry = obstack_alloc(&temp_obst, sizeof(entry));
1310 entry->argument = fold_constant(expression);
1313 list = &entry->next;
1314 if (token.type != ',')
1318 rem_anchor_token(',');
1319 rem_anchor_token(')');
1323 attribute->invalid = true;
1327 * parse one string literal argument.
1329 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1332 add_anchor_token('(');
1333 if (token.type != T_STRING_LITERAL) {
1334 parse_error_expected("while parsing attribute directive",
1335 T_STRING_LITERAL, NULL);
1338 *string = parse_string_literals();
1339 rem_anchor_token('(');
1343 attribute->invalid = true;
1347 * parse one tls model.
1349 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1351 static const char *const tls_models[] = {
1357 string_t string = { NULL, 0 };
1358 parse_gnu_attribute_string_arg(attribute, &string);
1359 if (string.begin != NULL) {
1360 for(size_t i = 0; i < 4; ++i) {
1361 if (strcmp(tls_models[i], string.begin) == 0) {
1362 attribute->u.value = i;
1366 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1368 attribute->invalid = true;
1372 * parse one tls model.
1374 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1376 static const char *const visibilities[] = {
1382 string_t string = { NULL, 0 };
1383 parse_gnu_attribute_string_arg(attribute, &string);
1384 if (string.begin != NULL) {
1385 for(size_t i = 0; i < 4; ++i) {
1386 if (strcmp(visibilities[i], string.begin) == 0) {
1387 attribute->u.value = i;
1391 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1393 attribute->invalid = true;
1397 * parse one (code) model.
1399 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1401 static const char *const visibilities[] = {
1406 string_t string = { NULL, 0 };
1407 parse_gnu_attribute_string_arg(attribute, &string);
1408 if (string.begin != NULL) {
1409 for(int i = 0; i < 3; ++i) {
1410 if (strcmp(visibilities[i], string.begin) == 0) {
1411 attribute->u.value = i;
1415 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1417 attribute->invalid = true;
1420 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1422 /* TODO: find out what is allowed here... */
1424 /* at least: byte, word, pointer, list of machine modes
1425 * __XXX___ is interpreted as XXX */
1426 add_anchor_token(')');
1428 if (token.type != T_IDENTIFIER) {
1429 expect(T_IDENTIFIER);
1432 /* This isn't really correct, the backend should provide a list of machine
1433 * specific modes (according to gcc philosophy that is...) */
1434 const char *symbol_str = token.v.symbol->string;
1435 if (strcmp_underscore("QI", symbol_str) == 0 ||
1436 strcmp_underscore("byte", symbol_str) == 0) {
1437 attribute->u.akind = ATOMIC_TYPE_CHAR;
1438 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1439 attribute->u.akind = ATOMIC_TYPE_SHORT;
1440 } else if (strcmp_underscore("SI", symbol_str) == 0
1441 || strcmp_underscore("word", symbol_str) == 0
1442 || strcmp_underscore("pointer", symbol_str) == 0) {
1443 attribute->u.akind = ATOMIC_TYPE_INT;
1444 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1445 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1447 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1448 attribute->invalid = true;
1452 rem_anchor_token(')');
1456 attribute->invalid = true;
1460 * parse one interrupt argument.
1462 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1464 static const char *const interrupts[] = {
1471 string_t string = { NULL, 0 };
1472 parse_gnu_attribute_string_arg(attribute, &string);
1473 if (string.begin != NULL) {
1474 for(size_t i = 0; i < 5; ++i) {
1475 if (strcmp(interrupts[i], string.begin) == 0) {
1476 attribute->u.value = i;
1480 errorf(HERE, "'%s' is not an interrupt", string.begin);
1482 attribute->invalid = true;
1486 * parse ( identifier, const expression, const expression )
1488 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1490 static const char *const format_names[] = {
1498 if (token.type != T_IDENTIFIER) {
1499 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1502 const char *name = token.v.symbol->string;
1503 for(i = 0; i < 4; ++i) {
1504 if (strcmp_underscore(format_names[i], name) == 0)
1508 if (warning.attribute)
1509 warningf(HERE, "'%s' is an unrecognized format function type", name);
1514 add_anchor_token(')');
1515 add_anchor_token(',');
1516 parse_constant_expression();
1517 rem_anchor_token(',');
1518 rem_anchor_token(')');
1521 add_anchor_token(')');
1522 parse_constant_expression();
1523 rem_anchor_token(')');
1527 attribute->u.value = true;
1530 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1532 if (!attribute->have_arguments)
1535 /* should have no arguments */
1536 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1537 eat_until_matching_token('(');
1538 /* we have already consumed '(', so we stop before ')', eat it */
1540 attribute->invalid = true;
1544 * Parse one GNU attribute.
1546 * Note that attribute names can be specified WITH or WITHOUT
1547 * double underscores, ie const or __const__.
1549 * The following attributes are parsed without arguments
1574 * no_instrument_function
1575 * warn_unused_result
1592 * externally_visible
1600 * The following attributes are parsed with arguments
1601 * aligned( const expression )
1602 * alias( string literal )
1603 * section( string literal )
1604 * format( identifier, const expression, const expression )
1605 * format_arg( const expression )
1606 * tls_model( string literal )
1607 * visibility( string literal )
1608 * regparm( const expression )
1609 * model( string leteral )
1610 * trap_exit( const expression )
1611 * sp_switch( string literal )
1613 * The following attributes might have arguments
1614 * weak_ref( string literal )
1615 * non_null( const expression // ',' )
1616 * interrupt( string literal )
1617 * sentinel( constant expression )
1619 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1621 gnu_attribute_t *head = *attributes;
1622 gnu_attribute_t *last = *attributes;
1623 decl_modifiers_t modifiers = 0;
1624 gnu_attribute_t *attribute;
1626 eat(T___attribute__);
1630 if (token.type != ')') {
1631 /* find the end of the list */
1633 while (last->next != NULL)
1637 /* non-empty attribute list */
1640 if (token.type == T_const) {
1642 } else if (token.type == T_volatile) {
1644 } else if (token.type == T_cdecl) {
1645 /* __attribute__((cdecl)), WITH ms mode */
1647 } else if (token.type == T_IDENTIFIER) {
1648 const symbol_t *sym = token.v.symbol;
1651 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1658 for(i = 0; i < GNU_AK_LAST; ++i) {
1659 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1662 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1665 if (kind == GNU_AK_LAST) {
1666 if (warning.attribute)
1667 warningf(HERE, "'%s' attribute directive ignored", name);
1669 /* skip possible arguments */
1670 if (token.type == '(') {
1671 eat_until_matching_token(')');
1674 /* check for arguments */
1675 attribute = allocate_gnu_attribute(kind);
1676 if (token.type == '(') {
1678 if (token.type == ')') {
1679 /* empty args are allowed */
1682 attribute->have_arguments = true;
1687 case GNU_AK_VOLATILE:
1692 case GNU_AK_NOCOMMON:
1694 case GNU_AK_NOTSHARED:
1695 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1696 case GNU_AK_WARN_UNUSED_RESULT:
1697 case GNU_AK_LONGCALL:
1698 case GNU_AK_SHORTCALL:
1699 case GNU_AK_LONG_CALL:
1700 case GNU_AK_SHORT_CALL:
1701 case GNU_AK_FUNCTION_VECTOR:
1702 case GNU_AK_INTERRUPT_HANDLER:
1703 case GNU_AK_NMI_HANDLER:
1704 case GNU_AK_NESTING:
1708 case GNU_AK_EIGTHBIT_DATA:
1709 case GNU_AK_TINY_DATA:
1710 case GNU_AK_SAVEALL:
1711 case GNU_AK_FLATTEN:
1712 case GNU_AK_SSEREGPARM:
1713 case GNU_AK_EXTERNALLY_VISIBLE:
1714 case GNU_AK_RETURN_TWICE:
1715 case GNU_AK_MAY_ALIAS:
1716 case GNU_AK_MS_STRUCT:
1717 case GNU_AK_GCC_STRUCT:
1720 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1721 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1722 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1723 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1724 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1725 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1726 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1727 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1728 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1729 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1730 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1731 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1732 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1733 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1734 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1735 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1736 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1738 case GNU_AK_ALIGNED:
1739 /* __align__ may be used without an argument */
1740 if (attribute->have_arguments) {
1741 parse_gnu_attribute_const_arg(attribute);
1745 case GNU_AK_FORMAT_ARG:
1746 case GNU_AK_REGPARM:
1747 case GNU_AK_TRAP_EXIT:
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_const_arg(attribute);
1756 case GNU_AK_SECTION:
1757 case GNU_AK_SP_SWITCH:
1758 if (!attribute->have_arguments) {
1759 /* should have arguments */
1760 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1761 attribute->invalid = true;
1763 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1766 if (!attribute->have_arguments) {
1767 /* should have arguments */
1768 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1769 attribute->invalid = true;
1771 parse_gnu_attribute_format_args(attribute);
1773 case GNU_AK_WEAKREF:
1774 /* may have one string argument */
1775 if (attribute->have_arguments)
1776 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1778 case GNU_AK_NONNULL:
1779 if (attribute->have_arguments)
1780 parse_gnu_attribute_const_arg_list(attribute);
1782 case GNU_AK_TLS_MODEL:
1783 if (!attribute->have_arguments) {
1784 /* should have arguments */
1785 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1787 parse_gnu_attribute_tls_model_arg(attribute);
1789 case GNU_AK_VISIBILITY:
1790 if (!attribute->have_arguments) {
1791 /* should have arguments */
1792 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1794 parse_gnu_attribute_visibility_arg(attribute);
1797 if (!attribute->have_arguments) {
1798 /* should have arguments */
1799 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1801 parse_gnu_attribute_model_arg(attribute);
1805 if (!attribute->have_arguments) {
1806 /* should have arguments */
1807 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1809 parse_gnu_attribute_mode_arg(attribute);
1812 case GNU_AK_INTERRUPT:
1813 /* may have one string argument */
1814 if (attribute->have_arguments)
1815 parse_gnu_attribute_interrupt_arg(attribute);
1817 case GNU_AK_SENTINEL:
1818 /* may have one string argument */
1819 if (attribute->have_arguments)
1820 parse_gnu_attribute_const_arg(attribute);
1823 /* already handled */
1827 check_no_argument(attribute, name);
1830 if (attribute != NULL) {
1832 last->next = attribute;
1835 head = last = attribute;
1839 if (token.type != ',')
1853 * Parse GNU attributes.
1855 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1857 decl_modifiers_t modifiers = 0;
1860 switch(token.type) {
1861 case T___attribute__:
1862 modifiers |= parse_gnu_attribute(attributes);
1868 if (token.type != T_STRING_LITERAL) {
1869 parse_error_expected("while parsing assembler attribute",
1870 T_STRING_LITERAL, NULL);
1871 eat_until_matching_token('(');
1874 parse_string_literals();
1879 case T_cdecl: modifiers |= DM_CDECL; break;
1880 case T__fastcall: modifiers |= DM_FASTCALL; break;
1881 case T__stdcall: modifiers |= DM_STDCALL; break;
1884 /* TODO record modifier */
1885 warningf(HERE, "Ignoring declaration modifier %K", &token);
1889 default: return modifiers;
1896 static designator_t *parse_designation(void)
1898 designator_t *result = NULL;
1899 designator_t *last = NULL;
1902 designator_t *designator;
1903 switch(token.type) {
1905 designator = allocate_ast_zero(sizeof(designator[0]));
1906 designator->source_position = token.source_position;
1908 add_anchor_token(']');
1909 designator->array_index = parse_constant_expression();
1910 rem_anchor_token(']');
1914 designator = allocate_ast_zero(sizeof(designator[0]));
1915 designator->source_position = token.source_position;
1917 if (token.type != T_IDENTIFIER) {
1918 parse_error_expected("while parsing designator",
1919 T_IDENTIFIER, NULL);
1922 designator->symbol = token.v.symbol;
1930 assert(designator != NULL);
1932 last->next = designator;
1934 result = designator;
1942 static initializer_t *initializer_from_string(array_type_t *type,
1943 const string_t *const string)
1945 /* TODO: check len vs. size of array type */
1948 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1949 initializer->string.string = *string;
1954 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1955 wide_string_t *const string)
1957 /* TODO: check len vs. size of array type */
1960 initializer_t *const initializer =
1961 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1962 initializer->wide_string.string = *string;
1968 * Build an initializer from a given expression.
1970 static initializer_t *initializer_from_expression(type_t *orig_type,
1971 expression_t *expression)
1973 /* TODO check that expression is a constant expression */
1975 /* § 6.7.8.14/15 char array may be initialized by string literals */
1976 type_t *type = skip_typeref(orig_type);
1977 type_t *expr_type_orig = expression->base.type;
1978 type_t *expr_type = skip_typeref(expr_type_orig);
1979 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1980 array_type_t *const array_type = &type->array;
1981 type_t *const element_type = skip_typeref(array_type->element_type);
1983 if (element_type->kind == TYPE_ATOMIC) {
1984 atomic_type_kind_t akind = element_type->atomic.akind;
1985 switch (expression->kind) {
1986 case EXPR_STRING_LITERAL:
1987 if (akind == ATOMIC_TYPE_CHAR
1988 || akind == ATOMIC_TYPE_SCHAR
1989 || akind == ATOMIC_TYPE_UCHAR) {
1990 return initializer_from_string(array_type,
1991 &expression->string.value);
1994 case EXPR_WIDE_STRING_LITERAL: {
1995 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1996 if (get_unqualified_type(element_type) == bare_wchar_type) {
1997 return initializer_from_wide_string(array_type,
1998 &expression->wide_string.value);
2008 assign_error_t error = semantic_assign(type, expression);
2009 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2011 report_assign_error(error, type, expression, "initializer",
2012 &expression->base.source_position);
2014 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2015 result->value.value = create_implicit_cast(expression, type);
2021 * Checks if a given expression can be used as an constant initializer.
2023 static bool is_initializer_constant(const expression_t *expression)
2025 return is_constant_expression(expression)
2026 || is_address_constant(expression);
2030 * Parses an scalar initializer.
2032 * § 6.7.8.11; eat {} without warning
2034 static initializer_t *parse_scalar_initializer(type_t *type,
2035 bool must_be_constant)
2037 /* there might be extra {} hierarchies */
2039 if (token.type == '{') {
2040 warningf(HERE, "extra curly braces around scalar initializer");
2044 } while (token.type == '{');
2047 expression_t *expression = parse_assignment_expression();
2048 if (must_be_constant && !is_initializer_constant(expression)) {
2049 errorf(&expression->base.source_position,
2050 "Initialisation expression '%E' is not constant\n",
2054 initializer_t *initializer = initializer_from_expression(type, expression);
2056 if (initializer == NULL) {
2057 errorf(&expression->base.source_position,
2058 "expression '%E' (type '%T') doesn't match expected type '%T'",
2059 expression, expression->base.type, type);
2064 bool additional_warning_displayed = false;
2065 while (braces > 0) {
2066 if (token.type == ',') {
2069 if (token.type != '}') {
2070 if (!additional_warning_displayed) {
2071 warningf(HERE, "additional elements in scalar initializer");
2072 additional_warning_displayed = true;
2083 * An entry in the type path.
2085 typedef struct type_path_entry_t type_path_entry_t;
2086 struct type_path_entry_t {
2087 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2089 size_t index; /**< For array types: the current index. */
2090 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2095 * A type path expression a position inside compound or array types.
2097 typedef struct type_path_t type_path_t;
2098 struct type_path_t {
2099 type_path_entry_t *path; /**< An flexible array containing the current path. */
2100 type_t *top_type; /**< type of the element the path points */
2101 size_t max_index; /**< largest index in outermost array */
2105 * Prints a type path for debugging.
2107 static __attribute__((unused)) void debug_print_type_path(
2108 const type_path_t *path)
2110 size_t len = ARR_LEN(path->path);
2112 for(size_t i = 0; i < len; ++i) {
2113 const type_path_entry_t *entry = & path->path[i];
2115 type_t *type = skip_typeref(entry->type);
2116 if (is_type_compound(type)) {
2117 /* in gcc mode structs can have no members */
2118 if (entry->v.compound_entry == NULL) {
2122 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2123 } else if (is_type_array(type)) {
2124 fprintf(stderr, "[%zu]", entry->v.index);
2126 fprintf(stderr, "-INVALID-");
2129 if (path->top_type != NULL) {
2130 fprintf(stderr, " (");
2131 print_type(path->top_type);
2132 fprintf(stderr, ")");
2137 * Return the top type path entry, ie. in a path
2138 * (type).a.b returns the b.
2140 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2142 size_t len = ARR_LEN(path->path);
2144 return &path->path[len-1];
2148 * Enlarge the type path by an (empty) element.
2150 static type_path_entry_t *append_to_type_path(type_path_t *path)
2152 size_t len = ARR_LEN(path->path);
2153 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2155 type_path_entry_t *result = & path->path[len];
2156 memset(result, 0, sizeof(result[0]));
2161 * Descending into a sub-type. Enter the scope of the current
2164 static void descend_into_subtype(type_path_t *path)
2166 type_t *orig_top_type = path->top_type;
2167 type_t *top_type = skip_typeref(orig_top_type);
2169 type_path_entry_t *top = append_to_type_path(path);
2170 top->type = top_type;
2172 if (is_type_compound(top_type)) {
2173 declaration_t *declaration = top_type->compound.declaration;
2174 declaration_t *entry = declaration->scope.declarations;
2175 top->v.compound_entry = entry;
2177 if (entry != NULL) {
2178 path->top_type = entry->type;
2180 path->top_type = NULL;
2182 } else if (is_type_array(top_type)) {
2184 path->top_type = top_type->array.element_type;
2186 assert(!is_type_valid(top_type));
2191 * Pop an entry from the given type path, ie. returning from
2192 * (type).a.b to (type).a
2194 static void ascend_from_subtype(type_path_t *path)
2196 type_path_entry_t *top = get_type_path_top(path);
2198 path->top_type = top->type;
2200 size_t len = ARR_LEN(path->path);
2201 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2205 * Pop entries from the given type path until the given
2206 * path level is reached.
2208 static void ascend_to(type_path_t *path, size_t top_path_level)
2210 size_t len = ARR_LEN(path->path);
2212 while (len > top_path_level) {
2213 ascend_from_subtype(path);
2214 len = ARR_LEN(path->path);
2218 static bool walk_designator(type_path_t *path, const designator_t *designator,
2219 bool used_in_offsetof)
2221 for( ; designator != NULL; designator = designator->next) {
2222 type_path_entry_t *top = get_type_path_top(path);
2223 type_t *orig_type = top->type;
2225 type_t *type = skip_typeref(orig_type);
2227 if (designator->symbol != NULL) {
2228 symbol_t *symbol = designator->symbol;
2229 if (!is_type_compound(type)) {
2230 if (is_type_valid(type)) {
2231 errorf(&designator->source_position,
2232 "'.%Y' designator used for non-compound type '%T'",
2238 declaration_t *declaration = type->compound.declaration;
2239 declaration_t *iter = declaration->scope.declarations;
2240 for( ; iter != NULL; iter = iter->next) {
2241 if (iter->symbol == symbol) {
2246 errorf(&designator->source_position,
2247 "'%T' has no member named '%Y'", orig_type, symbol);
2250 if (used_in_offsetof) {
2251 type_t *real_type = skip_typeref(iter->type);
2252 if (real_type->kind == TYPE_BITFIELD) {
2253 errorf(&designator->source_position,
2254 "offsetof designator '%Y' may not specify bitfield",
2260 top->type = orig_type;
2261 top->v.compound_entry = iter;
2262 orig_type = iter->type;
2264 expression_t *array_index = designator->array_index;
2265 assert(designator->array_index != NULL);
2267 if (!is_type_array(type)) {
2268 if (is_type_valid(type)) {
2269 errorf(&designator->source_position,
2270 "[%E] designator used for non-array type '%T'",
2271 array_index, orig_type);
2275 if (!is_type_valid(array_index->base.type)) {
2279 long index = fold_constant(array_index);
2280 if (!used_in_offsetof) {
2282 errorf(&designator->source_position,
2283 "array index [%E] must be positive", array_index);
2286 if (type->array.size_constant == true) {
2287 long array_size = type->array.size;
2288 if (index >= array_size) {
2289 errorf(&designator->source_position,
2290 "designator [%E] (%d) exceeds array size %d",
2291 array_index, index, array_size);
2297 top->type = orig_type;
2298 top->v.index = (size_t) index;
2299 orig_type = type->array.element_type;
2301 path->top_type = orig_type;
2303 if (designator->next != NULL) {
2304 descend_into_subtype(path);
2313 static void advance_current_object(type_path_t *path, size_t top_path_level)
2315 type_path_entry_t *top = get_type_path_top(path);
2317 type_t *type = skip_typeref(top->type);
2318 if (is_type_union(type)) {
2319 /* in unions only the first element is initialized */
2320 top->v.compound_entry = NULL;
2321 } else if (is_type_struct(type)) {
2322 declaration_t *entry = top->v.compound_entry;
2324 entry = entry->next;
2325 top->v.compound_entry = entry;
2326 if (entry != NULL) {
2327 path->top_type = entry->type;
2331 assert(is_type_array(type));
2335 if (!type->array.size_constant || top->v.index < type->array.size) {
2340 /* we're past the last member of the current sub-aggregate, try if we
2341 * can ascend in the type hierarchy and continue with another subobject */
2342 size_t len = ARR_LEN(path->path);
2344 if (len > top_path_level) {
2345 ascend_from_subtype(path);
2346 advance_current_object(path, top_path_level);
2348 path->top_type = NULL;
2353 * skip until token is found.
2355 static void skip_until(int type)
2357 while (token.type != type) {
2358 if (token.type == T_EOF)
2365 * skip any {...} blocks until a closing bracket is reached.
2367 static void skip_initializers(void)
2369 if (token.type == '{')
2372 while (token.type != '}') {
2373 if (token.type == T_EOF)
2375 if (token.type == '{') {
2383 static initializer_t *create_empty_initializer(void)
2385 static initializer_t empty_initializer
2386 = { .list = { { INITIALIZER_LIST }, 0 } };
2387 return &empty_initializer;
2391 * Parse a part of an initialiser for a struct or union,
2393 static initializer_t *parse_sub_initializer(type_path_t *path,
2394 type_t *outer_type, size_t top_path_level,
2395 parse_initializer_env_t *env)
2397 if (token.type == '}') {
2398 /* empty initializer */
2399 return create_empty_initializer();
2402 type_t *orig_type = path->top_type;
2403 type_t *type = NULL;
2405 if (orig_type == NULL) {
2406 /* We are initializing an empty compound. */
2408 type = skip_typeref(orig_type);
2410 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2411 * initializers in this case. */
2412 if (!is_type_valid(type)) {
2413 skip_initializers();
2414 return create_empty_initializer();
2418 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2421 designator_t *designator = NULL;
2422 if (token.type == '.' || token.type == '[') {
2423 designator = parse_designation();
2424 goto finish_designator;
2425 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2426 /* GNU-style designator ("identifier: value") */
2427 designator = allocate_ast_zero(sizeof(designator[0]));
2428 designator->source_position = token.source_position;
2429 designator->symbol = token.v.symbol;
2434 /* reset path to toplevel, evaluate designator from there */
2435 ascend_to(path, top_path_level);
2436 if (!walk_designator(path, designator, false)) {
2437 /* can't continue after designation error */
2441 initializer_t *designator_initializer
2442 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2443 designator_initializer->designator.designator = designator;
2444 ARR_APP1(initializer_t*, initializers, designator_initializer);
2446 orig_type = path->top_type;
2447 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2452 if (token.type == '{') {
2453 if (type != NULL && is_type_scalar(type)) {
2454 sub = parse_scalar_initializer(type, env->must_be_constant);
2458 if (env->declaration != NULL) {
2459 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2460 env->declaration->symbol);
2462 errorf(HERE, "extra brace group at end of initializer");
2465 descend_into_subtype(path);
2467 add_anchor_token('}');
2468 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2470 rem_anchor_token('}');
2473 ascend_from_subtype(path);
2477 goto error_parse_next;
2481 /* must be an expression */
2482 expression_t *expression = parse_assignment_expression();
2484 if (env->must_be_constant && !is_initializer_constant(expression)) {
2485 errorf(&expression->base.source_position,
2486 "Initialisation expression '%E' is not constant\n",
2491 /* we are already outside, ... */
2492 if (is_type_compound(outer_type) &&
2493 !outer_type->compound.declaration->init.complete) {
2494 goto error_parse_next;
2499 /* handle { "string" } special case */
2500 if ((expression->kind == EXPR_STRING_LITERAL
2501 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2502 && outer_type != NULL) {
2503 sub = initializer_from_expression(outer_type, expression);
2505 if (token.type == ',') {
2508 if (token.type != '}') {
2509 warningf(HERE, "excessive elements in initializer for type '%T'",
2512 /* TODO: eat , ... */
2517 /* descend into subtypes until expression matches type */
2519 orig_type = path->top_type;
2520 type = skip_typeref(orig_type);
2522 sub = initializer_from_expression(orig_type, expression);
2526 if (!is_type_valid(type)) {
2529 if (is_type_scalar(type)) {
2530 errorf(&expression->base.source_position,
2531 "expression '%E' doesn't match expected type '%T'",
2532 expression, orig_type);
2536 descend_into_subtype(path);
2540 /* update largest index of top array */
2541 const type_path_entry_t *first = &path->path[0];
2542 type_t *first_type = first->type;
2543 first_type = skip_typeref(first_type);
2544 if (is_type_array(first_type)) {
2545 size_t index = first->v.index;
2546 if (index > path->max_index)
2547 path->max_index = index;
2551 /* append to initializers list */
2552 ARR_APP1(initializer_t*, initializers, sub);
2555 if (env->declaration != NULL)
2556 warningf(HERE, "excess elements in struct initializer for '%Y'",
2557 env->declaration->symbol);
2559 warningf(HERE, "excess elements in struct initializer");
2563 if (token.type == '}') {
2567 if (token.type == '}') {
2572 /* advance to the next declaration if we are not at the end */
2573 advance_current_object(path, top_path_level);
2574 orig_type = path->top_type;
2575 if (orig_type != NULL)
2576 type = skip_typeref(orig_type);
2582 size_t len = ARR_LEN(initializers);
2583 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2584 initializer_t *result = allocate_ast_zero(size);
2585 result->kind = INITIALIZER_LIST;
2586 result->list.len = len;
2587 memcpy(&result->list.initializers, initializers,
2588 len * sizeof(initializers[0]));
2590 DEL_ARR_F(initializers);
2591 ascend_to(path, top_path_level+1);
2596 skip_initializers();
2597 DEL_ARR_F(initializers);
2598 ascend_to(path, top_path_level+1);
2603 * Parses an initializer. Parsers either a compound literal
2604 * (env->declaration == NULL) or an initializer of a declaration.
2606 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2608 type_t *type = skip_typeref(env->type);
2609 initializer_t *result = NULL;
2612 if (is_type_scalar(type)) {
2613 result = parse_scalar_initializer(type, env->must_be_constant);
2614 } else if (token.type == '{') {
2618 memset(&path, 0, sizeof(path));
2619 path.top_type = env->type;
2620 path.path = NEW_ARR_F(type_path_entry_t, 0);
2622 descend_into_subtype(&path);
2624 add_anchor_token('}');
2625 result = parse_sub_initializer(&path, env->type, 1, env);
2626 rem_anchor_token('}');
2628 max_index = path.max_index;
2629 DEL_ARR_F(path.path);
2633 /* parse_scalar_initializer() also works in this case: we simply
2634 * have an expression without {} around it */
2635 result = parse_scalar_initializer(type, env->must_be_constant);
2638 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2639 * the array type size */
2640 if (is_type_array(type) && type->array.size_expression == NULL
2641 && result != NULL) {
2643 switch (result->kind) {
2644 case INITIALIZER_LIST:
2645 size = max_index + 1;
2648 case INITIALIZER_STRING:
2649 size = result->string.string.size;
2652 case INITIALIZER_WIDE_STRING:
2653 size = result->wide_string.string.size;
2656 case INITIALIZER_DESIGNATOR:
2657 case INITIALIZER_VALUE:
2658 /* can happen for parse errors */
2663 internal_errorf(HERE, "invalid initializer type");
2666 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2667 cnst->base.type = type_size_t;
2668 cnst->conste.v.int_value = size;
2670 type_t *new_type = duplicate_type(type);
2672 new_type->array.size_expression = cnst;
2673 new_type->array.size_constant = true;
2674 new_type->array.size = size;
2675 env->type = new_type;
2683 static declaration_t *append_declaration(declaration_t *declaration);
2685 static declaration_t *parse_compound_type_specifier(bool is_struct)
2687 gnu_attribute_t *attributes = NULL;
2688 decl_modifiers_t modifiers = 0;
2695 symbol_t *symbol = NULL;
2696 declaration_t *declaration = NULL;
2698 if (token.type == T___attribute__) {
2699 modifiers |= parse_attributes(&attributes);
2702 if (token.type == T_IDENTIFIER) {
2703 symbol = token.v.symbol;
2706 namespace_t const namespc =
2707 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2708 declaration = get_declaration(symbol, namespc);
2709 if (declaration != NULL) {
2710 if (declaration->parent_scope != scope &&
2711 (token.type == '{' || token.type == ';')) {
2713 } else if (declaration->init.complete &&
2714 token.type == '{') {
2715 assert(symbol != NULL);
2716 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2717 is_struct ? "struct" : "union", symbol,
2718 &declaration->source_position);
2719 declaration->scope.declarations = NULL;
2722 } else if (token.type != '{') {
2724 parse_error_expected("while parsing struct type specifier",
2725 T_IDENTIFIER, '{', NULL);
2727 parse_error_expected("while parsing union type specifier",
2728 T_IDENTIFIER, '{', NULL);
2734 if (declaration == NULL) {
2735 declaration = allocate_declaration_zero();
2736 declaration->namespc =
2737 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2738 declaration->source_position = token.source_position;
2739 declaration->symbol = symbol;
2740 declaration->parent_scope = scope;
2741 if (symbol != NULL) {
2742 environment_push(declaration);
2744 append_declaration(declaration);
2747 if (token.type == '{') {
2748 declaration->init.complete = true;
2750 parse_compound_type_entries(declaration);
2751 modifiers |= parse_attributes(&attributes);
2754 declaration->modifiers |= modifiers;
2758 static void parse_enum_entries(type_t *const enum_type)
2762 if (token.type == '}') {
2764 errorf(HERE, "empty enum not allowed");
2768 add_anchor_token('}');
2770 if (token.type != T_IDENTIFIER) {
2771 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2773 rem_anchor_token('}');
2777 declaration_t *const entry = allocate_declaration_zero();
2778 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2779 entry->type = enum_type;
2780 entry->symbol = token.v.symbol;
2781 entry->source_position = token.source_position;
2784 if (token.type == '=') {
2786 expression_t *value = parse_constant_expression();
2788 value = create_implicit_cast(value, enum_type);
2789 entry->init.enum_value = value;
2794 record_declaration(entry, false);
2796 if (token.type != ',')
2799 } while (token.type != '}');
2800 rem_anchor_token('}');
2808 static type_t *parse_enum_specifier(void)
2810 gnu_attribute_t *attributes = NULL;
2811 declaration_t *declaration;
2815 if (token.type == T_IDENTIFIER) {
2816 symbol = token.v.symbol;
2819 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2820 } else if (token.type != '{') {
2821 parse_error_expected("while parsing enum type specifier",
2822 T_IDENTIFIER, '{', NULL);
2829 if (declaration == NULL) {
2830 declaration = allocate_declaration_zero();
2831 declaration->namespc = NAMESPACE_ENUM;
2832 declaration->source_position = token.source_position;
2833 declaration->symbol = symbol;
2834 declaration->parent_scope = scope;
2837 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2838 type->enumt.declaration = declaration;
2840 if (token.type == '{') {
2841 if (declaration->init.complete) {
2842 errorf(HERE, "multiple definitions of enum %Y", symbol);
2844 if (symbol != NULL) {
2845 environment_push(declaration);
2847 append_declaration(declaration);
2848 declaration->init.complete = true;
2850 parse_enum_entries(type);
2851 parse_attributes(&attributes);
2858 * if a symbol is a typedef to another type, return true
2860 static bool is_typedef_symbol(symbol_t *symbol)
2862 const declaration_t *const declaration =
2863 get_declaration(symbol, NAMESPACE_NORMAL);
2865 declaration != NULL &&
2866 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2869 static type_t *parse_typeof(void)
2876 add_anchor_token(')');
2878 expression_t *expression = NULL;
2880 bool old_type_prop = in_type_prop;
2881 bool old_gcc_extension = in_gcc_extension;
2882 in_type_prop = true;
2884 while (token.type == T___extension__) {
2885 /* This can be a prefix to a typename or an expression. */
2887 in_gcc_extension = true;
2889 switch (token.type) {
2891 if (is_typedef_symbol(token.v.symbol)) {
2892 type = parse_typename();
2894 expression = parse_expression();
2895 type = expression->base.type;
2900 type = parse_typename();
2904 expression = parse_expression();
2905 type = expression->base.type;
2908 in_type_prop = old_type_prop;
2909 in_gcc_extension = old_gcc_extension;
2911 rem_anchor_token(')');
2914 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2915 typeof_type->typeoft.expression = expression;
2916 typeof_type->typeoft.typeof_type = type;
2923 typedef enum specifiers_t {
2924 SPECIFIER_SIGNED = 1 << 0,
2925 SPECIFIER_UNSIGNED = 1 << 1,
2926 SPECIFIER_LONG = 1 << 2,
2927 SPECIFIER_INT = 1 << 3,
2928 SPECIFIER_DOUBLE = 1 << 4,
2929 SPECIFIER_CHAR = 1 << 5,
2930 SPECIFIER_SHORT = 1 << 6,
2931 SPECIFIER_LONG_LONG = 1 << 7,
2932 SPECIFIER_FLOAT = 1 << 8,
2933 SPECIFIER_BOOL = 1 << 9,
2934 SPECIFIER_VOID = 1 << 10,
2935 SPECIFIER_INT8 = 1 << 11,
2936 SPECIFIER_INT16 = 1 << 12,
2937 SPECIFIER_INT32 = 1 << 13,
2938 SPECIFIER_INT64 = 1 << 14,
2939 SPECIFIER_INT128 = 1 << 15,
2940 SPECIFIER_COMPLEX = 1 << 16,
2941 SPECIFIER_IMAGINARY = 1 << 17,
2944 static type_t *create_builtin_type(symbol_t *const symbol,
2945 type_t *const real_type)
2947 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2948 type->builtin.symbol = symbol;
2949 type->builtin.real_type = real_type;
2951 type_t *result = typehash_insert(type);
2952 if (type != result) {
2959 static type_t *get_typedef_type(symbol_t *symbol)
2961 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2962 if (declaration == NULL ||
2963 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2966 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2967 type->typedeft.declaration = declaration;
2973 * check for the allowed MS alignment values.
2975 static bool check_alignment_value(long long intvalue)
2977 if (intvalue < 1 || intvalue > 8192) {
2978 errorf(HERE, "illegal alignment value");
2981 unsigned v = (unsigned)intvalue;
2982 for (unsigned i = 1; i <= 8192; i += i) {
2986 errorf(HERE, "alignment must be power of two");
2990 #define DET_MOD(name, tag) do { \
2991 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2992 *modifiers |= tag; \
2995 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2997 decl_modifiers_t *modifiers = &specifiers->modifiers;
3000 if (token.type == T_restrict) {
3002 DET_MOD(restrict, DM_RESTRICT);
3004 } else if (token.type != T_IDENTIFIER)
3006 symbol_t *symbol = token.v.symbol;
3007 if (symbol == sym_align) {
3010 if (token.type != T_INTEGER)
3012 if (check_alignment_value(token.v.intvalue)) {
3013 if (specifiers->alignment != 0)
3014 warningf(HERE, "align used more than once");
3015 specifiers->alignment = (unsigned char)token.v.intvalue;
3019 } else if (symbol == sym_allocate) {
3022 if (token.type != T_IDENTIFIER)
3024 (void)token.v.symbol;
3026 } else if (symbol == sym_dllimport) {
3028 DET_MOD(dllimport, DM_DLLIMPORT);
3029 } else if (symbol == sym_dllexport) {
3031 DET_MOD(dllexport, DM_DLLEXPORT);
3032 } else if (symbol == sym_thread) {
3034 DET_MOD(thread, DM_THREAD);
3035 } else if (symbol == sym_naked) {
3037 DET_MOD(naked, DM_NAKED);
3038 } else if (symbol == sym_noinline) {
3040 DET_MOD(noinline, DM_NOINLINE);
3041 } else if (symbol == sym_noreturn) {
3043 DET_MOD(noreturn, DM_NORETURN);
3044 } else if (symbol == sym_nothrow) {
3046 DET_MOD(nothrow, DM_NOTHROW);
3047 } else if (symbol == sym_novtable) {
3049 DET_MOD(novtable, DM_NOVTABLE);
3050 } else if (symbol == sym_property) {
3054 bool is_get = false;
3055 if (token.type != T_IDENTIFIER)
3057 if (token.v.symbol == sym_get) {
3059 } else if (token.v.symbol == sym_put) {
3061 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3066 if (token.type != T_IDENTIFIER)
3069 if (specifiers->get_property_sym != NULL) {
3070 errorf(HERE, "get property name already specified");
3072 specifiers->get_property_sym = token.v.symbol;
3075 if (specifiers->put_property_sym != NULL) {
3076 errorf(HERE, "put property name already specified");
3078 specifiers->put_property_sym = token.v.symbol;
3082 if (token.type == ',') {
3089 } else if (symbol == sym_selectany) {
3091 DET_MOD(selectany, DM_SELECTANY);
3092 } else if (symbol == sym_uuid) {
3095 if (token.type != T_STRING_LITERAL)
3099 } else if (symbol == sym_deprecated) {
3101 if (specifiers->deprecated != 0)
3102 warningf(HERE, "deprecated used more than once");
3103 specifiers->deprecated = 1;
3104 if (token.type == '(') {
3106 if (token.type == T_STRING_LITERAL) {
3107 specifiers->deprecated_string = token.v.string.begin;
3110 errorf(HERE, "string literal expected");
3114 } else if (symbol == sym_noalias) {
3116 DET_MOD(noalias, DM_NOALIAS);
3118 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3120 if (token.type == '(')
3124 if (token.type == ',')
3131 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3133 declaration_t *const decl = allocate_declaration_zero();
3134 decl->source_position = *HERE;
3135 decl->declared_storage_class = storage_class;
3136 decl->storage_class =
3137 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3138 storage_class : STORAGE_CLASS_AUTO;
3139 decl->symbol = symbol;
3140 decl->implicit = true;
3141 record_declaration(decl, false);
3146 * Finish the construction of a struct type by calculating
3147 * its size, offsets, alignment.
3149 static void finish_struct_type(compound_type_t *type) {
3150 if (type->declaration == NULL)
3152 declaration_t *struct_decl = type->declaration;
3153 if (! struct_decl->init.complete)
3158 il_alignment_t alignment = 1;
3159 bool need_pad = false;
3161 declaration_t *entry = struct_decl->scope.declarations;
3162 for (; entry != NULL; entry = entry->next) {
3163 if (entry->namespc != NAMESPACE_NORMAL)
3166 type_t *m_type = skip_typeref(entry->type);
3167 if (! is_type_valid(m_type)) {
3168 /* simply ignore errors here */
3171 il_alignment_t m_alignment = m_type->base.alignment;
3172 if (m_alignment > alignment)
3173 alignment = m_alignment;
3175 offset = (size + m_alignment - 1) & -m_alignment;
3179 entry->offset = offset;
3180 size = offset + m_type->base.size;
3182 if (type->base.alignment != 0) {
3183 alignment = type->base.alignment;
3186 offset = (size + alignment - 1) & -alignment;
3190 if (warning.padded && need_pad) {
3191 warningf(&struct_decl->source_position,
3192 "'%#T' needs padding", type, struct_decl->symbol);
3194 if (warning.packed && !need_pad) {
3195 warningf(&struct_decl->source_position,
3196 "superfluous packed attribute on '%#T'",
3197 type, struct_decl->symbol);
3200 type->base.size = offset;
3201 type->base.alignment = alignment;
3205 * Finish the construction of an union type by calculating
3206 * its size and alignment.
3208 static void finish_union_type(compound_type_t *type) {
3209 if (type->declaration == NULL)
3211 declaration_t *union_decl = type->declaration;
3212 if (! union_decl->init.complete)
3216 il_alignment_t alignment = 1;
3218 declaration_t *entry = union_decl->scope.declarations;
3219 for (; entry != NULL; entry = entry->next) {
3220 if (entry->namespc != NAMESPACE_NORMAL)
3223 type_t *m_type = skip_typeref(entry->type);
3224 if (! is_type_valid(m_type))
3228 if (m_type->base.size > size)
3229 size = m_type->base.size;
3230 if (m_type->base.alignment > alignment)
3231 alignment = m_type->base.alignment;
3233 if (type->base.alignment != 0) {
3234 alignment = type->base.alignment;
3236 size = (size + alignment - 1) & -alignment;
3237 type->base.size = size;
3238 type->base.alignment = alignment;
3241 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3243 type_t *type = NULL;
3244 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3245 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3246 unsigned type_specifiers = 0;
3247 bool newtype = false;
3248 bool saw_error = false;
3249 bool old_gcc_extension = in_gcc_extension;
3251 specifiers->source_position = token.source_position;
3254 specifiers->modifiers
3255 |= parse_attributes(&specifiers->gnu_attributes);
3256 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3257 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3259 switch (token.type) {
3262 #define MATCH_STORAGE_CLASS(token, class) \
3264 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3265 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3267 specifiers->declared_storage_class = class; \
3271 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3272 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3273 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3274 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3275 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3280 add_anchor_token(')');
3281 parse_microsoft_extended_decl_modifier(specifiers);
3282 rem_anchor_token(')');
3287 switch (specifiers->declared_storage_class) {
3288 case STORAGE_CLASS_NONE:
3289 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3292 case STORAGE_CLASS_EXTERN:
3293 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3296 case STORAGE_CLASS_STATIC:
3297 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3301 errorf(HERE, "multiple storage classes in declaration specifiers");
3307 /* type qualifiers */
3308 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3310 qualifiers |= qualifier; \
3314 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3315 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3316 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3317 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3318 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3319 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3320 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3321 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3323 case T___extension__:
3325 in_gcc_extension = true;
3328 /* type specifiers */
3329 #define MATCH_SPECIFIER(token, specifier, name) \
3332 if (type_specifiers & specifier) { \
3333 errorf(HERE, "multiple " name " type specifiers given"); \
3335 type_specifiers |= specifier; \
3339 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3340 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3341 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3342 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3343 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3344 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3345 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3346 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3347 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3348 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3349 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3350 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3351 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3352 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3353 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3354 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3356 case T__forceinline:
3357 /* only in microsoft mode */
3358 specifiers->modifiers |= DM_FORCEINLINE;
3363 specifiers->is_inline = true;
3368 if (type_specifiers & SPECIFIER_LONG_LONG) {
3369 errorf(HERE, "multiple type specifiers given");
3370 } else if (type_specifiers & SPECIFIER_LONG) {
3371 type_specifiers |= SPECIFIER_LONG_LONG;
3373 type_specifiers |= SPECIFIER_LONG;
3378 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3380 type->compound.declaration = parse_compound_type_specifier(true);
3381 finish_struct_type(&type->compound);
3385 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3386 type->compound.declaration = parse_compound_type_specifier(false);
3387 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3388 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3390 finish_union_type(&type->compound);
3393 type = parse_enum_specifier();
3396 type = parse_typeof();
3398 case T___builtin_va_list:
3399 type = duplicate_type(type_valist);
3403 case T_IDENTIFIER: {
3404 /* only parse identifier if we haven't found a type yet */
3405 if (type != NULL || type_specifiers != 0) {
3406 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3407 * declaration, so it doesn't generate errors about expecting '(' or
3409 switch (look_ahead(1)->type) {
3416 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3419 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3424 goto finish_specifiers;
3428 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3429 if (typedef_type == NULL) {
3430 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3431 * declaration, so it doesn't generate 'implicit int' followed by more
3432 * errors later on. */
3433 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3438 errorf(HERE, "%K does not name a type", &token);
3440 declaration_t *const decl =
3441 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3443 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3444 type->typedeft.declaration = decl;
3448 if (la1_type == '*')
3449 goto finish_specifiers;
3454 goto finish_specifiers;
3459 type = typedef_type;
3463 /* function specifier */
3465 goto finish_specifiers;
3470 in_gcc_extension = old_gcc_extension;
3472 if (type == NULL || (saw_error && type_specifiers != 0)) {
3473 atomic_type_kind_t atomic_type;
3475 /* match valid basic types */
3476 switch(type_specifiers) {
3477 case SPECIFIER_VOID:
3478 atomic_type = ATOMIC_TYPE_VOID;
3480 case SPECIFIER_CHAR:
3481 atomic_type = ATOMIC_TYPE_CHAR;
3483 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3484 atomic_type = ATOMIC_TYPE_SCHAR;
3486 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3487 atomic_type = ATOMIC_TYPE_UCHAR;
3489 case SPECIFIER_SHORT:
3490 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3491 case SPECIFIER_SHORT | SPECIFIER_INT:
3492 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3493 atomic_type = ATOMIC_TYPE_SHORT;
3495 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3496 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3497 atomic_type = ATOMIC_TYPE_USHORT;
3500 case SPECIFIER_SIGNED:
3501 case SPECIFIER_SIGNED | SPECIFIER_INT:
3502 atomic_type = ATOMIC_TYPE_INT;
3504 case SPECIFIER_UNSIGNED:
3505 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3506 atomic_type = ATOMIC_TYPE_UINT;
3508 case SPECIFIER_LONG:
3509 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3510 case SPECIFIER_LONG | SPECIFIER_INT:
3511 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3512 atomic_type = ATOMIC_TYPE_LONG;
3514 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3515 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3516 atomic_type = ATOMIC_TYPE_ULONG;
3519 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3520 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3521 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3522 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3524 atomic_type = ATOMIC_TYPE_LONGLONG;
3525 goto warn_about_long_long;
3527 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3528 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3530 atomic_type = ATOMIC_TYPE_ULONGLONG;
3531 warn_about_long_long:
3532 if (warning.long_long) {
3533 warningf(&specifiers->source_position,
3534 "ISO C90 does not support 'long long'");
3538 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3539 atomic_type = unsigned_int8_type_kind;
3542 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3543 atomic_type = unsigned_int16_type_kind;
3546 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3547 atomic_type = unsigned_int32_type_kind;
3550 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3551 atomic_type = unsigned_int64_type_kind;
3554 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3555 atomic_type = unsigned_int128_type_kind;
3558 case SPECIFIER_INT8:
3559 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3560 atomic_type = int8_type_kind;
3563 case SPECIFIER_INT16:
3564 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3565 atomic_type = int16_type_kind;
3568 case SPECIFIER_INT32:
3569 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3570 atomic_type = int32_type_kind;
3573 case SPECIFIER_INT64:
3574 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3575 atomic_type = int64_type_kind;
3578 case SPECIFIER_INT128:
3579 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3580 atomic_type = int128_type_kind;
3583 case SPECIFIER_FLOAT:
3584 atomic_type = ATOMIC_TYPE_FLOAT;
3586 case SPECIFIER_DOUBLE:
3587 atomic_type = ATOMIC_TYPE_DOUBLE;
3589 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3590 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3592 case SPECIFIER_BOOL:
3593 atomic_type = ATOMIC_TYPE_BOOL;
3595 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3596 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3597 atomic_type = ATOMIC_TYPE_FLOAT;
3599 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3600 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3601 atomic_type = ATOMIC_TYPE_DOUBLE;
3603 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3604 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3605 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3608 /* invalid specifier combination, give an error message */
3609 if (type_specifiers == 0) {
3614 if (warning.implicit_int) {
3615 warningf(HERE, "no type specifiers in declaration, using 'int'");
3617 atomic_type = ATOMIC_TYPE_INT;
3620 errorf(HERE, "no type specifiers given in declaration");
3622 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3623 (type_specifiers & SPECIFIER_UNSIGNED)) {
3624 errorf(HERE, "signed and unsigned specifiers given");
3625 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3626 errorf(HERE, "only integer types can be signed or unsigned");
3628 errorf(HERE, "multiple datatypes in declaration");
3633 if (type_specifiers & SPECIFIER_COMPLEX) {
3634 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3635 type->complex.akind = atomic_type;
3636 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3637 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3638 type->imaginary.akind = atomic_type;
3640 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3641 type->atomic.akind = atomic_type;
3644 } else if (type_specifiers != 0) {
3645 errorf(HERE, "multiple datatypes in declaration");
3648 /* FIXME: check type qualifiers here */
3650 type->base.qualifiers = qualifiers;
3651 type->base.modifiers = modifiers;
3653 type_t *result = typehash_insert(type);
3654 if (newtype && result != type) {
3658 specifiers->type = result;
3662 specifiers->type = type_error_type;
3666 static type_qualifiers_t parse_type_qualifiers(void)
3668 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3671 switch(token.type) {
3672 /* type qualifiers */
3673 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3674 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3675 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3676 /* microsoft extended type modifiers */
3677 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3678 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3679 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3680 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3681 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3690 * Parses an K&R identifier list and return a list of declarations.
3692 * @param last points to the last declaration in the list
3693 * @return the list of declarations
3695 static declaration_t *parse_identifier_list(declaration_t **last)
3697 declaration_t *declarations = NULL;
3698 declaration_t *last_declaration = NULL;
3700 declaration_t *const declaration = allocate_declaration_zero();
3701 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3702 declaration->source_position = token.source_position;
3703 declaration->symbol = token.v.symbol;
3706 if (last_declaration != NULL) {
3707 last_declaration->next = declaration;
3709 declarations = declaration;
3711 last_declaration = declaration;
3713 if (token.type != ',') {
3717 } while (token.type == T_IDENTIFIER);
3719 *last = last_declaration;
3720 return declarations;
3723 static type_t *automatic_type_conversion(type_t *orig_type);
3725 static void semantic_parameter(declaration_t *declaration)
3727 /* TODO: improve error messages */
3728 source_position_t const* const pos = &declaration->source_position;
3730 switch (declaration->declared_storage_class) {
3731 case STORAGE_CLASS_TYPEDEF:
3732 errorf(pos, "typedef not allowed in parameter list");
3735 /* Allowed storage classes */
3736 case STORAGE_CLASS_NONE:
3737 case STORAGE_CLASS_REGISTER:
3741 errorf(pos, "parameter may only have none or register storage class");
3745 type_t *const orig_type = declaration->type;
3746 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3747 * sugar. Turn it into a pointer.
3748 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3749 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3751 type_t *const type = automatic_type_conversion(orig_type);
3752 declaration->type = type;
3754 if (is_type_incomplete(skip_typeref(type))) {
3755 errorf(pos, "parameter '%#T' is of incomplete type",
3756 orig_type, declaration->symbol);
3760 static declaration_t *parse_parameter(void)
3762 declaration_specifiers_t specifiers;
3763 memset(&specifiers, 0, sizeof(specifiers));
3765 parse_declaration_specifiers(&specifiers);
3767 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3773 * Parses a function type parameter list and return a list of declarations.
3775 * @param last point to the last element of the list
3776 * @return the parameter list
3778 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
3780 declaration_t *declarations = NULL;
3783 add_anchor_token(')');
3784 int saved_comma_state = save_and_reset_anchor_state(',');
3786 if (token.type == T_IDENTIFIER &&
3787 !is_typedef_symbol(token.v.symbol)) {
3788 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3789 if (la1_type == ',' || la1_type == ')') {
3790 type->kr_style_parameters = true;
3791 declarations = parse_identifier_list(last);
3792 goto parameters_finished;
3796 if (token.type == ')') {
3797 type->unspecified_parameters = 1;
3798 goto parameters_finished;
3801 declaration_t *declaration;
3802 declaration_t *last_declaration = NULL;
3803 function_parameter_t *parameter;
3804 function_parameter_t *last_parameter = NULL;
3807 switch(token.type) {
3811 goto parameters_finished;
3814 case T___extension__:
3816 declaration = parse_parameter();
3818 /* func(void) is not a parameter */
3819 if (last_parameter == NULL
3820 && token.type == ')'
3821 && declaration->symbol == NULL
3822 && skip_typeref(declaration->type) == type_void) {
3823 goto parameters_finished;
3825 semantic_parameter(declaration);
3827 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3828 memset(parameter, 0, sizeof(parameter[0]));
3829 parameter->type = declaration->type;
3831 if (last_parameter != NULL) {
3832 last_declaration->next = declaration;
3833 last_parameter->next = parameter;
3835 type->parameters = parameter;
3836 declarations = declaration;
3838 last_parameter = parameter;
3839 last_declaration = declaration;
3843 goto parameters_finished;
3845 if (token.type != ',') {
3846 goto parameters_finished;
3852 parameters_finished:
3853 rem_anchor_token(')');
3856 restore_anchor_state(',', saved_comma_state);
3857 *last = last_declaration;
3858 return declarations;
3861 restore_anchor_state(',', saved_comma_state);
3866 typedef enum construct_type_kind_t {
3871 } construct_type_kind_t;
3873 typedef struct construct_type_t construct_type_t;
3874 struct construct_type_t {
3875 construct_type_kind_t kind;
3876 construct_type_t *next;
3879 typedef struct parsed_pointer_t parsed_pointer_t;
3880 struct parsed_pointer_t {
3881 construct_type_t construct_type;
3882 type_qualifiers_t type_qualifiers;
3885 typedef struct construct_function_type_t construct_function_type_t;
3886 struct construct_function_type_t {
3887 construct_type_t construct_type;
3888 type_t *function_type;
3891 typedef struct parsed_array_t parsed_array_t;
3892 struct parsed_array_t {
3893 construct_type_t construct_type;
3894 type_qualifiers_t type_qualifiers;
3900 typedef struct construct_base_type_t construct_base_type_t;
3901 struct construct_base_type_t {
3902 construct_type_t construct_type;
3906 static construct_type_t *parse_pointer_declarator(void)
3910 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3911 memset(pointer, 0, sizeof(pointer[0]));
3912 pointer->construct_type.kind = CONSTRUCT_POINTER;
3913 pointer->type_qualifiers = parse_type_qualifiers();
3915 return (construct_type_t*) pointer;
3918 static construct_type_t *parse_array_declarator(void)
3921 add_anchor_token(']');
3923 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3924 memset(array, 0, sizeof(array[0]));
3925 array->construct_type.kind = CONSTRUCT_ARRAY;
3927 if (token.type == T_static) {
3928 array->is_static = true;
3932 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3933 if (type_qualifiers != 0) {
3934 if (token.type == T_static) {
3935 array->is_static = true;
3939 array->type_qualifiers = type_qualifiers;
3941 if (token.type == '*' && look_ahead(1)->type == ']') {
3942 array->is_variable = true;
3944 } else if (token.type != ']') {
3945 array->size = parse_assignment_expression();
3948 rem_anchor_token(']');
3952 return (construct_type_t*) array;
3955 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3958 if (declaration != NULL) {
3959 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3961 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3963 if (mask & (mask-1)) {
3964 const char *first = NULL, *second = NULL;
3966 /* more than one calling convention set */
3967 if (declaration->modifiers & DM_CDECL) {
3968 if (first == NULL) first = "cdecl";
3969 else if (second == NULL) second = "cdecl";
3971 if (declaration->modifiers & DM_STDCALL) {
3972 if (first == NULL) first = "stdcall";
3973 else if (second == NULL) second = "stdcall";
3975 if (declaration->modifiers & DM_FASTCALL) {
3976 if (first == NULL) first = "fastcall";
3977 else if (second == NULL) second = "fastcall";
3979 if (declaration->modifiers & DM_THISCALL) {
3980 if (first == NULL) first = "thiscall";
3981 else if (second == NULL) second = "thiscall";
3983 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3986 if (declaration->modifiers & DM_CDECL)
3987 type->function.calling_convention = CC_CDECL;
3988 else if (declaration->modifiers & DM_STDCALL)
3989 type->function.calling_convention = CC_STDCALL;
3990 else if (declaration->modifiers & DM_FASTCALL)
3991 type->function.calling_convention = CC_FASTCALL;
3992 else if (declaration->modifiers & DM_THISCALL)
3993 type->function.calling_convention = CC_THISCALL;
3995 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3998 declaration_t *last;
3999 declaration_t *parameters = parse_parameters(&type->function, &last);
4000 if (declaration != NULL) {
4001 declaration->scope.declarations = parameters;
4002 declaration->scope.last_declaration = last;
4003 declaration->scope.is_parameter = true;
4006 construct_function_type_t *construct_function_type =
4007 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4008 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4009 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4010 construct_function_type->function_type = type;
4012 return &construct_function_type->construct_type;
4015 static void fix_declaration_type(declaration_t *declaration)
4017 decl_modifiers_t declaration_modifiers = declaration->modifiers;
4018 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
4020 if (declaration_modifiers & DM_TRANSPARENT_UNION)
4021 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4023 if (declaration->type->base.modifiers == type_modifiers)
4026 type_t *copy = duplicate_type(declaration->type);
4027 copy->base.modifiers = type_modifiers;
4029 type_t *result = typehash_insert(copy);
4030 if (result != copy) {
4031 obstack_free(type_obst, copy);
4034 declaration->type = result;
4037 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4038 bool may_be_abstract)
4040 /* construct a single linked list of construct_type_t's which describe
4041 * how to construct the final declarator type */
4042 construct_type_t *first = NULL;
4043 construct_type_t *last = NULL;
4044 gnu_attribute_t *attributes = NULL;
4046 decl_modifiers_t modifiers = parse_attributes(&attributes);
4049 while (token.type == '*') {
4050 construct_type_t *type = parse_pointer_declarator();
4060 /* TODO: find out if this is correct */
4061 modifiers |= parse_attributes(&attributes);
4064 if (declaration != NULL)
4065 declaration->modifiers |= modifiers;
4067 construct_type_t *inner_types = NULL;
4069 switch(token.type) {
4071 if (declaration == NULL) {
4072 errorf(HERE, "no identifier expected in typename");
4074 declaration->symbol = token.v.symbol;
4075 declaration->source_position = token.source_position;
4081 add_anchor_token(')');
4082 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4083 if (inner_types != NULL) {
4084 /* All later declarators only modify the return type, not declaration */
4087 rem_anchor_token(')');
4091 if (may_be_abstract)
4093 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4098 construct_type_t *p = last;
4101 construct_type_t *type;
4102 switch(token.type) {
4104 type = parse_function_declarator(declaration);
4107 type = parse_array_declarator();
4110 goto declarator_finished;
4113 /* insert in the middle of the list (behind p) */
4115 type->next = p->next;
4126 declarator_finished:
4127 /* append inner_types at the end of the list, we don't to set last anymore
4128 * as it's not needed anymore */
4130 assert(first == NULL);
4131 first = inner_types;
4133 last->next = inner_types;
4141 static void parse_declaration_attributes(declaration_t *declaration)
4143 gnu_attribute_t *attributes = NULL;
4144 decl_modifiers_t modifiers = parse_attributes(&attributes);
4146 if (declaration == NULL)
4149 declaration->modifiers |= modifiers;
4150 /* check if we have these stupid mode attributes... */
4151 type_t *old_type = declaration->type;
4152 if (old_type == NULL)
4155 gnu_attribute_t *attribute = attributes;
4156 for ( ; attribute != NULL; attribute = attribute->next) {
4157 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4160 atomic_type_kind_t akind = attribute->u.akind;
4161 if (!is_type_signed(old_type)) {
4163 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4164 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4165 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4166 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4168 panic("invalid akind in mode attribute");
4172 = make_atomic_type(akind, old_type->base.qualifiers);
4176 static type_t *construct_declarator_type(construct_type_t *construct_list,
4179 construct_type_t *iter = construct_list;
4180 for( ; iter != NULL; iter = iter->next) {
4181 switch(iter->kind) {
4182 case CONSTRUCT_INVALID:
4183 internal_errorf(HERE, "invalid type construction found");
4184 case CONSTRUCT_FUNCTION: {
4185 construct_function_type_t *construct_function_type
4186 = (construct_function_type_t*) iter;
4188 type_t *function_type = construct_function_type->function_type;
4190 function_type->function.return_type = type;
4192 type_t *skipped_return_type = skip_typeref(type);
4194 if (is_type_function(skipped_return_type)) {
4195 errorf(HERE, "function returning function is not allowed");
4196 } else if (is_type_array(skipped_return_type)) {
4197 errorf(HERE, "function returning array is not allowed");
4199 if (skipped_return_type->base.qualifiers != 0) {
4201 "type qualifiers in return type of function type are meaningless");
4205 type = function_type;
4209 case CONSTRUCT_POINTER: {
4210 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4211 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4212 pointer_type->pointer.points_to = type;
4213 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4215 type = pointer_type;
4219 case CONSTRUCT_ARRAY: {
4220 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4221 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4223 expression_t *size_expression = parsed_array->size;
4224 if (size_expression != NULL) {
4226 = create_implicit_cast(size_expression, type_size_t);
4229 array_type->base.qualifiers = parsed_array->type_qualifiers;
4230 array_type->array.element_type = type;
4231 array_type->array.is_static = parsed_array->is_static;
4232 array_type->array.is_variable = parsed_array->is_variable;
4233 array_type->array.size_expression = size_expression;
4235 if (size_expression != NULL) {
4236 if (is_constant_expression(size_expression)) {
4237 array_type->array.size_constant = true;
4238 array_type->array.size
4239 = fold_constant(size_expression);
4241 array_type->array.is_vla = true;
4245 type_t *skipped_type = skip_typeref(type);
4247 if (is_type_incomplete(skipped_type)) {
4248 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4249 } else if (is_type_function(skipped_type)) {
4250 errorf(HERE, "array of functions is not allowed");
4257 type_t *hashed_type = typehash_insert(type);
4258 if (hashed_type != type) {
4259 /* the function type was constructed earlier freeing it here will
4260 * destroy other types... */
4261 if (iter->kind != CONSTRUCT_FUNCTION) {
4271 static declaration_t *parse_declarator(
4272 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4274 declaration_t *const declaration = allocate_declaration_zero();
4275 declaration->source_position = specifiers->source_position;
4276 declaration->declared_storage_class = specifiers->declared_storage_class;
4277 declaration->modifiers = specifiers->modifiers;
4278 declaration->deprecated_string = specifiers->deprecated_string;
4279 declaration->get_property_sym = specifiers->get_property_sym;
4280 declaration->put_property_sym = specifiers->put_property_sym;
4281 declaration->is_inline = specifiers->is_inline;
4283 declaration->storage_class = specifiers->declared_storage_class;
4284 if (declaration->storage_class == STORAGE_CLASS_NONE
4285 && scope != global_scope) {
4286 declaration->storage_class = STORAGE_CLASS_AUTO;
4289 if (specifiers->alignment != 0) {
4290 /* TODO: add checks here */
4291 declaration->alignment = specifiers->alignment;
4294 construct_type_t *construct_type
4295 = parse_inner_declarator(declaration, may_be_abstract);
4296 type_t *const type = specifiers->type;
4297 declaration->type = construct_declarator_type(construct_type, type);
4299 parse_declaration_attributes(declaration);
4301 fix_declaration_type(declaration);
4303 if (construct_type != NULL) {
4304 obstack_free(&temp_obst, construct_type);
4310 static type_t *parse_abstract_declarator(type_t *base_type)
4312 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4314 type_t *result = construct_declarator_type(construct_type, base_type);
4315 if (construct_type != NULL) {
4316 obstack_free(&temp_obst, construct_type);
4322 static declaration_t *append_declaration(declaration_t* const declaration)
4324 if (last_declaration != NULL) {
4325 last_declaration->next = declaration;
4327 scope->declarations = declaration;
4329 last_declaration = declaration;
4334 * Check if the declaration of main is suspicious. main should be a
4335 * function with external linkage, returning int, taking either zero
4336 * arguments, two, or three arguments of appropriate types, ie.
4338 * int main([ int argc, char **argv [, char **env ] ]).
4340 * @param decl the declaration to check
4341 * @param type the function type of the declaration
4343 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4345 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4346 warningf(&decl->source_position,
4347 "'main' is normally a non-static function");
4349 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4350 warningf(&decl->source_position,
4351 "return type of 'main' should be 'int', but is '%T'",
4352 func_type->return_type);
4354 const function_parameter_t *parm = func_type->parameters;
4356 type_t *const first_type = parm->type;
4357 if (!types_compatible(skip_typeref(first_type), type_int)) {
4358 warningf(&decl->source_position,
4359 "first argument of 'main' should be 'int', but is '%T'", first_type);
4363 type_t *const second_type = parm->type;
4364 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4365 warningf(&decl->source_position,
4366 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4370 type_t *const third_type = parm->type;
4371 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4372 warningf(&decl->source_position,
4373 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4377 goto warn_arg_count;
4381 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4387 * Check if a symbol is the equal to "main".
4389 static bool is_sym_main(const symbol_t *const sym)
4391 return strcmp(sym->string, "main") == 0;
4394 static declaration_t *record_declaration(
4395 declaration_t *const declaration,
4396 const bool is_definition)
4398 const symbol_t *const symbol = declaration->symbol;
4399 const namespace_t namespc = (namespace_t)declaration->namespc;
4401 assert(symbol != NULL);
4402 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4404 type_t *const orig_type = declaration->type;
4405 type_t *const type = skip_typeref(orig_type);
4406 if (is_type_function(type) &&
4407 type->function.unspecified_parameters &&
4408 warning.strict_prototypes &&
4409 previous_declaration == NULL) {
4410 warningf(&declaration->source_position,
4411 "function declaration '%#T' is not a prototype",
4415 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4416 check_type_of_main(declaration, &type->function);
4419 if (warning.nested_externs &&
4420 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4421 scope != global_scope) {
4422 warningf(&declaration->source_position,
4423 "nested extern declaration of '%#T'", declaration->type, symbol);
4426 assert(declaration != previous_declaration);
4427 if (previous_declaration != NULL &&
4428 previous_declaration->parent_scope->is_parameter) {
4429 errorf(&declaration->source_position,
4430 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4431 orig_type, symbol, previous_declaration->type, symbol,
4432 &previous_declaration->source_position);
4435 if (previous_declaration != NULL &&
4436 previous_declaration->parent_scope == scope) {
4437 /* can happen for K&R style declarations */
4438 if (previous_declaration->type == NULL) {
4439 previous_declaration->type = declaration->type;
4442 const type_t *prev_type = skip_typeref(previous_declaration->type);
4443 if (!types_compatible(type, prev_type)) {
4444 errorf(&declaration->source_position,
4445 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4446 orig_type, symbol, previous_declaration->type, symbol,
4447 &previous_declaration->source_position);
4449 unsigned old_storage_class = previous_declaration->storage_class;
4450 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4451 errorf(&declaration->source_position,
4452 "redeclaration of enum entry '%Y' (declared %P)",
4453 symbol, &previous_declaration->source_position);
4454 return previous_declaration;
4457 if (warning.redundant_decls &&
4459 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4460 !(previous_declaration->modifiers & DM_USED) &&
4461 !previous_declaration->used) {
4462 warningf(&previous_declaration->source_position,
4463 "unnecessary static forward declaration for '%#T'",
4464 previous_declaration->type, symbol);
4467 unsigned new_storage_class = declaration->storage_class;
4469 if (is_type_incomplete(prev_type)) {
4470 previous_declaration->type = type;
4474 /* pretend no storage class means extern for function
4475 * declarations (except if the previous declaration is neither
4476 * none nor extern) */
4477 if (is_type_function(type)) {
4478 if (prev_type->function.unspecified_parameters) {
4479 previous_declaration->type = type;
4483 switch (old_storage_class) {
4484 case STORAGE_CLASS_NONE:
4485 old_storage_class = STORAGE_CLASS_EXTERN;
4488 case STORAGE_CLASS_EXTERN:
4489 if (is_definition) {
4490 if (warning.missing_prototypes &&
4491 prev_type->function.unspecified_parameters &&
4492 !is_sym_main(symbol)) {
4493 warningf(&declaration->source_position,
4494 "no previous prototype for '%#T'",
4497 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4498 new_storage_class = STORAGE_CLASS_EXTERN;
4507 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4508 new_storage_class == STORAGE_CLASS_EXTERN) {
4509 warn_redundant_declaration:
4510 if (!is_definition &&
4511 warning.redundant_decls &&
4512 is_type_valid(prev_type) &&
4513 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4514 warningf(&declaration->source_position,
4515 "redundant declaration for '%Y' (declared %P)",
4516 symbol, &previous_declaration->source_position);
4518 } else if (current_function == NULL) {
4519 if (old_storage_class != STORAGE_CLASS_STATIC &&
4520 new_storage_class == STORAGE_CLASS_STATIC) {
4521 errorf(&declaration->source_position,
4522 "static declaration of '%Y' follows non-static declaration (declared %P)",
4523 symbol, &previous_declaration->source_position);
4524 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4525 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4526 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4528 goto warn_redundant_declaration;
4530 } else if (is_type_valid(prev_type)) {
4531 if (old_storage_class == new_storage_class) {
4532 errorf(&declaration->source_position,
4533 "redeclaration of '%Y' (declared %P)",
4534 symbol, &previous_declaration->source_position);
4536 errorf(&declaration->source_position,
4537 "redeclaration of '%Y' with different linkage (declared %P)",
4538 symbol, &previous_declaration->source_position);
4543 previous_declaration->modifiers |= declaration->modifiers;
4544 previous_declaration->is_inline |= declaration->is_inline;
4545 return previous_declaration;
4546 } else if (is_type_function(type)) {
4547 if (is_definition &&
4548 declaration->storage_class != STORAGE_CLASS_STATIC) {
4549 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4550 warningf(&declaration->source_position,
4551 "no previous prototype for '%#T'", orig_type, symbol);
4552 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4553 warningf(&declaration->source_position,
4554 "no previous declaration for '%#T'", orig_type,
4559 if (warning.missing_declarations &&
4560 scope == global_scope && (
4561 declaration->storage_class == STORAGE_CLASS_NONE ||
4562 declaration->storage_class == STORAGE_CLASS_THREAD
4564 warningf(&declaration->source_position,
4565 "no previous declaration for '%#T'", orig_type, symbol);
4569 assert(declaration->parent_scope == NULL);
4570 assert(scope != NULL);
4572 declaration->parent_scope = scope;
4574 environment_push(declaration);
4575 return append_declaration(declaration);
4578 static void parser_error_multiple_definition(declaration_t *declaration,
4579 const source_position_t *source_position)
4581 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4582 declaration->symbol, &declaration->source_position);
4585 static bool is_declaration_specifier(const token_t *token,
4586 bool only_specifiers_qualifiers)
4588 switch (token->type) {
4593 return is_typedef_symbol(token->v.symbol);
4595 case T___extension__:
4597 return !only_specifiers_qualifiers;
4604 static void parse_init_declarator_rest(declaration_t *declaration)
4608 type_t *orig_type = declaration->type;
4609 type_t *type = skip_typeref(orig_type);
4611 if (declaration->init.initializer != NULL) {
4612 parser_error_multiple_definition(declaration, HERE);
4615 bool must_be_constant = false;
4616 if (declaration->storage_class == STORAGE_CLASS_STATIC
4617 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4618 || declaration->parent_scope == global_scope) {
4619 must_be_constant = true;
4622 if (is_type_function(type)) {
4623 errorf(&declaration->source_position,
4624 "function '%#T' is initialized like a variable",
4625 orig_type, declaration->symbol);
4626 orig_type = type_error_type;
4629 parse_initializer_env_t env;
4630 env.type = orig_type;
4631 env.must_be_constant = must_be_constant;
4632 env.declaration = current_init_decl = declaration;
4634 initializer_t *initializer = parse_initializer(&env);
4635 current_init_decl = NULL;
4637 if (!is_type_function(type)) {
4638 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4639 * the array type size */
4640 declaration->type = env.type;
4641 declaration->init.initializer = initializer;
4645 /* parse rest of a declaration without any declarator */
4646 static void parse_anonymous_declaration_rest(
4647 const declaration_specifiers_t *specifiers)
4651 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4652 warningf(&specifiers->source_position,
4653 "useless storage class in empty declaration");
4656 type_t *type = specifiers->type;
4657 switch (type->kind) {
4658 case TYPE_COMPOUND_STRUCT:
4659 case TYPE_COMPOUND_UNION: {
4660 if (type->compound.declaration->symbol == NULL) {
4661 warningf(&specifiers->source_position,
4662 "unnamed struct/union that defines no instances");
4671 warningf(&specifiers->source_position, "empty declaration");
4675 #ifdef RECORD_EMPTY_DECLARATIONS
4676 declaration_t *const declaration = allocate_declaration_zero();
4677 declaration->type = specifiers->type;
4678 declaration->declared_storage_class = specifiers->declared_storage_class;
4679 declaration->source_position = specifiers->source_position;
4680 declaration->modifiers = specifiers->modifiers;
4681 declaration->storage_class = STORAGE_CLASS_NONE;
4683 append_declaration(declaration);
4687 static void parse_declaration_rest(declaration_t *ndeclaration,
4688 const declaration_specifiers_t *specifiers,
4689 parsed_declaration_func finished_declaration)
4691 add_anchor_token(';');
4692 add_anchor_token(',');
4694 declaration_t *declaration =
4695 finished_declaration(ndeclaration, token.type == '=');
4697 type_t *orig_type = declaration->type;
4698 type_t *type = skip_typeref(orig_type);
4700 if (type->kind != TYPE_FUNCTION &&
4701 declaration->is_inline &&
4702 is_type_valid(type)) {
4703 warningf(&declaration->source_position,
4704 "variable '%Y' declared 'inline'\n", declaration->symbol);
4707 if (token.type == '=') {
4708 parse_init_declarator_rest(declaration);
4711 if (token.type != ',')
4715 add_anchor_token('=');
4716 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4717 rem_anchor_token('=');
4722 rem_anchor_token(';');
4723 rem_anchor_token(',');
4726 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4728 symbol_t *symbol = declaration->symbol;
4729 if (symbol == NULL) {
4730 errorf(HERE, "anonymous declaration not valid as function parameter");
4733 namespace_t namespc = (namespace_t) declaration->namespc;
4734 if (namespc != NAMESPACE_NORMAL) {
4735 return record_declaration(declaration, false);
4738 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4739 if (previous_declaration == NULL ||
4740 previous_declaration->parent_scope != scope) {
4741 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4746 if (is_definition) {
4747 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4750 if (previous_declaration->type == NULL) {
4751 previous_declaration->type = declaration->type;
4752 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4753 previous_declaration->storage_class = declaration->storage_class;
4754 previous_declaration->parent_scope = scope;
4755 return previous_declaration;
4757 return record_declaration(declaration, false);
4761 static void parse_declaration(parsed_declaration_func finished_declaration)
4763 declaration_specifiers_t specifiers;
4764 memset(&specifiers, 0, sizeof(specifiers));
4766 add_anchor_token(';');
4767 parse_declaration_specifiers(&specifiers);
4768 rem_anchor_token(';');
4770 if (token.type == ';') {
4771 parse_anonymous_declaration_rest(&specifiers);
4773 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4774 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4778 static type_t *get_default_promoted_type(type_t *orig_type)
4780 type_t *result = orig_type;
4782 type_t *type = skip_typeref(orig_type);
4783 if (is_type_integer(type)) {
4784 result = promote_integer(type);
4785 } else if (type == type_float) {
4786 result = type_double;
4792 static void parse_kr_declaration_list(declaration_t *declaration)
4794 type_t *type = skip_typeref(declaration->type);
4795 if (!is_type_function(type))
4798 if (!type->function.kr_style_parameters)
4801 add_anchor_token('{');
4803 /* push function parameters */
4804 int top = environment_top();
4805 scope_push(&declaration->scope);
4807 declaration_t *parameter = declaration->scope.declarations;
4808 for ( ; parameter != NULL; parameter = parameter->next) {
4809 assert(parameter->parent_scope == NULL);
4810 parameter->parent_scope = scope;
4811 environment_push(parameter);
4814 /* parse declaration list */
4815 while (is_declaration_specifier(&token, false)) {
4816 parse_declaration(finished_kr_declaration);
4819 /* pop function parameters */
4820 assert(scope == &declaration->scope);
4822 environment_pop_to(top);
4824 /* update function type */
4825 type_t *new_type = duplicate_type(type);
4827 function_parameter_t *parameters = NULL;
4828 function_parameter_t *last_parameter = NULL;
4830 declaration_t *parameter_declaration = declaration->scope.declarations;
4831 for( ; parameter_declaration != NULL;
4832 parameter_declaration = parameter_declaration->next) {
4833 type_t *parameter_type = parameter_declaration->type;
4834 if (parameter_type == NULL) {
4836 errorf(HERE, "no type specified for function parameter '%Y'",
4837 parameter_declaration->symbol);
4839 if (warning.implicit_int) {
4840 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4841 parameter_declaration->symbol);
4843 parameter_type = type_int;
4844 parameter_declaration->type = parameter_type;
4848 semantic_parameter(parameter_declaration);
4849 parameter_type = parameter_declaration->type;
4852 * we need the default promoted types for the function type
4854 parameter_type = get_default_promoted_type(parameter_type);
4856 function_parameter_t *function_parameter
4857 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4858 memset(function_parameter, 0, sizeof(function_parameter[0]));
4860 function_parameter->type = parameter_type;
4861 if (last_parameter != NULL) {
4862 last_parameter->next = function_parameter;
4864 parameters = function_parameter;
4866 last_parameter = function_parameter;
4869 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4871 new_type->function.parameters = parameters;
4872 new_type->function.unspecified_parameters = true;
4874 type = typehash_insert(new_type);
4875 if (type != new_type) {
4876 obstack_free(type_obst, new_type);
4879 declaration->type = type;
4881 rem_anchor_token('{');
4884 static bool first_err = true;
4887 * When called with first_err set, prints the name of the current function,
4890 static void print_in_function(void)
4894 diagnosticf("%s: In function '%Y':\n",
4895 current_function->source_position.input_name,
4896 current_function->symbol);
4901 * Check if all labels are defined in the current function.
4902 * Check if all labels are used in the current function.
4904 static void check_labels(void)
4906 for (const goto_statement_t *goto_statement = goto_first;
4907 goto_statement != NULL;
4908 goto_statement = goto_statement->next) {
4909 /* skip computed gotos */
4910 if (goto_statement->expression != NULL)
4913 declaration_t *label = goto_statement->label;
4916 if (label->source_position.input_name == NULL) {
4917 print_in_function();
4918 errorf(&goto_statement->base.source_position,
4919 "label '%Y' used but not defined", label->symbol);
4922 goto_first = goto_last = NULL;
4924 if (warning.unused_label) {
4925 for (const label_statement_t *label_statement = label_first;
4926 label_statement != NULL;
4927 label_statement = label_statement->next) {
4928 const declaration_t *label = label_statement->label;
4930 if (! label->used) {
4931 print_in_function();
4932 warningf(&label_statement->base.source_position,
4933 "label '%Y' defined but not used", label->symbol);
4937 label_first = label_last = NULL;
4941 * Check declarations of current_function for unused entities.
4943 static void check_declarations(void)
4945 if (warning.unused_parameter) {
4946 const scope_t *scope = ¤t_function->scope;
4948 if (is_sym_main(current_function->symbol)) {
4949 /* do not issue unused warnings for main */
4952 const declaration_t *parameter = scope->declarations;
4953 for (; parameter != NULL; parameter = parameter->next) {
4954 if (! parameter->used) {
4955 print_in_function();
4956 warningf(¶meter->source_position,
4957 "unused parameter '%Y'", parameter->symbol);
4961 if (warning.unused_variable) {
4965 static int determine_truth(expression_t const* const cond)
4968 !is_constant_expression(cond) ? 0 :
4969 fold_constant(cond) != 0 ? 1 :
4973 static bool noreturn_candidate;
4975 static void check_reachable(statement_t *const stmt)
4977 if (stmt->base.reachable)
4979 if (stmt->kind != STATEMENT_DO_WHILE)
4980 stmt->base.reachable = true;
4982 statement_t *last = stmt;
4984 switch (stmt->kind) {
4985 case STATEMENT_INVALID:
4986 case STATEMENT_EMPTY:
4987 case STATEMENT_DECLARATION:
4989 next = stmt->base.next;
4992 case STATEMENT_COMPOUND:
4993 next = stmt->compound.statements;
4996 case STATEMENT_RETURN:
4997 noreturn_candidate = false;
5000 case STATEMENT_IF: {
5001 if_statement_t const* const ifs = &stmt->ifs;
5002 int const val = determine_truth(ifs->condition);
5005 check_reachable(ifs->true_statement);
5010 if (ifs->false_statement != NULL) {
5011 check_reachable(ifs->false_statement);
5015 next = stmt->base.next;
5019 case STATEMENT_SWITCH: {
5020 switch_statement_t const *const switchs = &stmt->switchs;
5021 expression_t const *const expr = switchs->expression;
5023 if (is_constant_expression(expr)) {
5024 long const val = fold_constant(expr);
5025 case_label_statement_t * defaults = NULL;
5026 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5027 if (i->expression == NULL) {
5032 if (i->first_case <= val && val <= i->last_case) {
5033 check_reachable((statement_t*)i);
5038 if (defaults != NULL) {
5039 check_reachable((statement_t*)defaults);
5043 bool has_default = false;
5044 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5045 if (i->expression == NULL)
5048 check_reachable((statement_t*)i);
5055 next = stmt->base.next;
5059 case STATEMENT_EXPRESSION: {
5060 /* Check for noreturn function call */
5061 expression_t const *const expr = stmt->expression.expression;
5062 if (expr->kind == EXPR_CALL) {
5063 expression_t const *const func = expr->call.function;
5064 if (func->kind == EXPR_REFERENCE) {
5065 declaration_t const *const decl = func->reference.declaration;
5066 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5072 next = stmt->base.next;
5076 case STATEMENT_CONTINUE: {
5077 statement_t *parent = stmt;
5079 parent = parent->base.parent;
5080 if (parent == NULL) /* continue not within loop */
5084 switch (parent->kind) {
5085 case STATEMENT_WHILE: goto continue_while;
5086 case STATEMENT_DO_WHILE: goto continue_do_while;
5087 case STATEMENT_FOR: goto continue_for;
5094 case STATEMENT_BREAK: {
5095 statement_t *parent = stmt;
5097 parent = parent->base.parent;
5098 if (parent == NULL) /* break not within loop/switch */
5101 switch (parent->kind) {
5102 case STATEMENT_SWITCH:
5103 case STATEMENT_WHILE:
5104 case STATEMENT_DO_WHILE:
5107 next = parent->base.next;
5108 goto found_break_parent;
5117 case STATEMENT_GOTO:
5118 if (stmt->gotos.expression) {
5119 statement_t *parent = stmt->base.parent;
5120 if (parent == NULL) /* top level goto */
5124 next = stmt->gotos.label->init.statement;
5125 if (next == NULL) /* missing label */
5130 case STATEMENT_LABEL:
5131 next = stmt->label.statement;
5134 case STATEMENT_CASE_LABEL:
5135 next = stmt->case_label.statement;
5138 case STATEMENT_WHILE: {
5139 while_statement_t const *const whiles = &stmt->whiles;
5140 int const val = determine_truth(whiles->condition);
5143 check_reachable(whiles->body);
5148 next = stmt->base.next;
5152 case STATEMENT_DO_WHILE:
5153 next = stmt->do_while.body;
5156 case STATEMENT_FOR: {
5157 for_statement_t *const fors = &stmt->fors;
5159 if (fors->condition_reachable)
5161 fors->condition_reachable = true;
5163 expression_t const *const cond = fors->condition;
5165 cond == NULL ? 1 : determine_truth(cond);
5168 check_reachable(fors->body);
5173 next = stmt->base.next;
5177 case STATEMENT_MS_TRY: {
5178 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5179 check_reachable(ms_try->try_statement);
5180 next = ms_try->final_statement;
5184 case STATEMENT_LEAVE: {
5185 statement_t *parent = stmt;
5187 parent = parent->base.parent;
5188 if (parent == NULL) /* __leave not within __try */
5191 if (parent->kind == STATEMENT_MS_TRY) {
5193 next = parent->ms_try.final_statement;
5201 while (next == NULL) {
5202 next = last->base.parent;
5204 noreturn_candidate = false;
5206 type_t *const type = current_function->type;
5207 assert(is_type_function(type));
5208 type_t *const ret = skip_typeref(type->function.return_type);
5209 if (warning.return_type &&
5210 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5211 is_type_valid(ret) &&
5212 !is_sym_main(current_function->symbol)) {
5213 warningf(&stmt->base.source_position,
5214 "control reaches end of non-void function");
5219 switch (next->kind) {
5220 case STATEMENT_INVALID:
5221 case STATEMENT_EMPTY:
5222 case STATEMENT_DECLARATION:
5223 case STATEMENT_EXPRESSION:
5225 case STATEMENT_RETURN:
5226 case STATEMENT_CONTINUE:
5227 case STATEMENT_BREAK:
5228 case STATEMENT_GOTO:
5229 case STATEMENT_LEAVE:
5230 panic("invalid control flow in function");
5232 case STATEMENT_COMPOUND:
5234 case STATEMENT_SWITCH:
5235 case STATEMENT_LABEL:
5236 case STATEMENT_CASE_LABEL:
5238 next = next->base.next;
5241 case STATEMENT_WHILE: {
5243 if (next->base.reachable)
5245 next->base.reachable = true;
5247 while_statement_t const *const whiles = &next->whiles;
5248 int const val = determine_truth(whiles->condition);
5251 check_reachable(whiles->body);
5257 next = next->base.next;
5261 case STATEMENT_DO_WHILE: {
5263 if (next->base.reachable)
5265 next->base.reachable = true;
5267 do_while_statement_t const *const dw = &next->do_while;
5268 int const val = determine_truth(dw->condition);
5271 check_reachable(dw->body);
5277 next = next->base.next;
5281 case STATEMENT_FOR: {
5283 for_statement_t *const fors = &next->fors;
5285 fors->step_reachable = true;
5287 if (fors->condition_reachable)
5289 fors->condition_reachable = true;
5291 expression_t const *const cond = fors->condition;
5293 cond == NULL ? 1 : determine_truth(cond);
5296 check_reachable(fors->body);
5302 next = next->base.next;
5306 case STATEMENT_MS_TRY:
5308 next = next->ms_try.final_statement;
5314 next = stmt->base.parent;
5316 warningf(&stmt->base.source_position,
5317 "control reaches end of non-void function");
5321 check_reachable(next);
5324 static void check_unreachable(statement_t const* const stmt)
5326 if (!stmt->base.reachable &&
5327 stmt->kind != STATEMENT_DO_WHILE &&
5328 stmt->kind != STATEMENT_FOR &&
5329 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5330 warningf(&stmt->base.source_position, "statement is unreachable");
5333 switch (stmt->kind) {
5334 case STATEMENT_INVALID:
5335 case STATEMENT_EMPTY:
5336 case STATEMENT_RETURN:
5337 case STATEMENT_DECLARATION:
5338 case STATEMENT_EXPRESSION:
5339 case STATEMENT_CONTINUE:
5340 case STATEMENT_BREAK:
5341 case STATEMENT_GOTO:
5343 case STATEMENT_LEAVE:
5346 case STATEMENT_COMPOUND:
5347 if (stmt->compound.statements)
5348 check_unreachable(stmt->compound.statements);
5352 check_unreachable(stmt->ifs.true_statement);
5353 if (stmt->ifs.false_statement != NULL)
5354 check_unreachable(stmt->ifs.false_statement);
5357 case STATEMENT_SWITCH:
5358 check_unreachable(stmt->switchs.body);
5361 case STATEMENT_LABEL:
5362 check_unreachable(stmt->label.statement);
5365 case STATEMENT_CASE_LABEL:
5366 check_unreachable(stmt->case_label.statement);
5369 case STATEMENT_WHILE:
5370 check_unreachable(stmt->whiles.body);
5373 case STATEMENT_DO_WHILE:
5374 check_unreachable(stmt->do_while.body);
5375 if (!stmt->base.reachable) {
5376 expression_t const *const cond = stmt->do_while.condition;
5377 if (determine_truth(cond) >= 0) {
5378 warningf(&cond->base.source_position,
5379 "condition of do-while-loop is unreachable");
5384 case STATEMENT_FOR: {
5385 for_statement_t const* const fors = &stmt->fors;
5387 // if init and step are unreachable, cond is unreachable, too
5388 if (!stmt->base.reachable && !fors->step_reachable) {
5389 warningf(&stmt->base.source_position, "statement is unreachable");
5391 if (!stmt->base.reachable && fors->initialisation != NULL) {
5392 warningf(&fors->initialisation->base.source_position,
5393 "initialisation of for-statement is unreachable");
5396 if (!fors->condition_reachable && fors->condition != NULL) {
5397 warningf(&fors->condition->base.source_position,
5398 "condition of for-statement is unreachable");
5401 if (!fors->step_reachable && fors->step != NULL) {
5402 warningf(&fors->step->base.source_position,
5403 "step of for-statement is unreachable");
5407 check_unreachable(fors->body);
5411 case STATEMENT_MS_TRY: {
5412 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5413 check_unreachable(ms_try->try_statement);
5414 check_unreachable(ms_try->final_statement);
5418 if (stmt->base.next)
5419 check_unreachable(stmt->base.next);
5422 static void parse_external_declaration(void)
5424 /* function-definitions and declarations both start with declaration
5426 declaration_specifiers_t specifiers;
5427 memset(&specifiers, 0, sizeof(specifiers));
5429 add_anchor_token(';');
5430 parse_declaration_specifiers(&specifiers);
5431 rem_anchor_token(';');
5433 /* must be a declaration */
5434 if (token.type == ';') {
5435 parse_anonymous_declaration_rest(&specifiers);
5439 add_anchor_token(',');
5440 add_anchor_token('=');
5441 add_anchor_token(';');
5442 add_anchor_token('{');
5444 /* declarator is common to both function-definitions and declarations */
5445 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5447 rem_anchor_token('{');
5448 rem_anchor_token(';');
5449 rem_anchor_token('=');
5450 rem_anchor_token(',');
5452 /* must be a declaration */
5453 switch (token.type) {
5457 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5461 /* must be a function definition */
5462 parse_kr_declaration_list(ndeclaration);
5464 if (token.type != '{') {
5465 parse_error_expected("while parsing function definition", '{', NULL);
5466 eat_until_matching_token(';');
5470 type_t *type = ndeclaration->type;
5472 /* note that we don't skip typerefs: the standard doesn't allow them here
5473 * (so we can't use is_type_function here) */
5474 if (type->kind != TYPE_FUNCTION) {
5475 if (is_type_valid(type)) {
5476 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5477 type, ndeclaration->symbol);
5483 if (warning.aggregate_return &&
5484 is_type_compound(skip_typeref(type->function.return_type))) {
5485 warningf(HERE, "function '%Y' returns an aggregate",
5486 ndeclaration->symbol);
5488 if (warning.traditional && !type->function.unspecified_parameters) {
5489 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5490 ndeclaration->symbol);
5492 if (warning.old_style_definition && type->function.unspecified_parameters) {
5493 warningf(HERE, "old-style function definition '%Y'",
5494 ndeclaration->symbol);
5497 /* § 6.7.5.3 (14) a function definition with () means no
5498 * parameters (and not unspecified parameters) */
5499 if (type->function.unspecified_parameters
5500 && type->function.parameters == NULL
5501 && !type->function.kr_style_parameters) {
5502 type_t *duplicate = duplicate_type(type);
5503 duplicate->function.unspecified_parameters = false;
5505 type = typehash_insert(duplicate);
5506 if (type != duplicate) {
5507 obstack_free(type_obst, duplicate);
5509 ndeclaration->type = type;
5512 declaration_t *const declaration = record_declaration(ndeclaration, true);
5513 if (ndeclaration != declaration) {
5514 declaration->scope = ndeclaration->scope;
5516 type = skip_typeref(declaration->type);
5518 /* push function parameters and switch scope */
5519 int top = environment_top();
5520 scope_push(&declaration->scope);
5522 declaration_t *parameter = declaration->scope.declarations;
5523 for( ; parameter != NULL; parameter = parameter->next) {
5524 if (parameter->parent_scope == &ndeclaration->scope) {
5525 parameter->parent_scope = scope;
5527 assert(parameter->parent_scope == NULL
5528 || parameter->parent_scope == scope);
5529 parameter->parent_scope = scope;
5530 if (parameter->symbol == NULL) {
5531 errorf(¶meter->source_position, "parameter name omitted");
5534 environment_push(parameter);
5537 if (declaration->init.statement != NULL) {
5538 parser_error_multiple_definition(declaration, HERE);
5541 /* parse function body */
5542 int label_stack_top = label_top();
5543 declaration_t *old_current_function = current_function;
5544 current_function = declaration;
5545 current_parent = NULL;
5547 statement_t *const body = parse_compound_statement(false);
5548 declaration->init.statement = body;
5551 check_declarations();
5552 if (warning.return_type ||
5553 warning.unreachable_code ||
5554 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5555 noreturn_candidate = true;
5556 check_reachable(body);
5557 if (warning.unreachable_code)
5558 check_unreachable(body);
5559 if (warning.missing_noreturn &&
5560 noreturn_candidate &&
5561 !(declaration->modifiers & DM_NORETURN)) {
5562 warningf(&body->base.source_position,
5563 "function '%#T' is candidate for attribute 'noreturn'",
5564 type, declaration->symbol);
5568 assert(current_parent == NULL);
5569 assert(current_function == declaration);
5570 current_function = old_current_function;
5571 label_pop_to(label_stack_top);
5574 assert(scope == &declaration->scope);
5576 environment_pop_to(top);
5579 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5580 source_position_t *source_position,
5581 const symbol_t *symbol)
5583 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5585 type->bitfield.base_type = base_type;
5586 type->bitfield.size_expression = size;
5589 type_t *skipped_type = skip_typeref(base_type);
5590 if (!is_type_integer(skipped_type)) {
5591 errorf(HERE, "bitfield base type '%T' is not an integer type",
5595 bit_size = skipped_type->base.size * 8;
5598 if (is_constant_expression(size)) {
5599 long v = fold_constant(size);
5602 errorf(source_position, "negative width in bit-field '%Y'",
5604 } else if (v == 0) {
5605 errorf(source_position, "zero width for bit-field '%Y'",
5607 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5608 errorf(source_position, "width of '%Y' exceeds its type",
5611 type->bitfield.bit_size = v;
5618 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5621 declaration_t *iter = compound_declaration->scope.declarations;
5622 for( ; iter != NULL; iter = iter->next) {
5623 if (iter->namespc != NAMESPACE_NORMAL)
5626 if (iter->symbol == NULL) {
5627 type_t *type = skip_typeref(iter->type);
5628 if (is_type_compound(type)) {
5629 declaration_t *result
5630 = find_compound_entry(type->compound.declaration, symbol);
5637 if (iter->symbol == symbol) {
5645 static void parse_compound_declarators(declaration_t *struct_declaration,
5646 const declaration_specifiers_t *specifiers)
5648 declaration_t *last_declaration = struct_declaration->scope.declarations;
5649 if (last_declaration != NULL) {
5650 while (last_declaration->next != NULL) {
5651 last_declaration = last_declaration->next;
5656 declaration_t *declaration;
5658 if (token.type == ':') {
5659 source_position_t source_position = *HERE;
5662 type_t *base_type = specifiers->type;
5663 expression_t *size = parse_constant_expression();
5665 type_t *type = make_bitfield_type(base_type, size,
5666 &source_position, sym_anonymous);
5668 declaration = allocate_declaration_zero();
5669 declaration->namespc = NAMESPACE_NORMAL;
5670 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5671 declaration->storage_class = STORAGE_CLASS_NONE;
5672 declaration->source_position = source_position;
5673 declaration->modifiers = specifiers->modifiers;
5674 declaration->type = type;
5676 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5678 type_t *orig_type = declaration->type;
5679 type_t *type = skip_typeref(orig_type);
5681 if (token.type == ':') {
5682 source_position_t source_position = *HERE;
5684 expression_t *size = parse_constant_expression();
5686 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5687 &source_position, declaration->symbol);
5688 declaration->type = bitfield_type;
5690 /* TODO we ignore arrays for now... what is missing is a check
5691 * that they're at the end of the struct */
5692 if (is_type_incomplete(type) && !is_type_array(type)) {
5694 "compound member '%Y' has incomplete type '%T'",
5695 declaration->symbol, orig_type);
5696 } else if (is_type_function(type)) {
5697 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5698 declaration->symbol, orig_type);
5703 /* make sure we don't define a symbol multiple times */
5704 symbol_t *symbol = declaration->symbol;
5705 if (symbol != NULL) {
5706 declaration_t *prev_decl
5707 = find_compound_entry(struct_declaration, symbol);
5709 if (prev_decl != NULL) {
5710 assert(prev_decl->symbol == symbol);
5711 errorf(&declaration->source_position,
5712 "multiple declarations of symbol '%Y' (declared %P)",
5713 symbol, &prev_decl->source_position);
5717 /* append declaration */
5718 if (last_declaration != NULL) {
5719 last_declaration->next = declaration;
5721 struct_declaration->scope.declarations = declaration;
5723 last_declaration = declaration;
5725 if (token.type != ',')
5735 static void parse_compound_type_entries(declaration_t *compound_declaration)
5738 add_anchor_token('}');
5740 while (token.type != '}' && token.type != T_EOF) {
5741 declaration_specifiers_t specifiers;
5742 memset(&specifiers, 0, sizeof(specifiers));
5743 parse_declaration_specifiers(&specifiers);
5745 parse_compound_declarators(compound_declaration, &specifiers);
5747 rem_anchor_token('}');
5749 if (token.type == T_EOF) {
5750 errorf(HERE, "EOF while parsing struct");
5755 static type_t *parse_typename(void)
5757 declaration_specifiers_t specifiers;
5758 memset(&specifiers, 0, sizeof(specifiers));
5759 parse_declaration_specifiers(&specifiers);
5760 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5761 /* TODO: improve error message, user does probably not know what a
5762 * storage class is...
5764 errorf(HERE, "typename may not have a storage class");
5767 type_t *result = parse_abstract_declarator(specifiers.type);
5775 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5776 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5777 expression_t *left);
5779 typedef struct expression_parser_function_t expression_parser_function_t;
5780 struct expression_parser_function_t {
5781 unsigned precedence;
5782 parse_expression_function parser;
5783 unsigned infix_precedence;
5784 parse_expression_infix_function infix_parser;
5787 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5790 * Prints an error message if an expression was expected but not read
5792 static expression_t *expected_expression_error(void)
5794 /* skip the error message if the error token was read */
5795 if (token.type != T_ERROR) {
5796 errorf(HERE, "expected expression, got token '%K'", &token);
5800 return create_invalid_expression();
5804 * Parse a string constant.
5806 static expression_t *parse_string_const(void)
5809 if (token.type == T_STRING_LITERAL) {
5810 string_t res = token.v.string;
5812 while (token.type == T_STRING_LITERAL) {
5813 res = concat_strings(&res, &token.v.string);
5816 if (token.type != T_WIDE_STRING_LITERAL) {
5817 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5818 /* note: that we use type_char_ptr here, which is already the
5819 * automatic converted type. revert_automatic_type_conversion
5820 * will construct the array type */
5821 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5822 cnst->string.value = res;
5826 wres = concat_string_wide_string(&res, &token.v.wide_string);
5828 wres = token.v.wide_string;
5833 switch (token.type) {
5834 case T_WIDE_STRING_LITERAL:
5835 wres = concat_wide_strings(&wres, &token.v.wide_string);
5838 case T_STRING_LITERAL:
5839 wres = concat_wide_string_string(&wres, &token.v.string);
5843 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5844 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5845 cnst->wide_string.value = wres;
5854 * Parse an integer constant.
5856 static expression_t *parse_int_const(void)
5858 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5859 cnst->base.source_position = *HERE;
5860 cnst->base.type = token.datatype;
5861 cnst->conste.v.int_value = token.v.intvalue;
5869 * Parse a character constant.
5871 static expression_t *parse_character_constant(void)
5873 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5875 cnst->base.source_position = *HERE;
5876 cnst->base.type = token.datatype;
5877 cnst->conste.v.character = token.v.string;
5879 if (cnst->conste.v.character.size != 1) {
5880 if (warning.multichar && GNU_MODE) {
5881 warningf(HERE, "multi-character character constant");
5883 errorf(HERE, "more than 1 characters in character constant");
5892 * Parse a wide character constant.
5894 static expression_t *parse_wide_character_constant(void)
5896 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5898 cnst->base.source_position = *HERE;
5899 cnst->base.type = token.datatype;
5900 cnst->conste.v.wide_character = token.v.wide_string;
5902 if (cnst->conste.v.wide_character.size != 1) {
5903 if (warning.multichar && GNU_MODE) {
5904 warningf(HERE, "multi-character character constant");
5906 errorf(HERE, "more than 1 characters in character constant");
5915 * Parse a float constant.
5917 static expression_t *parse_float_const(void)
5919 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5920 cnst->base.type = token.datatype;
5921 cnst->conste.v.float_value = token.v.floatvalue;
5928 static declaration_t *create_implicit_function(symbol_t *symbol,
5929 const source_position_t *source_position)
5931 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5932 ntype->function.return_type = type_int;
5933 ntype->function.unspecified_parameters = true;
5935 type_t *type = typehash_insert(ntype);
5936 if (type != ntype) {
5940 declaration_t *const declaration = allocate_declaration_zero();
5941 declaration->storage_class = STORAGE_CLASS_EXTERN;
5942 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5943 declaration->type = type;
5944 declaration->symbol = symbol;
5945 declaration->source_position = *source_position;
5946 declaration->implicit = true;
5948 bool strict_prototypes_old = warning.strict_prototypes;
5949 warning.strict_prototypes = false;
5950 record_declaration(declaration, false);
5951 warning.strict_prototypes = strict_prototypes_old;
5957 * Creates a return_type (func)(argument_type) function type if not
5960 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5961 type_t *argument_type2)
5963 function_parameter_t *parameter2
5964 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5965 memset(parameter2, 0, sizeof(parameter2[0]));
5966 parameter2->type = argument_type2;
5968 function_parameter_t *parameter1
5969 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5970 memset(parameter1, 0, sizeof(parameter1[0]));
5971 parameter1->type = argument_type1;
5972 parameter1->next = parameter2;
5974 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5975 type->function.return_type = return_type;
5976 type->function.parameters = parameter1;
5978 type_t *result = typehash_insert(type);
5979 if (result != type) {
5987 * Creates a return_type (func)(argument_type) function type if not
5990 * @param return_type the return type
5991 * @param argument_type the argument type
5993 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5995 function_parameter_t *parameter
5996 = obstack_alloc(type_obst, sizeof(parameter[0]));
5997 memset(parameter, 0, sizeof(parameter[0]));
5998 parameter->type = argument_type;
6000 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
6001 type->function.return_type = return_type;
6002 type->function.parameters = parameter;
6004 type_t *result = typehash_insert(type);
6005 if (result != type) {
6012 static type_t *make_function_0_type(type_t *return_type)
6014 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
6015 type->function.return_type = return_type;
6016 type->function.parameters = NULL;
6018 type_t *result = typehash_insert(type);
6019 if (result != type) {
6027 * Creates a function type for some function like builtins.
6029 * @param symbol the symbol describing the builtin
6031 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6033 switch(symbol->ID) {
6034 case T___builtin_alloca:
6035 return make_function_1_type(type_void_ptr, type_size_t);
6036 case T___builtin_huge_val:
6037 return make_function_0_type(type_double);
6038 case T___builtin_nan:
6039 return make_function_1_type(type_double, type_char_ptr);
6040 case T___builtin_nanf:
6041 return make_function_1_type(type_float, type_char_ptr);
6042 case T___builtin_nand:
6043 return make_function_1_type(type_long_double, type_char_ptr);
6044 case T___builtin_va_end:
6045 return make_function_1_type(type_void, type_valist);
6046 case T___builtin_expect:
6047 return make_function_2_type(type_long, type_long, type_long);
6049 internal_errorf(HERE, "not implemented builtin symbol found");
6054 * Performs automatic type cast as described in § 6.3.2.1.
6056 * @param orig_type the original type
6058 static type_t *automatic_type_conversion(type_t *orig_type)
6060 type_t *type = skip_typeref(orig_type);
6061 if (is_type_array(type)) {
6062 array_type_t *array_type = &type->array;
6063 type_t *element_type = array_type->element_type;
6064 unsigned qualifiers = array_type->base.qualifiers;
6066 return make_pointer_type(element_type, qualifiers);
6069 if (is_type_function(type)) {
6070 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6077 * reverts the automatic casts of array to pointer types and function
6078 * to function-pointer types as defined § 6.3.2.1
6080 type_t *revert_automatic_type_conversion(const expression_t *expression)
6082 switch (expression->kind) {
6083 case EXPR_REFERENCE: return expression->reference.declaration->type;
6086 return get_qualified_type(expression->select.compound_entry->type,
6087 expression->base.type->base.qualifiers);
6089 case EXPR_UNARY_DEREFERENCE: {
6090 const expression_t *const value = expression->unary.value;
6091 type_t *const type = skip_typeref(value->base.type);
6092 assert(is_type_pointer(type));
6093 return type->pointer.points_to;
6096 case EXPR_BUILTIN_SYMBOL:
6097 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6099 case EXPR_ARRAY_ACCESS: {
6100 const expression_t *array_ref = expression->array_access.array_ref;
6101 type_t *type_left = skip_typeref(array_ref->base.type);
6102 if (!is_type_valid(type_left))
6104 assert(is_type_pointer(type_left));
6105 return type_left->pointer.points_to;
6108 case EXPR_STRING_LITERAL: {
6109 size_t size = expression->string.value.size;
6110 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6113 case EXPR_WIDE_STRING_LITERAL: {
6114 size_t size = expression->wide_string.value.size;
6115 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6118 case EXPR_COMPOUND_LITERAL:
6119 return expression->compound_literal.type;
6124 return expression->base.type;
6127 static expression_t *parse_reference(void)
6129 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6131 reference_expression_t *ref = &expression->reference;
6132 symbol_t *const symbol = token.v.symbol;
6134 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6136 if (declaration == NULL) {
6137 if (!strict_mode && look_ahead(1)->type == '(') {
6138 /* an implicitly declared function */
6139 if (warning.implicit_function_declaration) {
6140 warningf(HERE, "implicit declaration of function '%Y'",
6144 declaration = create_implicit_function(symbol, HERE);
6146 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6147 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6151 type_t *type = declaration->type;
6153 /* we always do the auto-type conversions; the & and sizeof parser contains
6154 * code to revert this! */
6155 type = automatic_type_conversion(type);
6157 ref->declaration = declaration;
6158 ref->base.type = type;
6160 /* this declaration is used */
6161 declaration->used = true;
6163 if (declaration->parent_scope != global_scope &&
6164 declaration->parent_scope->depth < current_function->scope.depth) {
6165 /* access of a variable from an outer function */
6166 declaration->address_taken = true;
6169 /* check for deprecated functions */
6170 if (warning.deprecated_declarations &&
6171 declaration->modifiers & DM_DEPRECATED) {
6172 char const *const prefix = is_type_function(declaration->type) ?
6173 "function" : "variable";
6175 if (declaration->deprecated_string != NULL) {
6176 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6177 prefix, declaration->symbol, &declaration->source_position,
6178 declaration->deprecated_string);
6180 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6181 declaration->symbol, &declaration->source_position);
6184 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6185 current_init_decl = NULL;
6186 warningf(HERE, "variable '%#T' is initialized by itself",
6187 declaration->type, declaration->symbol);
6194 static bool semantic_cast(expression_t *cast)
6196 expression_t *expression = cast->unary.value;
6197 type_t *orig_dest_type = cast->base.type;
6198 type_t *orig_type_right = expression->base.type;
6199 type_t const *dst_type = skip_typeref(orig_dest_type);
6200 type_t const *src_type = skip_typeref(orig_type_right);
6201 source_position_t const *pos = &cast->base.source_position;
6203 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6204 if (dst_type == type_void)
6207 /* only integer and pointer can be casted to pointer */
6208 if (is_type_pointer(dst_type) &&
6209 !is_type_pointer(src_type) &&
6210 !is_type_integer(src_type) &&
6211 is_type_valid(src_type)) {
6212 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6216 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6217 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6221 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6222 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6226 if (warning.cast_qual &&
6227 is_type_pointer(src_type) &&
6228 is_type_pointer(dst_type)) {
6229 type_t *src = skip_typeref(src_type->pointer.points_to);
6230 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6231 unsigned missing_qualifiers =
6232 src->base.qualifiers & ~dst->base.qualifiers;
6233 if (missing_qualifiers != 0) {
6235 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6236 missing_qualifiers, orig_type_right);
6242 static expression_t *parse_compound_literal(type_t *type)
6244 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6246 parse_initializer_env_t env;
6248 env.declaration = NULL;
6249 env.must_be_constant = false;
6250 initializer_t *initializer = parse_initializer(&env);
6253 expression->compound_literal.initializer = initializer;
6254 expression->compound_literal.type = type;
6255 expression->base.type = automatic_type_conversion(type);
6261 * Parse a cast expression.
6263 static expression_t *parse_cast(void)
6265 add_anchor_token(')');
6267 source_position_t source_position = token.source_position;
6269 type_t *type = parse_typename();
6271 rem_anchor_token(')');
6274 if (token.type == '{') {
6275 return parse_compound_literal(type);
6278 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6279 cast->base.source_position = source_position;
6281 expression_t *value = parse_sub_expression(20);
6282 cast->base.type = type;
6283 cast->unary.value = value;
6285 if (! semantic_cast(cast)) {
6286 /* TODO: record the error in the AST. else it is impossible to detect it */
6291 return create_invalid_expression();
6295 * Parse a statement expression.
6297 static expression_t *parse_statement_expression(void)
6299 add_anchor_token(')');
6301 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6303 statement_t *statement = parse_compound_statement(true);
6304 expression->statement.statement = statement;
6305 expression->base.source_position = statement->base.source_position;
6307 /* find last statement and use its type */
6308 type_t *type = type_void;
6309 const statement_t *stmt = statement->compound.statements;
6311 while (stmt->base.next != NULL)
6312 stmt = stmt->base.next;
6314 if (stmt->kind == STATEMENT_EXPRESSION) {
6315 type = stmt->expression.expression->base.type;
6318 warningf(&expression->base.source_position, "empty statement expression ({})");
6320 expression->base.type = type;
6322 rem_anchor_token(')');
6330 * Parse a parenthesized expression.
6332 static expression_t *parse_parenthesized_expression(void)
6336 switch(token.type) {
6338 /* gcc extension: a statement expression */
6339 return parse_statement_expression();
6343 return parse_cast();
6345 if (is_typedef_symbol(token.v.symbol)) {
6346 return parse_cast();
6350 add_anchor_token(')');
6351 expression_t *result = parse_expression();
6352 rem_anchor_token(')');
6359 static expression_t *parse_function_keyword(void)
6364 if (current_function == NULL) {
6365 errorf(HERE, "'__func__' used outside of a function");
6368 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6369 expression->base.type = type_char_ptr;
6370 expression->funcname.kind = FUNCNAME_FUNCTION;
6375 static expression_t *parse_pretty_function_keyword(void)
6377 eat(T___PRETTY_FUNCTION__);
6379 if (current_function == NULL) {
6380 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6383 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6384 expression->base.type = type_char_ptr;
6385 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6390 static expression_t *parse_funcsig_keyword(void)
6394 if (current_function == NULL) {
6395 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6398 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6399 expression->base.type = type_char_ptr;
6400 expression->funcname.kind = FUNCNAME_FUNCSIG;
6405 static expression_t *parse_funcdname_keyword(void)
6407 eat(T___FUNCDNAME__);
6409 if (current_function == NULL) {
6410 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6413 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6414 expression->base.type = type_char_ptr;
6415 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6420 static designator_t *parse_designator(void)
6422 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6423 result->source_position = *HERE;
6425 if (token.type != T_IDENTIFIER) {
6426 parse_error_expected("while parsing member designator",
6427 T_IDENTIFIER, NULL);
6430 result->symbol = token.v.symbol;
6433 designator_t *last_designator = result;
6435 if (token.type == '.') {
6437 if (token.type != T_IDENTIFIER) {
6438 parse_error_expected("while parsing member designator",
6439 T_IDENTIFIER, NULL);
6442 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6443 designator->source_position = *HERE;
6444 designator->symbol = token.v.symbol;
6447 last_designator->next = designator;
6448 last_designator = designator;
6451 if (token.type == '[') {
6453 add_anchor_token(']');
6454 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6455 designator->source_position = *HERE;
6456 designator->array_index = parse_expression();
6457 rem_anchor_token(']');
6459 if (designator->array_index == NULL) {
6463 last_designator->next = designator;
6464 last_designator = designator;
6476 * Parse the __builtin_offsetof() expression.
6478 static expression_t *parse_offsetof(void)
6480 eat(T___builtin_offsetof);
6482 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6483 expression->base.type = type_size_t;
6486 add_anchor_token(',');
6487 type_t *type = parse_typename();
6488 rem_anchor_token(',');
6490 add_anchor_token(')');
6491 designator_t *designator = parse_designator();
6492 rem_anchor_token(')');
6495 expression->offsetofe.type = type;
6496 expression->offsetofe.designator = designator;
6499 memset(&path, 0, sizeof(path));
6500 path.top_type = type;
6501 path.path = NEW_ARR_F(type_path_entry_t, 0);
6503 descend_into_subtype(&path);
6505 if (!walk_designator(&path, designator, true)) {
6506 return create_invalid_expression();
6509 DEL_ARR_F(path.path);
6513 return create_invalid_expression();
6517 * Parses a _builtin_va_start() expression.
6519 static expression_t *parse_va_start(void)
6521 eat(T___builtin_va_start);
6523 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6526 add_anchor_token(',');
6527 expression->va_starte.ap = parse_assignment_expression();
6528 rem_anchor_token(',');
6530 expression_t *const expr = parse_assignment_expression();
6531 if (expr->kind == EXPR_REFERENCE) {
6532 declaration_t *const decl = expr->reference.declaration;
6533 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6534 errorf(&expr->base.source_position,
6535 "second argument of 'va_start' must be last parameter of the current function");
6537 expression->va_starte.parameter = decl;
6543 return create_invalid_expression();
6547 * Parses a _builtin_va_arg() expression.
6549 static expression_t *parse_va_arg(void)
6551 eat(T___builtin_va_arg);
6553 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6556 expression->va_arge.ap = parse_assignment_expression();
6558 expression->base.type = parse_typename();
6563 return create_invalid_expression();
6566 static expression_t *parse_builtin_symbol(void)
6568 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6570 symbol_t *symbol = token.v.symbol;
6572 expression->builtin_symbol.symbol = symbol;
6575 type_t *type = get_builtin_symbol_type(symbol);
6576 type = automatic_type_conversion(type);
6578 expression->base.type = type;
6583 * Parses a __builtin_constant() expression.
6585 static expression_t *parse_builtin_constant(void)
6587 eat(T___builtin_constant_p);
6589 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6592 add_anchor_token(')');
6593 expression->builtin_constant.value = parse_assignment_expression();
6594 rem_anchor_token(')');
6596 expression->base.type = type_int;
6600 return create_invalid_expression();
6604 * Parses a __builtin_prefetch() expression.
6606 static expression_t *parse_builtin_prefetch(void)
6608 eat(T___builtin_prefetch);
6610 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6613 add_anchor_token(')');
6614 expression->builtin_prefetch.adr = parse_assignment_expression();
6615 if (token.type == ',') {
6617 expression->builtin_prefetch.rw = parse_assignment_expression();
6619 if (token.type == ',') {
6621 expression->builtin_prefetch.locality = parse_assignment_expression();
6623 rem_anchor_token(')');
6625 expression->base.type = type_void;
6629 return create_invalid_expression();
6633 * Parses a __builtin_is_*() compare expression.
6635 static expression_t *parse_compare_builtin(void)
6637 expression_t *expression;
6639 switch(token.type) {
6640 case T___builtin_isgreater:
6641 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6643 case T___builtin_isgreaterequal:
6644 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6646 case T___builtin_isless:
6647 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6649 case T___builtin_islessequal:
6650 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6652 case T___builtin_islessgreater:
6653 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6655 case T___builtin_isunordered:
6656 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6659 internal_errorf(HERE, "invalid compare builtin found");
6662 expression->base.source_position = *HERE;
6666 expression->binary.left = parse_assignment_expression();
6668 expression->binary.right = parse_assignment_expression();
6671 type_t *const orig_type_left = expression->binary.left->base.type;
6672 type_t *const orig_type_right = expression->binary.right->base.type;
6674 type_t *const type_left = skip_typeref(orig_type_left);
6675 type_t *const type_right = skip_typeref(orig_type_right);
6676 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6677 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6678 type_error_incompatible("invalid operands in comparison",
6679 &expression->base.source_position, orig_type_left, orig_type_right);
6682 semantic_comparison(&expression->binary);
6687 return create_invalid_expression();
6692 * Parses a __builtin_expect() expression.
6694 static expression_t *parse_builtin_expect(void)
6696 eat(T___builtin_expect);
6698 expression_t *expression
6699 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6702 expression->binary.left = parse_assignment_expression();
6704 expression->binary.right = parse_constant_expression();
6707 expression->base.type = expression->binary.left->base.type;
6711 return create_invalid_expression();
6716 * Parses a MS assume() expression.
6718 static expression_t *parse_assume(void)
6722 expression_t *expression
6723 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6726 add_anchor_token(')');
6727 expression->unary.value = parse_assignment_expression();
6728 rem_anchor_token(')');
6731 expression->base.type = type_void;
6734 return create_invalid_expression();
6738 * Return the declaration for a given label symbol or create a new one.
6740 * @param symbol the symbol of the label
6742 static declaration_t *get_label(symbol_t *symbol)
6744 declaration_t *candidate;
6745 assert(current_function != NULL);
6747 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6748 /* if we found a local label, we already created the declaration */
6749 if (candidate != NULL) {
6750 assert(candidate->parent_scope == scope);
6754 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6755 /* if we found a label in the same function, then we already created the
6757 if (candidate != NULL
6758 && candidate->parent_scope == ¤t_function->scope) {
6762 /* otherwise we need to create a new one */
6763 declaration_t *const declaration = allocate_declaration_zero();
6764 declaration->namespc = NAMESPACE_LABEL;
6765 declaration->symbol = symbol;
6767 label_push(declaration);
6773 * Parses a GNU && label address expression.
6775 static expression_t *parse_label_address(void)
6777 source_position_t source_position = token.source_position;
6779 if (token.type != T_IDENTIFIER) {
6780 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6783 symbol_t *symbol = token.v.symbol;
6786 declaration_t *label = get_label(symbol);
6789 label->address_taken = true;
6791 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6792 expression->base.source_position = source_position;
6794 /* label address is threaten as a void pointer */
6795 expression->base.type = type_void_ptr;
6796 expression->label_address.declaration = label;
6799 return create_invalid_expression();
6803 * Parse a microsoft __noop expression.
6805 static expression_t *parse_noop_expression(void)
6807 source_position_t source_position = *HERE;
6810 if (token.type == '(') {
6811 /* parse arguments */
6813 add_anchor_token(')');
6814 add_anchor_token(',');
6816 if (token.type != ')') {
6818 (void)parse_assignment_expression();
6819 if (token.type != ',')
6825 rem_anchor_token(',');
6826 rem_anchor_token(')');
6829 /* the result is a (int)0 */
6830 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6831 cnst->base.source_position = source_position;
6832 cnst->base.type = type_int;
6833 cnst->conste.v.int_value = 0;
6834 cnst->conste.is_ms_noop = true;
6839 return create_invalid_expression();
6843 * Parses a primary expression.
6845 static expression_t *parse_primary_expression(void)
6847 switch (token.type) {
6848 case T_INTEGER: return parse_int_const();
6849 case T_CHARACTER_CONSTANT: return parse_character_constant();
6850 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6851 case T_FLOATINGPOINT: return parse_float_const();
6852 case T_STRING_LITERAL:
6853 case T_WIDE_STRING_LITERAL: return parse_string_const();
6854 case T_IDENTIFIER: return parse_reference();
6855 case T___FUNCTION__:
6856 case T___func__: return parse_function_keyword();
6857 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6858 case T___FUNCSIG__: return parse_funcsig_keyword();
6859 case T___FUNCDNAME__: return parse_funcdname_keyword();
6860 case T___builtin_offsetof: return parse_offsetof();
6861 case T___builtin_va_start: return parse_va_start();
6862 case T___builtin_va_arg: return parse_va_arg();
6863 case T___builtin_expect:
6864 case T___builtin_alloca:
6865 case T___builtin_nan:
6866 case T___builtin_nand:
6867 case T___builtin_nanf:
6868 case T___builtin_huge_val:
6869 case T___builtin_va_end: return parse_builtin_symbol();
6870 case T___builtin_isgreater:
6871 case T___builtin_isgreaterequal:
6872 case T___builtin_isless:
6873 case T___builtin_islessequal:
6874 case T___builtin_islessgreater:
6875 case T___builtin_isunordered: return parse_compare_builtin();
6876 case T___builtin_constant_p: return parse_builtin_constant();
6877 case T___builtin_prefetch: return parse_builtin_prefetch();
6878 case T__assume: return parse_assume();
6881 return parse_label_address();
6884 case '(': return parse_parenthesized_expression();
6885 case T___noop: return parse_noop_expression();
6888 errorf(HERE, "unexpected token %K, expected an expression", &token);
6889 return create_invalid_expression();
6893 * Check if the expression has the character type and issue a warning then.
6895 static void check_for_char_index_type(const expression_t *expression)
6897 type_t *const type = expression->base.type;
6898 const type_t *const base_type = skip_typeref(type);
6900 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6901 warning.char_subscripts) {
6902 warningf(&expression->base.source_position,
6903 "array subscript has type '%T'", type);
6907 static expression_t *parse_array_expression(unsigned precedence,
6913 add_anchor_token(']');
6915 expression_t *inside = parse_expression();
6917 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6919 array_access_expression_t *array_access = &expression->array_access;
6921 type_t *const orig_type_left = left->base.type;
6922 type_t *const orig_type_inside = inside->base.type;
6924 type_t *const type_left = skip_typeref(orig_type_left);
6925 type_t *const type_inside = skip_typeref(orig_type_inside);
6927 type_t *return_type;
6928 if (is_type_pointer(type_left)) {
6929 return_type = type_left->pointer.points_to;
6930 array_access->array_ref = left;
6931 array_access->index = inside;
6932 check_for_char_index_type(inside);
6933 } else if (is_type_pointer(type_inside)) {
6934 return_type = type_inside->pointer.points_to;
6935 array_access->array_ref = inside;
6936 array_access->index = left;
6937 array_access->flipped = true;
6938 check_for_char_index_type(left);
6940 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6942 "array access on object with non-pointer types '%T', '%T'",
6943 orig_type_left, orig_type_inside);
6945 return_type = type_error_type;
6946 array_access->array_ref = left;
6947 array_access->index = inside;
6950 expression->base.type = automatic_type_conversion(return_type);
6952 rem_anchor_token(']');
6953 if (token.type == ']') {
6956 parse_error_expected("Problem while parsing array access", ']', NULL);
6961 static expression_t *parse_typeprop(expression_kind_t const kind,
6962 source_position_t const pos,
6963 unsigned const precedence)
6965 expression_t *tp_expression = allocate_expression_zero(kind);
6966 tp_expression->base.type = type_size_t;
6967 tp_expression->base.source_position = pos;
6969 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6971 /* we only refer to a type property, mark this case */
6972 bool old = in_type_prop;
6973 in_type_prop = true;
6974 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6976 add_anchor_token(')');
6977 type_t* const orig_type = parse_typename();
6978 tp_expression->typeprop.type = orig_type;
6980 type_t const* const type = skip_typeref(orig_type);
6981 char const* const wrong_type =
6982 is_type_incomplete(type) ? "incomplete" :
6983 type->kind == TYPE_FUNCTION ? "function designator" :
6984 type->kind == TYPE_BITFIELD ? "bitfield" :
6986 if (wrong_type != NULL) {
6987 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6988 what, wrong_type, type);
6991 rem_anchor_token(')');
6994 expression_t *expression = parse_sub_expression(precedence);
6996 type_t* const orig_type = revert_automatic_type_conversion(expression);
6997 expression->base.type = orig_type;
6999 type_t const* const type = skip_typeref(orig_type);
7000 char const* const wrong_type =
7001 is_type_incomplete(type) ? "incomplete" :
7002 type->kind == TYPE_FUNCTION ? "function designator" :
7003 type->kind == TYPE_BITFIELD ? "bitfield" :
7005 if (wrong_type != NULL) {
7006 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
7009 tp_expression->typeprop.type = expression->base.type;
7010 tp_expression->typeprop.tp_expression = expression;
7015 return tp_expression;
7018 static expression_t *parse_sizeof(unsigned precedence)
7020 source_position_t pos = *HERE;
7022 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
7025 static expression_t *parse_alignof(unsigned precedence)
7027 source_position_t pos = *HERE;
7029 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
7032 static expression_t *parse_select_expression(unsigned precedence,
7033 expression_t *compound)
7036 assert(token.type == '.' || token.type == T_MINUSGREATER);
7038 bool is_pointer = (token.type == T_MINUSGREATER);
7041 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7042 select->select.compound = compound;
7044 if (token.type != T_IDENTIFIER) {
7045 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7048 symbol_t *symbol = token.v.symbol;
7051 type_t *const orig_type = compound->base.type;
7052 type_t *const type = skip_typeref(orig_type);
7055 bool saw_error = false;
7056 if (is_type_pointer(type)) {
7059 "request for member '%Y' in something not a struct or union, but '%T'",
7063 type_left = skip_typeref(type->pointer.points_to);
7065 if (is_pointer && is_type_valid(type)) {
7066 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7072 declaration_t *entry;
7073 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7074 type_left->kind == TYPE_COMPOUND_UNION) {
7075 declaration_t *const declaration = type_left->compound.declaration;
7077 if (!declaration->init.complete) {
7078 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7080 goto create_error_entry;
7083 entry = find_compound_entry(declaration, symbol);
7084 if (entry == NULL) {
7085 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7086 goto create_error_entry;
7089 if (is_type_valid(type_left) && !saw_error) {
7091 "request for member '%Y' in something not a struct or union, but '%T'",
7095 entry = allocate_declaration_zero();
7096 entry->symbol = symbol;
7099 select->select.compound_entry = entry;
7101 type_t *const res_type =
7102 get_qualified_type(entry->type, type_left->base.qualifiers);
7104 /* we always do the auto-type conversions; the & and sizeof parser contains
7105 * code to revert this! */
7106 select->base.type = automatic_type_conversion(res_type);
7108 type_t *skipped = skip_typeref(res_type);
7109 if (skipped->kind == TYPE_BITFIELD) {
7110 select->base.type = skipped->bitfield.base_type;
7116 static void check_call_argument(const function_parameter_t *parameter,
7117 call_argument_t *argument, unsigned pos)
7119 type_t *expected_type = parameter->type;
7120 type_t *expected_type_skip = skip_typeref(expected_type);
7121 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7122 expression_t *arg_expr = argument->expression;
7123 type_t *arg_type = skip_typeref(arg_expr->base.type);
7125 /* handle transparent union gnu extension */
7126 if (is_type_union(expected_type_skip)
7127 && (expected_type_skip->base.modifiers
7128 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7129 declaration_t *union_decl = expected_type_skip->compound.declaration;
7131 declaration_t *declaration = union_decl->scope.declarations;
7132 type_t *best_type = NULL;
7133 for ( ; declaration != NULL; declaration = declaration->next) {
7134 type_t *decl_type = declaration->type;
7135 error = semantic_assign(decl_type, arg_expr);
7136 if (error == ASSIGN_ERROR_INCOMPATIBLE
7137 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7140 if (error == ASSIGN_SUCCESS) {
7141 best_type = decl_type;
7142 } else if (best_type == NULL) {
7143 best_type = decl_type;
7147 if (best_type != NULL) {
7148 expected_type = best_type;
7152 error = semantic_assign(expected_type, arg_expr);
7153 argument->expression = create_implicit_cast(argument->expression,
7156 if (error != ASSIGN_SUCCESS) {
7157 /* report exact scope in error messages (like "in argument 3") */
7159 snprintf(buf, sizeof(buf), "call argument %u", pos);
7160 report_assign_error(error, expected_type, arg_expr, buf,
7161 &arg_expr->base.source_position);
7162 } else if (warning.traditional || warning.conversion) {
7163 type_t *const promoted_type = get_default_promoted_type(arg_type);
7164 if (!types_compatible(expected_type_skip, promoted_type) &&
7165 !types_compatible(expected_type_skip, type_void_ptr) &&
7166 !types_compatible(type_void_ptr, promoted_type)) {
7167 /* Deliberately show the skipped types in this warning */
7168 warningf(&arg_expr->base.source_position,
7169 "passing call argument %u as '%T' rather than '%T' due to prototype",
7170 pos, expected_type_skip, promoted_type);
7176 * Parse a call expression, ie. expression '( ... )'.
7178 * @param expression the function address
7180 static expression_t *parse_call_expression(unsigned precedence,
7181 expression_t *expression)
7184 expression_t *result = allocate_expression_zero(EXPR_CALL);
7185 result->base.source_position = expression->base.source_position;
7187 call_expression_t *call = &result->call;
7188 call->function = expression;
7190 type_t *const orig_type = expression->base.type;
7191 type_t *const type = skip_typeref(orig_type);
7193 function_type_t *function_type = NULL;
7194 if (is_type_pointer(type)) {
7195 type_t *const to_type = skip_typeref(type->pointer.points_to);
7197 if (is_type_function(to_type)) {
7198 function_type = &to_type->function;
7199 call->base.type = function_type->return_type;
7203 if (function_type == NULL && is_type_valid(type)) {
7204 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7207 /* parse arguments */
7209 add_anchor_token(')');
7210 add_anchor_token(',');
7212 if (token.type != ')') {
7213 call_argument_t *last_argument = NULL;
7216 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7218 argument->expression = parse_assignment_expression();
7219 if (last_argument == NULL) {
7220 call->arguments = argument;
7222 last_argument->next = argument;
7224 last_argument = argument;
7226 if (token.type != ',')
7231 rem_anchor_token(',');
7232 rem_anchor_token(')');
7235 if (function_type == NULL)
7238 function_parameter_t *parameter = function_type->parameters;
7239 call_argument_t *argument = call->arguments;
7240 if (!function_type->unspecified_parameters) {
7241 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7242 parameter = parameter->next, argument = argument->next) {
7243 check_call_argument(parameter, argument, ++pos);
7246 if (parameter != NULL) {
7247 errorf(HERE, "too few arguments to function '%E'", expression);
7248 } else if (argument != NULL && !function_type->variadic) {
7249 errorf(HERE, "too many arguments to function '%E'", expression);
7253 /* do default promotion */
7254 for( ; argument != NULL; argument = argument->next) {
7255 type_t *type = argument->expression->base.type;
7257 type = get_default_promoted_type(type);
7259 argument->expression
7260 = create_implicit_cast(argument->expression, type);
7263 check_format(&result->call);
7265 if (warning.aggregate_return &&
7266 is_type_compound(skip_typeref(function_type->return_type))) {
7267 warningf(&result->base.source_position,
7268 "function call has aggregate value");
7275 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7277 static bool same_compound_type(const type_t *type1, const type_t *type2)
7280 is_type_compound(type1) &&
7281 type1->kind == type2->kind &&
7282 type1->compound.declaration == type2->compound.declaration;
7286 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7288 * @param expression the conditional expression
7290 static expression_t *parse_conditional_expression(unsigned precedence,
7291 expression_t *expression)
7293 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7295 conditional_expression_t *conditional = &result->conditional;
7296 conditional->base.source_position = *HERE;
7297 conditional->condition = expression;
7300 add_anchor_token(':');
7303 type_t *const condition_type_orig = expression->base.type;
7304 type_t *const condition_type = skip_typeref(condition_type_orig);
7305 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7306 type_error("expected a scalar type in conditional condition",
7307 &expression->base.source_position, condition_type_orig);
7310 expression_t *true_expression = expression;
7311 bool gnu_cond = false;
7312 if (GNU_MODE && token.type == ':') {
7315 true_expression = parse_expression();
7316 rem_anchor_token(':');
7318 expression_t *false_expression = parse_sub_expression(precedence);
7320 type_t *const orig_true_type = true_expression->base.type;
7321 type_t *const orig_false_type = false_expression->base.type;
7322 type_t *const true_type = skip_typeref(orig_true_type);
7323 type_t *const false_type = skip_typeref(orig_false_type);
7326 type_t *result_type;
7327 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7328 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7329 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7330 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7331 warningf(&conditional->base.source_position,
7332 "ISO C forbids conditional expression with only one void side");
7334 result_type = type_void;
7335 } else if (is_type_arithmetic(true_type)
7336 && is_type_arithmetic(false_type)) {
7337 result_type = semantic_arithmetic(true_type, false_type);
7339 true_expression = create_implicit_cast(true_expression, result_type);
7340 false_expression = create_implicit_cast(false_expression, result_type);
7342 conditional->true_expression = true_expression;
7343 conditional->false_expression = false_expression;
7344 conditional->base.type = result_type;
7345 } else if (same_compound_type(true_type, false_type)) {
7346 /* just take 1 of the 2 types */
7347 result_type = true_type;
7348 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7349 type_t *pointer_type;
7351 expression_t *other_expression;
7352 if (is_type_pointer(true_type) &&
7353 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7354 pointer_type = true_type;
7355 other_type = false_type;
7356 other_expression = false_expression;
7358 pointer_type = false_type;
7359 other_type = true_type;
7360 other_expression = true_expression;
7363 if (is_null_pointer_constant(other_expression)) {
7364 result_type = pointer_type;
7365 } else if (is_type_pointer(other_type)) {
7366 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7367 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7370 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7371 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7373 } else if (types_compatible(get_unqualified_type(to1),
7374 get_unqualified_type(to2))) {
7377 warningf(&conditional->base.source_position,
7378 "pointer types '%T' and '%T' in conditional expression are incompatible",
7379 true_type, false_type);
7383 type_t *const type =
7384 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7385 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7386 } else if (is_type_integer(other_type)) {
7387 warningf(&conditional->base.source_position,
7388 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7389 result_type = pointer_type;
7391 type_error_incompatible("while parsing conditional",
7392 &expression->base.source_position, true_type, false_type);
7393 result_type = type_error_type;
7396 /* TODO: one pointer to void*, other some pointer */
7398 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7399 type_error_incompatible("while parsing conditional",
7400 &conditional->base.source_position, true_type,
7403 result_type = type_error_type;
7406 conditional->true_expression
7407 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7408 conditional->false_expression
7409 = create_implicit_cast(false_expression, result_type);
7410 conditional->base.type = result_type;
7413 return create_invalid_expression();
7417 * Parse an extension expression.
7419 static expression_t *parse_extension(unsigned precedence)
7421 eat(T___extension__);
7423 bool old_gcc_extension = in_gcc_extension;
7424 in_gcc_extension = true;
7425 expression_t *expression = parse_sub_expression(precedence);
7426 in_gcc_extension = old_gcc_extension;
7431 * Parse a __builtin_classify_type() expression.
7433 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7435 eat(T___builtin_classify_type);
7437 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7438 result->base.type = type_int;
7441 add_anchor_token(')');
7442 expression_t *expression = parse_sub_expression(precedence);
7443 rem_anchor_token(')');
7445 result->classify_type.type_expression = expression;
7449 return create_invalid_expression();
7452 static bool check_pointer_arithmetic(const source_position_t *source_position,
7453 type_t *pointer_type,
7454 type_t *orig_pointer_type)
7456 type_t *points_to = pointer_type->pointer.points_to;
7457 points_to = skip_typeref(points_to);
7459 if (is_type_incomplete(points_to)) {
7460 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7461 errorf(source_position,
7462 "arithmetic with pointer to incomplete type '%T' not allowed",
7465 } else if (warning.pointer_arith) {
7466 warningf(source_position,
7467 "pointer of type '%T' used in arithmetic",
7470 } else if (is_type_function(points_to)) {
7472 errorf(source_position,
7473 "arithmetic with pointer to function type '%T' not allowed",
7476 } else if (warning.pointer_arith) {
7477 warningf(source_position,
7478 "pointer to a function '%T' used in arithmetic",
7485 static bool is_lvalue(const expression_t *expression)
7487 switch (expression->kind) {
7488 case EXPR_REFERENCE:
7489 case EXPR_ARRAY_ACCESS:
7491 case EXPR_UNARY_DEREFERENCE:
7499 static void semantic_incdec(unary_expression_t *expression)
7501 type_t *const orig_type = expression->value->base.type;
7502 type_t *const type = skip_typeref(orig_type);
7503 if (is_type_pointer(type)) {
7504 if (!check_pointer_arithmetic(&expression->base.source_position,
7508 } else if (!is_type_real(type) && is_type_valid(type)) {
7509 /* TODO: improve error message */
7510 errorf(&expression->base.source_position,
7511 "operation needs an arithmetic or pointer type");
7514 if (!is_lvalue(expression->value)) {
7515 /* TODO: improve error message */
7516 errorf(&expression->base.source_position, "lvalue required as operand");
7518 expression->base.type = orig_type;
7521 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7523 type_t *const orig_type = expression->value->base.type;
7524 type_t *const type = skip_typeref(orig_type);
7525 if (!is_type_arithmetic(type)) {
7526 if (is_type_valid(type)) {
7527 /* TODO: improve error message */
7528 errorf(&expression->base.source_position,
7529 "operation needs an arithmetic type");
7534 expression->base.type = orig_type;
7537 static void semantic_unexpr_plus(unary_expression_t *expression)
7539 semantic_unexpr_arithmetic(expression);
7540 if (warning.traditional)
7541 warningf(&expression->base.source_position,
7542 "traditional C rejects the unary plus operator");
7545 static expression_t const *get_reference_address(expression_t const *expr)
7547 bool regular_take_address = true;
7549 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7550 expr = expr->unary.value;
7552 regular_take_address = false;
7555 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7558 expr = expr->unary.value;
7561 if (expr->kind != EXPR_REFERENCE)
7564 if (!regular_take_address &&
7565 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7572 static void warn_function_address_as_bool(expression_t const* expr)
7574 if (!warning.address)
7577 expr = get_reference_address(expr);
7579 warningf(&expr->base.source_position,
7580 "the address of '%Y' will always evaluate as 'true'",
7581 expr->reference.declaration->symbol);
7585 static void semantic_not(unary_expression_t *expression)
7587 type_t *const orig_type = expression->value->base.type;
7588 type_t *const type = skip_typeref(orig_type);
7589 if (!is_type_scalar(type) && is_type_valid(type)) {
7590 errorf(&expression->base.source_position,
7591 "operand of ! must be of scalar type");
7594 warn_function_address_as_bool(expression->value);
7596 expression->base.type = type_int;
7599 static void semantic_unexpr_integer(unary_expression_t *expression)
7601 type_t *const orig_type = expression->value->base.type;
7602 type_t *const type = skip_typeref(orig_type);
7603 if (!is_type_integer(type)) {
7604 if (is_type_valid(type)) {
7605 errorf(&expression->base.source_position,
7606 "operand of ~ must be of integer type");
7611 expression->base.type = orig_type;
7614 static void semantic_dereference(unary_expression_t *expression)
7616 type_t *const orig_type = expression->value->base.type;
7617 type_t *const type = skip_typeref(orig_type);
7618 if (!is_type_pointer(type)) {
7619 if (is_type_valid(type)) {
7620 errorf(&expression->base.source_position,
7621 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7626 type_t *result_type = type->pointer.points_to;
7627 result_type = automatic_type_conversion(result_type);
7628 expression->base.type = result_type;
7632 * Record that an address is taken (expression represents an lvalue).
7634 * @param expression the expression
7635 * @param may_be_register if true, the expression might be an register
7637 static void set_address_taken(expression_t *expression, bool may_be_register)
7639 if (expression->kind != EXPR_REFERENCE)
7642 declaration_t *const declaration = expression->reference.declaration;
7643 /* happens for parse errors */
7644 if (declaration == NULL)
7647 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7648 errorf(&expression->base.source_position,
7649 "address of register variable '%Y' requested",
7650 declaration->symbol);
7652 declaration->address_taken = 1;
7657 * Check the semantic of the address taken expression.
7659 static void semantic_take_addr(unary_expression_t *expression)
7661 expression_t *value = expression->value;
7662 value->base.type = revert_automatic_type_conversion(value);
7664 type_t *orig_type = value->base.type;
7665 if (!is_type_valid(orig_type))
7668 set_address_taken(value, false);
7670 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7673 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7674 static expression_t *parse_##unexpression_type(unsigned precedence) \
7676 expression_t *unary_expression \
7677 = allocate_expression_zero(unexpression_type); \
7678 unary_expression->base.source_position = *HERE; \
7680 unary_expression->unary.value = parse_sub_expression(precedence); \
7682 sfunc(&unary_expression->unary); \
7684 return unary_expression; \
7687 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7688 semantic_unexpr_arithmetic)
7689 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7690 semantic_unexpr_plus)
7691 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7693 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7694 semantic_dereference)
7695 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7697 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7698 semantic_unexpr_integer)
7699 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7701 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7704 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7706 static expression_t *parse_##unexpression_type(unsigned precedence, \
7707 expression_t *left) \
7709 (void) precedence; \
7711 expression_t *unary_expression \
7712 = allocate_expression_zero(unexpression_type); \
7713 unary_expression->base.source_position = *HERE; \
7715 unary_expression->unary.value = left; \
7717 sfunc(&unary_expression->unary); \
7719 return unary_expression; \
7722 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7723 EXPR_UNARY_POSTFIX_INCREMENT,
7725 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7726 EXPR_UNARY_POSTFIX_DECREMENT,
7729 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7731 /* TODO: handle complex + imaginary types */
7733 type_left = get_unqualified_type(type_left);
7734 type_right = get_unqualified_type(type_right);
7736 /* § 6.3.1.8 Usual arithmetic conversions */
7737 if (type_left == type_long_double || type_right == type_long_double) {
7738 return type_long_double;
7739 } else if (type_left == type_double || type_right == type_double) {
7741 } else if (type_left == type_float || type_right == type_float) {
7745 type_left = promote_integer(type_left);
7746 type_right = promote_integer(type_right);
7748 if (type_left == type_right)
7751 bool const signed_left = is_type_signed(type_left);
7752 bool const signed_right = is_type_signed(type_right);
7753 int const rank_left = get_rank(type_left);
7754 int const rank_right = get_rank(type_right);
7756 if (signed_left == signed_right)
7757 return rank_left >= rank_right ? type_left : type_right;
7766 u_rank = rank_right;
7767 u_type = type_right;
7769 s_rank = rank_right;
7770 s_type = type_right;
7775 if (u_rank >= s_rank)
7778 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7780 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7781 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7785 case ATOMIC_TYPE_INT: return type_unsigned_int;
7786 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7787 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7789 default: panic("invalid atomic type");
7794 * Check the semantic restrictions for a binary expression.
7796 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7798 expression_t *const left = expression->left;
7799 expression_t *const right = expression->right;
7800 type_t *const orig_type_left = left->base.type;
7801 type_t *const orig_type_right = right->base.type;
7802 type_t *const type_left = skip_typeref(orig_type_left);
7803 type_t *const type_right = skip_typeref(orig_type_right);
7805 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7806 /* TODO: improve error message */
7807 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7808 errorf(&expression->base.source_position,
7809 "operation needs arithmetic types");
7814 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7815 expression->left = create_implicit_cast(left, arithmetic_type);
7816 expression->right = create_implicit_cast(right, arithmetic_type);
7817 expression->base.type = arithmetic_type;
7820 static void warn_div_by_zero(binary_expression_t const *const expression)
7822 if (!warning.div_by_zero ||
7823 !is_type_integer(expression->base.type))
7826 expression_t const *const right = expression->right;
7827 /* The type of the right operand can be different for /= */
7828 if (is_type_integer(right->base.type) &&
7829 is_constant_expression(right) &&
7830 fold_constant(right) == 0) {
7831 warningf(&expression->base.source_position, "division by zero");
7836 * Check the semantic restrictions for a div/mod expression.
7838 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7839 semantic_binexpr_arithmetic(expression);
7840 warn_div_by_zero(expression);
7843 static void semantic_shift_op(binary_expression_t *expression)
7845 expression_t *const left = expression->left;
7846 expression_t *const right = expression->right;
7847 type_t *const orig_type_left = left->base.type;
7848 type_t *const orig_type_right = right->base.type;
7849 type_t * type_left = skip_typeref(orig_type_left);
7850 type_t * type_right = skip_typeref(orig_type_right);
7852 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7853 /* TODO: improve error message */
7854 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7855 errorf(&expression->base.source_position,
7856 "operands of shift operation must have integer types");
7861 type_left = promote_integer(type_left);
7862 type_right = promote_integer(type_right);
7864 expression->left = create_implicit_cast(left, type_left);
7865 expression->right = create_implicit_cast(right, type_right);
7866 expression->base.type = type_left;
7869 static void semantic_add(binary_expression_t *expression)
7871 expression_t *const left = expression->left;
7872 expression_t *const right = expression->right;
7873 type_t *const orig_type_left = left->base.type;
7874 type_t *const orig_type_right = right->base.type;
7875 type_t *const type_left = skip_typeref(orig_type_left);
7876 type_t *const type_right = skip_typeref(orig_type_right);
7879 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7880 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7881 expression->left = create_implicit_cast(left, arithmetic_type);
7882 expression->right = create_implicit_cast(right, arithmetic_type);
7883 expression->base.type = arithmetic_type;
7885 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7886 check_pointer_arithmetic(&expression->base.source_position,
7887 type_left, orig_type_left);
7888 expression->base.type = type_left;
7889 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7890 check_pointer_arithmetic(&expression->base.source_position,
7891 type_right, orig_type_right);
7892 expression->base.type = type_right;
7893 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7894 errorf(&expression->base.source_position,
7895 "invalid operands to binary + ('%T', '%T')",
7896 orig_type_left, orig_type_right);
7900 static void semantic_sub(binary_expression_t *expression)
7902 expression_t *const left = expression->left;
7903 expression_t *const right = expression->right;
7904 type_t *const orig_type_left = left->base.type;
7905 type_t *const orig_type_right = right->base.type;
7906 type_t *const type_left = skip_typeref(orig_type_left);
7907 type_t *const type_right = skip_typeref(orig_type_right);
7908 source_position_t const *const pos = &expression->base.source_position;
7911 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7912 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7913 expression->left = create_implicit_cast(left, arithmetic_type);
7914 expression->right = create_implicit_cast(right, arithmetic_type);
7915 expression->base.type = arithmetic_type;
7917 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7918 check_pointer_arithmetic(&expression->base.source_position,
7919 type_left, orig_type_left);
7920 expression->base.type = type_left;
7921 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7922 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7923 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7924 if (!types_compatible(unqual_left, unqual_right)) {
7926 "subtracting pointers to incompatible types '%T' and '%T'",
7927 orig_type_left, orig_type_right);
7928 } else if (!is_type_object(unqual_left)) {
7929 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7930 warningf(pos, "subtracting pointers to void");
7932 errorf(pos, "subtracting pointers to non-object types '%T'",
7936 expression->base.type = type_ptrdiff_t;
7937 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7938 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7939 orig_type_left, orig_type_right);
7943 static void warn_string_literal_address(expression_t const* expr)
7945 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7946 expr = expr->unary.value;
7947 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7949 expr = expr->unary.value;
7952 if (expr->kind == EXPR_STRING_LITERAL ||
7953 expr->kind == EXPR_WIDE_STRING_LITERAL) {
7954 warningf(&expr->base.source_position,
7955 "comparison with string literal results in unspecified behaviour");
7960 * Check the semantics of comparison expressions.
7962 * @param expression The expression to check.
7964 static void semantic_comparison(binary_expression_t *expression)
7966 expression_t *left = expression->left;
7967 expression_t *right = expression->right;
7969 if (warning.address) {
7970 warn_string_literal_address(left);
7971 warn_string_literal_address(right);
7973 expression_t const* const func_left = get_reference_address(left);
7974 if (func_left != NULL && is_null_pointer_constant(right)) {
7975 warningf(&expression->base.source_position,
7976 "the address of '%Y' will never be NULL",
7977 func_left->reference.declaration->symbol);
7980 expression_t const* const func_right = get_reference_address(right);
7981 if (func_right != NULL && is_null_pointer_constant(right)) {
7982 warningf(&expression->base.source_position,
7983 "the address of '%Y' will never be NULL",
7984 func_right->reference.declaration->symbol);
7988 type_t *orig_type_left = left->base.type;
7989 type_t *orig_type_right = right->base.type;
7990 type_t *type_left = skip_typeref(orig_type_left);
7991 type_t *type_right = skip_typeref(orig_type_right);
7993 /* TODO non-arithmetic types */
7994 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7995 /* test for signed vs unsigned compares */
7996 if (warning.sign_compare &&
7997 (expression->base.kind != EXPR_BINARY_EQUAL &&
7998 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7999 (is_type_signed(type_left) != is_type_signed(type_right))) {
8001 /* check if 1 of the operands is a constant, in this case we just
8002 * check wether we can safely represent the resulting constant in
8003 * the type of the other operand. */
8004 expression_t *const_expr = NULL;
8005 expression_t *other_expr = NULL;
8007 if (is_constant_expression(left)) {
8010 } else if (is_constant_expression(right)) {
8015 if (const_expr != NULL) {
8016 type_t *other_type = skip_typeref(other_expr->base.type);
8017 long val = fold_constant(const_expr);
8018 /* TODO: check if val can be represented by other_type */
8022 warningf(&expression->base.source_position,
8023 "comparison between signed and unsigned");
8025 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8026 expression->left = create_implicit_cast(left, arithmetic_type);
8027 expression->right = create_implicit_cast(right, arithmetic_type);
8028 expression->base.type = arithmetic_type;
8029 if (warning.float_equal &&
8030 (expression->base.kind == EXPR_BINARY_EQUAL ||
8031 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8032 is_type_float(arithmetic_type)) {
8033 warningf(&expression->base.source_position,
8034 "comparing floating point with == or != is unsafe");
8036 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8037 /* TODO check compatibility */
8038 } else if (is_type_pointer(type_left)) {
8039 expression->right = create_implicit_cast(right, type_left);
8040 } else if (is_type_pointer(type_right)) {
8041 expression->left = create_implicit_cast(left, type_right);
8042 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8043 type_error_incompatible("invalid operands in comparison",
8044 &expression->base.source_position,
8045 type_left, type_right);
8047 expression->base.type = type_int;
8051 * Checks if a compound type has constant fields.
8053 static bool has_const_fields(const compound_type_t *type)
8055 const scope_t *scope = &type->declaration->scope;
8056 const declaration_t *declaration = scope->declarations;
8058 for (; declaration != NULL; declaration = declaration->next) {
8059 if (declaration->namespc != NAMESPACE_NORMAL)
8062 const type_t *decl_type = skip_typeref(declaration->type);
8063 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8070 static bool is_valid_assignment_lhs(expression_t const* const left)
8072 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8073 type_t *const type_left = skip_typeref(orig_type_left);
8075 if (!is_lvalue(left)) {
8076 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8081 if (is_type_array(type_left)) {
8082 errorf(HERE, "cannot assign to arrays ('%E')", left);
8085 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8086 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8090 if (is_type_incomplete(type_left)) {
8091 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8092 left, orig_type_left);
8095 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8096 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8097 left, orig_type_left);
8104 static void semantic_arithmetic_assign(binary_expression_t *expression)
8106 expression_t *left = expression->left;
8107 expression_t *right = expression->right;
8108 type_t *orig_type_left = left->base.type;
8109 type_t *orig_type_right = right->base.type;
8111 if (!is_valid_assignment_lhs(left))
8114 type_t *type_left = skip_typeref(orig_type_left);
8115 type_t *type_right = skip_typeref(orig_type_right);
8117 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8118 /* TODO: improve error message */
8119 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8120 errorf(&expression->base.source_position,
8121 "operation needs arithmetic types");
8126 /* combined instructions are tricky. We can't create an implicit cast on
8127 * the left side, because we need the uncasted form for the store.
8128 * The ast2firm pass has to know that left_type must be right_type
8129 * for the arithmetic operation and create a cast by itself */
8130 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8131 expression->right = create_implicit_cast(right, arithmetic_type);
8132 expression->base.type = type_left;
8135 static void semantic_divmod_assign(binary_expression_t *expression)
8137 semantic_arithmetic_assign(expression);
8138 warn_div_by_zero(expression);
8141 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8143 expression_t *const left = expression->left;
8144 expression_t *const right = expression->right;
8145 type_t *const orig_type_left = left->base.type;
8146 type_t *const orig_type_right = right->base.type;
8147 type_t *const type_left = skip_typeref(orig_type_left);
8148 type_t *const type_right = skip_typeref(orig_type_right);
8150 if (!is_valid_assignment_lhs(left))
8153 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8154 /* combined instructions are tricky. We can't create an implicit cast on
8155 * the left side, because we need the uncasted form for the store.
8156 * The ast2firm pass has to know that left_type must be right_type
8157 * for the arithmetic operation and create a cast by itself */
8158 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8159 expression->right = create_implicit_cast(right, arithmetic_type);
8160 expression->base.type = type_left;
8161 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8162 check_pointer_arithmetic(&expression->base.source_position,
8163 type_left, orig_type_left);
8164 expression->base.type = type_left;
8165 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8166 errorf(&expression->base.source_position,
8167 "incompatible types '%T' and '%T' in assignment",
8168 orig_type_left, orig_type_right);
8173 * Check the semantic restrictions of a logical expression.
8175 static void semantic_logical_op(binary_expression_t *expression)
8177 expression_t *const left = expression->left;
8178 expression_t *const right = expression->right;
8179 type_t *const orig_type_left = left->base.type;
8180 type_t *const orig_type_right = right->base.type;
8181 type_t *const type_left = skip_typeref(orig_type_left);
8182 type_t *const type_right = skip_typeref(orig_type_right);
8184 warn_function_address_as_bool(left);
8185 warn_function_address_as_bool(right);
8187 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8188 /* TODO: improve error message */
8189 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8190 errorf(&expression->base.source_position,
8191 "operation needs scalar types");
8196 expression->base.type = type_int;
8200 * Check the semantic restrictions of a binary assign expression.
8202 static void semantic_binexpr_assign(binary_expression_t *expression)
8204 expression_t *left = expression->left;
8205 type_t *orig_type_left = left->base.type;
8207 if (!is_valid_assignment_lhs(left))
8210 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8211 report_assign_error(error, orig_type_left, expression->right,
8212 "assignment", &left->base.source_position);
8213 expression->right = create_implicit_cast(expression->right, orig_type_left);
8214 expression->base.type = orig_type_left;
8218 * Determine if the outermost operation (or parts thereof) of the given
8219 * expression has no effect in order to generate a warning about this fact.
8220 * Therefore in some cases this only examines some of the operands of the
8221 * expression (see comments in the function and examples below).
8223 * f() + 23; // warning, because + has no effect
8224 * x || f(); // no warning, because x controls execution of f()
8225 * x ? y : f(); // warning, because y has no effect
8226 * (void)x; // no warning to be able to suppress the warning
8227 * This function can NOT be used for an "expression has definitely no effect"-
8229 static bool expression_has_effect(const expression_t *const expr)
8231 switch (expr->kind) {
8232 case EXPR_UNKNOWN: break;
8233 case EXPR_INVALID: return true; /* do NOT warn */
8234 case EXPR_REFERENCE: return false;
8235 /* suppress the warning for microsoft __noop operations */
8236 case EXPR_CONST: return expr->conste.is_ms_noop;
8237 case EXPR_CHARACTER_CONSTANT: return false;
8238 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8239 case EXPR_STRING_LITERAL: return false;
8240 case EXPR_WIDE_STRING_LITERAL: return false;
8241 case EXPR_LABEL_ADDRESS: return false;
8244 const call_expression_t *const call = &expr->call;
8245 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8248 switch (call->function->builtin_symbol.symbol->ID) {
8249 case T___builtin_va_end: return true;
8250 default: return false;
8254 /* Generate the warning if either the left or right hand side of a
8255 * conditional expression has no effect */
8256 case EXPR_CONDITIONAL: {
8257 const conditional_expression_t *const cond = &expr->conditional;
8259 expression_has_effect(cond->true_expression) &&
8260 expression_has_effect(cond->false_expression);
8263 case EXPR_SELECT: return false;
8264 case EXPR_ARRAY_ACCESS: return false;
8265 case EXPR_SIZEOF: return false;
8266 case EXPR_CLASSIFY_TYPE: return false;
8267 case EXPR_ALIGNOF: return false;
8269 case EXPR_FUNCNAME: return false;
8270 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8271 case EXPR_BUILTIN_CONSTANT_P: return false;
8272 case EXPR_BUILTIN_PREFETCH: return true;
8273 case EXPR_OFFSETOF: return false;
8274 case EXPR_VA_START: return true;
8275 case EXPR_VA_ARG: return true;
8276 case EXPR_STATEMENT: return true; // TODO
8277 case EXPR_COMPOUND_LITERAL: return false;
8279 case EXPR_UNARY_NEGATE: return false;
8280 case EXPR_UNARY_PLUS: return false;
8281 case EXPR_UNARY_BITWISE_NEGATE: return false;
8282 case EXPR_UNARY_NOT: return false;
8283 case EXPR_UNARY_DEREFERENCE: return false;
8284 case EXPR_UNARY_TAKE_ADDRESS: return false;
8285 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8286 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8287 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8288 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8290 /* Treat void casts as if they have an effect in order to being able to
8291 * suppress the warning */
8292 case EXPR_UNARY_CAST: {
8293 type_t *const type = skip_typeref(expr->base.type);
8294 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8297 case EXPR_UNARY_CAST_IMPLICIT: return true;
8298 case EXPR_UNARY_ASSUME: return true;
8300 case EXPR_BINARY_ADD: return false;
8301 case EXPR_BINARY_SUB: return false;
8302 case EXPR_BINARY_MUL: return false;
8303 case EXPR_BINARY_DIV: return false;
8304 case EXPR_BINARY_MOD: return false;
8305 case EXPR_BINARY_EQUAL: return false;
8306 case EXPR_BINARY_NOTEQUAL: return false;
8307 case EXPR_BINARY_LESS: return false;
8308 case EXPR_BINARY_LESSEQUAL: return false;
8309 case EXPR_BINARY_GREATER: return false;
8310 case EXPR_BINARY_GREATEREQUAL: return false;
8311 case EXPR_BINARY_BITWISE_AND: return false;
8312 case EXPR_BINARY_BITWISE_OR: return false;
8313 case EXPR_BINARY_BITWISE_XOR: return false;
8314 case EXPR_BINARY_SHIFTLEFT: return false;
8315 case EXPR_BINARY_SHIFTRIGHT: return false;
8316 case EXPR_BINARY_ASSIGN: return true;
8317 case EXPR_BINARY_MUL_ASSIGN: return true;
8318 case EXPR_BINARY_DIV_ASSIGN: return true;
8319 case EXPR_BINARY_MOD_ASSIGN: return true;
8320 case EXPR_BINARY_ADD_ASSIGN: return true;
8321 case EXPR_BINARY_SUB_ASSIGN: return true;
8322 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8323 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8324 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8325 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8326 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8328 /* Only examine the right hand side of && and ||, because the left hand
8329 * side already has the effect of controlling the execution of the right
8331 case EXPR_BINARY_LOGICAL_AND:
8332 case EXPR_BINARY_LOGICAL_OR:
8333 /* Only examine the right hand side of a comma expression, because the left
8334 * hand side has a separate warning */
8335 case EXPR_BINARY_COMMA:
8336 return expression_has_effect(expr->binary.right);
8338 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8339 case EXPR_BINARY_ISGREATER: return false;
8340 case EXPR_BINARY_ISGREATEREQUAL: return false;
8341 case EXPR_BINARY_ISLESS: return false;
8342 case EXPR_BINARY_ISLESSEQUAL: return false;
8343 case EXPR_BINARY_ISLESSGREATER: return false;
8344 case EXPR_BINARY_ISUNORDERED: return false;
8347 internal_errorf(HERE, "unexpected expression");
8350 static void semantic_comma(binary_expression_t *expression)
8352 if (warning.unused_value) {
8353 const expression_t *const left = expression->left;
8354 if (!expression_has_effect(left)) {
8355 warningf(&left->base.source_position,
8356 "left-hand operand of comma expression has no effect");
8359 expression->base.type = expression->right->base.type;
8362 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8363 static expression_t *parse_##binexpression_type(unsigned precedence, \
8364 expression_t *left) \
8366 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8367 binexpr->base.source_position = *HERE; \
8368 binexpr->binary.left = left; \
8371 expression_t *right = parse_sub_expression(precedence + lr); \
8373 binexpr->binary.right = right; \
8374 sfunc(&binexpr->binary); \
8379 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8380 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8381 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8382 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8383 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8384 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8385 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8386 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8387 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8389 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8390 semantic_comparison, 1)
8391 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8392 semantic_comparison, 1)
8393 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8394 semantic_comparison, 1)
8395 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8396 semantic_comparison, 1)
8398 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8399 semantic_binexpr_arithmetic, 1)
8400 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8401 semantic_binexpr_arithmetic, 1)
8402 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8403 semantic_binexpr_arithmetic, 1)
8404 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8405 semantic_logical_op, 1)
8406 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8407 semantic_logical_op, 1)
8408 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8409 semantic_shift_op, 1)
8410 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8411 semantic_shift_op, 1)
8412 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8413 semantic_arithmetic_addsubb_assign, 0)
8414 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8415 semantic_arithmetic_addsubb_assign, 0)
8416 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8417 semantic_arithmetic_assign, 0)
8418 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8419 semantic_divmod_assign, 0)
8420 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8421 semantic_divmod_assign, 0)
8422 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8423 semantic_arithmetic_assign, 0)
8424 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8425 semantic_arithmetic_assign, 0)
8426 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8427 semantic_arithmetic_assign, 0)
8428 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8429 semantic_arithmetic_assign, 0)
8430 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8431 semantic_arithmetic_assign, 0)
8433 static expression_t *parse_sub_expression(unsigned precedence)
8435 if (token.type < 0) {
8436 return expected_expression_error();
8439 expression_parser_function_t *parser
8440 = &expression_parsers[token.type];
8441 source_position_t source_position = token.source_position;
8444 if (parser->parser != NULL) {
8445 left = parser->parser(parser->precedence);
8447 left = parse_primary_expression();
8449 assert(left != NULL);
8450 left->base.source_position = source_position;
8453 if (token.type < 0) {
8454 return expected_expression_error();
8457 parser = &expression_parsers[token.type];
8458 if (parser->infix_parser == NULL)
8460 if (parser->infix_precedence < precedence)
8463 left = parser->infix_parser(parser->infix_precedence, left);
8465 assert(left != NULL);
8466 assert(left->kind != EXPR_UNKNOWN);
8467 left->base.source_position = source_position;
8474 * Parse an expression.
8476 static expression_t *parse_expression(void)
8478 return parse_sub_expression(1);
8482 * Register a parser for a prefix-like operator with given precedence.
8484 * @param parser the parser function
8485 * @param token_type the token type of the prefix token
8486 * @param precedence the precedence of the operator
8488 static void register_expression_parser(parse_expression_function parser,
8489 int token_type, unsigned precedence)
8491 expression_parser_function_t *entry = &expression_parsers[token_type];
8493 if (entry->parser != NULL) {
8494 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8495 panic("trying to register multiple expression parsers for a token");
8497 entry->parser = parser;
8498 entry->precedence = precedence;
8502 * Register a parser for an infix operator with given precedence.
8504 * @param parser the parser function
8505 * @param token_type the token type of the infix operator
8506 * @param precedence the precedence of the operator
8508 static void register_infix_parser(parse_expression_infix_function parser,
8509 int token_type, unsigned precedence)
8511 expression_parser_function_t *entry = &expression_parsers[token_type];
8513 if (entry->infix_parser != NULL) {
8514 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8515 panic("trying to register multiple infix expression parsers for a "
8518 entry->infix_parser = parser;
8519 entry->infix_precedence = precedence;
8523 * Initialize the expression parsers.
8525 static void init_expression_parsers(void)
8527 memset(&expression_parsers, 0, sizeof(expression_parsers));
8529 register_infix_parser(parse_array_expression, '[', 30);
8530 register_infix_parser(parse_call_expression, '(', 30);
8531 register_infix_parser(parse_select_expression, '.', 30);
8532 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8533 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8535 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8538 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8539 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8540 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8541 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8542 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8543 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8544 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8545 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8546 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8547 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8548 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8549 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8550 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8551 T_EXCLAMATIONMARKEQUAL, 13);
8552 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8553 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8554 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8555 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8556 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8557 register_infix_parser(parse_conditional_expression, '?', 7);
8558 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8559 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8560 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8561 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8562 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8563 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8564 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8565 T_LESSLESSEQUAL, 2);
8566 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8567 T_GREATERGREATEREQUAL, 2);
8568 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8570 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8572 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8575 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8577 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8578 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8579 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8580 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8581 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8582 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8583 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8585 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8587 register_expression_parser(parse_sizeof, T_sizeof, 25);
8588 register_expression_parser(parse_alignof, T___alignof__, 25);
8589 register_expression_parser(parse_extension, T___extension__, 25);
8590 register_expression_parser(parse_builtin_classify_type,
8591 T___builtin_classify_type, 25);
8595 * Parse a asm statement arguments specification.
8597 static asm_argument_t *parse_asm_arguments(bool is_out)
8599 asm_argument_t *result = NULL;
8600 asm_argument_t *last = NULL;
8602 while (token.type == T_STRING_LITERAL || token.type == '[') {
8603 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8604 memset(argument, 0, sizeof(argument[0]));
8606 if (token.type == '[') {
8608 if (token.type != T_IDENTIFIER) {
8609 parse_error_expected("while parsing asm argument",
8610 T_IDENTIFIER, NULL);
8613 argument->symbol = token.v.symbol;
8618 argument->constraints = parse_string_literals();
8620 add_anchor_token(')');
8621 expression_t *expression = parse_expression();
8622 rem_anchor_token(')');
8624 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8625 * change size or type representation (e.g. int -> long is ok, but
8626 * int -> float is not) */
8627 if (expression->kind == EXPR_UNARY_CAST) {
8628 type_t *const type = expression->base.type;
8629 type_kind_t const kind = type->kind;
8630 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8633 if (kind == TYPE_ATOMIC) {
8634 atomic_type_kind_t const akind = type->atomic.akind;
8635 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8636 size = get_atomic_type_size(akind);
8638 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8639 size = get_atomic_type_size(get_intptr_kind());
8643 expression_t *const value = expression->unary.value;
8644 type_t *const value_type = value->base.type;
8645 type_kind_t const value_kind = value_type->kind;
8647 unsigned value_flags;
8648 unsigned value_size;
8649 if (value_kind == TYPE_ATOMIC) {
8650 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8651 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8652 value_size = get_atomic_type_size(value_akind);
8653 } else if (value_kind == TYPE_POINTER) {
8654 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8655 value_size = get_atomic_type_size(get_intptr_kind());
8660 if (value_flags != flags || value_size != size)
8664 } while (expression->kind == EXPR_UNARY_CAST);
8668 if (!is_lvalue(expression)) {
8669 errorf(&expression->base.source_position,
8670 "asm output argument is not an lvalue");
8673 argument->expression = expression;
8676 set_address_taken(expression, true);
8679 last->next = argument;
8685 if (token.type != ',')
8696 * Parse a asm statement clobber specification.
8698 static asm_clobber_t *parse_asm_clobbers(void)
8700 asm_clobber_t *result = NULL;
8701 asm_clobber_t *last = NULL;
8703 while(token.type == T_STRING_LITERAL) {
8704 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8705 clobber->clobber = parse_string_literals();
8708 last->next = clobber;
8714 if (token.type != ',')
8723 * Parse an asm statement.
8725 static statement_t *parse_asm_statement(void)
8729 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8730 statement->base.source_position = token.source_position;
8732 asm_statement_t *asm_statement = &statement->asms;
8734 if (token.type == T_volatile) {
8736 asm_statement->is_volatile = true;
8740 add_anchor_token(')');
8741 add_anchor_token(':');
8742 asm_statement->asm_text = parse_string_literals();
8744 if (token.type != ':') {
8745 rem_anchor_token(':');
8750 asm_statement->outputs = parse_asm_arguments(true);
8751 if (token.type != ':') {
8752 rem_anchor_token(':');
8757 asm_statement->inputs = parse_asm_arguments(false);
8758 if (token.type != ':') {
8759 rem_anchor_token(':');
8762 rem_anchor_token(':');
8765 asm_statement->clobbers = parse_asm_clobbers();
8768 rem_anchor_token(')');
8772 if (asm_statement->outputs == NULL) {
8773 /* GCC: An 'asm' instruction without any output operands will be treated
8774 * identically to a volatile 'asm' instruction. */
8775 asm_statement->is_volatile = true;
8780 return create_invalid_statement();
8784 * Parse a case statement.
8786 static statement_t *parse_case_statement(void)
8790 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8791 source_position_t *const pos = &statement->base.source_position;
8793 *pos = token.source_position;
8794 expression_t *const expression = parse_expression();
8795 statement->case_label.expression = expression;
8796 if (!is_constant_expression(expression)) {
8797 /* This check does not prevent the error message in all cases of an
8798 * prior error while parsing the expression. At least it catches the
8799 * common case of a mistyped enum entry. */
8800 if (is_type_valid(expression->base.type)) {
8801 errorf(pos, "case label does not reduce to an integer constant");
8803 statement->case_label.is_bad = true;
8805 long const val = fold_constant(expression);
8806 statement->case_label.first_case = val;
8807 statement->case_label.last_case = val;
8811 if (token.type == T_DOTDOTDOT) {
8813 expression_t *const end_range = parse_expression();
8814 statement->case_label.end_range = end_range;
8815 if (!is_constant_expression(end_range)) {
8816 /* This check does not prevent the error message in all cases of an
8817 * prior error while parsing the expression. At least it catches the
8818 * common case of a mistyped enum entry. */
8819 if (is_type_valid(end_range->base.type)) {
8820 errorf(pos, "case range does not reduce to an integer constant");
8822 statement->case_label.is_bad = true;
8824 long const val = fold_constant(end_range);
8825 statement->case_label.last_case = val;
8827 if (val < statement->case_label.first_case) {
8828 statement->case_label.is_empty_range = true;
8829 warningf(pos, "empty range specified");
8835 PUSH_PARENT(statement);
8839 if (current_switch != NULL) {
8840 if (! statement->case_label.is_bad) {
8841 /* Check for duplicate case values */
8842 case_label_statement_t *c = &statement->case_label;
8843 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8844 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8847 if (c->last_case < l->first_case || c->first_case > l->last_case)
8850 errorf(pos, "duplicate case value (previously used %P)",
8851 &l->base.source_position);
8855 /* link all cases into the switch statement */
8856 if (current_switch->last_case == NULL) {
8857 current_switch->first_case = &statement->case_label;
8859 current_switch->last_case->next = &statement->case_label;
8861 current_switch->last_case = &statement->case_label;
8863 errorf(pos, "case label not within a switch statement");
8866 statement_t *const inner_stmt = parse_statement();
8867 statement->case_label.statement = inner_stmt;
8868 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8869 errorf(&inner_stmt->base.source_position, "declaration after case label");
8876 return create_invalid_statement();
8880 * Parse a default statement.
8882 static statement_t *parse_default_statement(void)
8886 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8887 statement->base.source_position = token.source_position;
8889 PUSH_PARENT(statement);
8892 if (current_switch != NULL) {
8893 const case_label_statement_t *def_label = current_switch->default_label;
8894 if (def_label != NULL) {
8895 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8896 &def_label->base.source_position);
8898 current_switch->default_label = &statement->case_label;
8900 /* link all cases into the switch statement */
8901 if (current_switch->last_case == NULL) {
8902 current_switch->first_case = &statement->case_label;
8904 current_switch->last_case->next = &statement->case_label;
8906 current_switch->last_case = &statement->case_label;
8909 errorf(&statement->base.source_position,
8910 "'default' label not within a switch statement");
8913 statement_t *const inner_stmt = parse_statement();
8914 statement->case_label.statement = inner_stmt;
8915 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8916 errorf(&inner_stmt->base.source_position, "declaration after default label");
8923 return create_invalid_statement();
8927 * Parse a label statement.
8929 static statement_t *parse_label_statement(void)
8931 assert(token.type == T_IDENTIFIER);
8932 symbol_t *symbol = token.v.symbol;
8935 declaration_t *label = get_label(symbol);
8937 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8938 statement->base.source_position = token.source_position;
8939 statement->label.label = label;
8941 PUSH_PARENT(statement);
8943 /* if statement is already set then the label is defined twice,
8944 * otherwise it was just mentioned in a goto/local label declaration so far */
8945 if (label->init.statement != NULL) {
8946 errorf(HERE, "duplicate label '%Y' (declared %P)",
8947 symbol, &label->source_position);
8949 label->source_position = token.source_position;
8950 label->init.statement = statement;
8955 if (token.type == '}') {
8956 /* TODO only warn? */
8958 warningf(HERE, "label at end of compound statement");
8959 statement->label.statement = create_empty_statement();
8961 errorf(HERE, "label at end of compound statement");
8962 statement->label.statement = create_invalid_statement();
8964 } else if (token.type == ';') {
8965 /* Eat an empty statement here, to avoid the warning about an empty
8966 * statement after a label. label:; is commonly used to have a label
8967 * before a closing brace. */
8968 statement->label.statement = create_empty_statement();
8971 statement_t *const inner_stmt = parse_statement();
8972 statement->label.statement = inner_stmt;
8973 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8974 errorf(&inner_stmt->base.source_position, "declaration after label");
8978 /* remember the labels in a list for later checking */
8979 if (label_last == NULL) {
8980 label_first = &statement->label;
8982 label_last->next = &statement->label;
8984 label_last = &statement->label;
8991 * Parse an if statement.
8993 static statement_t *parse_if(void)
8997 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8998 statement->base.source_position = token.source_position;
9000 PUSH_PARENT(statement);
9003 add_anchor_token(')');
9004 statement->ifs.condition = parse_expression();
9005 rem_anchor_token(')');
9008 add_anchor_token(T_else);
9009 statement->ifs.true_statement = parse_statement();
9010 rem_anchor_token(T_else);
9012 if (token.type == T_else) {
9014 statement->ifs.false_statement = parse_statement();
9021 return create_invalid_statement();
9025 * Check that all enums are handled in a switch.
9027 * @param statement the switch statement to check
9029 static void check_enum_cases(const switch_statement_t *statement) {
9030 const type_t *type = skip_typeref(statement->expression->base.type);
9031 if (! is_type_enum(type))
9033 const enum_type_t *enumt = &type->enumt;
9035 /* if we have a default, no warnings */
9036 if (statement->default_label != NULL)
9039 /* FIXME: calculation of value should be done while parsing */
9040 const declaration_t *declaration;
9041 long last_value = -1;
9042 for (declaration = enumt->declaration->next;
9043 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9044 declaration = declaration->next) {
9045 const expression_t *expression = declaration->init.enum_value;
9046 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9048 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9049 if (l->expression == NULL)
9051 if (l->first_case <= value && value <= l->last_case) {
9057 warningf(&statement->base.source_position,
9058 "enumeration value '%Y' not handled in switch", declaration->symbol);
9065 * Parse a switch statement.
9067 static statement_t *parse_switch(void)
9071 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9072 statement->base.source_position = token.source_position;
9074 PUSH_PARENT(statement);
9077 add_anchor_token(')');
9078 expression_t *const expr = parse_expression();
9079 type_t * type = skip_typeref(expr->base.type);
9080 if (is_type_integer(type)) {
9081 type = promote_integer(type);
9082 if (warning.traditional) {
9083 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9084 warningf(&expr->base.source_position,
9085 "'%T' switch expression not converted to '%T' in ISO C",
9089 } else if (is_type_valid(type)) {
9090 errorf(&expr->base.source_position,
9091 "switch quantity is not an integer, but '%T'", type);
9092 type = type_error_type;
9094 statement->switchs.expression = create_implicit_cast(expr, type);
9096 rem_anchor_token(')');
9098 switch_statement_t *rem = current_switch;
9099 current_switch = &statement->switchs;
9100 statement->switchs.body = parse_statement();
9101 current_switch = rem;
9103 if (warning.switch_default &&
9104 statement->switchs.default_label == NULL) {
9105 warningf(&statement->base.source_position, "switch has no default case");
9107 if (warning.switch_enum)
9108 check_enum_cases(&statement->switchs);
9114 return create_invalid_statement();
9117 static statement_t *parse_loop_body(statement_t *const loop)
9119 statement_t *const rem = current_loop;
9120 current_loop = loop;
9122 statement_t *const body = parse_statement();
9129 * Parse a while statement.
9131 static statement_t *parse_while(void)
9135 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9136 statement->base.source_position = token.source_position;
9138 PUSH_PARENT(statement);
9141 add_anchor_token(')');
9142 statement->whiles.condition = parse_expression();
9143 rem_anchor_token(')');
9146 statement->whiles.body = parse_loop_body(statement);
9152 return create_invalid_statement();
9156 * Parse a do statement.
9158 static statement_t *parse_do(void)
9162 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9163 statement->base.source_position = token.source_position;
9165 PUSH_PARENT(statement)
9167 add_anchor_token(T_while);
9168 statement->do_while.body = parse_loop_body(statement);
9169 rem_anchor_token(T_while);
9173 add_anchor_token(')');
9174 statement->do_while.condition = parse_expression();
9175 rem_anchor_token(')');
9183 return create_invalid_statement();
9187 * Parse a for statement.
9189 static statement_t *parse_for(void)
9193 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9194 statement->base.source_position = token.source_position;
9196 PUSH_PARENT(statement);
9198 int top = environment_top();
9199 scope_push(&statement->fors.scope);
9202 add_anchor_token(')');
9204 if (token.type != ';') {
9205 if (is_declaration_specifier(&token, false)) {
9206 parse_declaration(record_declaration);
9208 add_anchor_token(';');
9209 expression_t *const init = parse_expression();
9210 statement->fors.initialisation = init;
9211 if (warning.unused_value && !expression_has_effect(init)) {
9212 warningf(&init->base.source_position,
9213 "initialisation of 'for'-statement has no effect");
9215 rem_anchor_token(';');
9222 if (token.type != ';') {
9223 add_anchor_token(';');
9224 statement->fors.condition = parse_expression();
9225 rem_anchor_token(';');
9228 if (token.type != ')') {
9229 expression_t *const step = parse_expression();
9230 statement->fors.step = step;
9231 if (warning.unused_value && !expression_has_effect(step)) {
9232 warningf(&step->base.source_position,
9233 "step of 'for'-statement has no effect");
9236 rem_anchor_token(')');
9238 statement->fors.body = parse_loop_body(statement);
9240 assert(scope == &statement->fors.scope);
9242 environment_pop_to(top);
9249 rem_anchor_token(')');
9250 assert(scope == &statement->fors.scope);
9252 environment_pop_to(top);
9254 return create_invalid_statement();
9258 * Parse a goto statement.
9260 static statement_t *parse_goto(void)
9262 source_position_t source_position = token.source_position;
9265 statement_t *statement;
9266 if (GNU_MODE && token.type == '*') {
9268 expression_t *expression = parse_expression();
9270 /* Argh: although documentation say the expression must be of type void *,
9271 * gcc excepts anything that can be casted into void * without error */
9272 type_t *type = expression->base.type;
9274 if (type != type_error_type) {
9275 if (!is_type_pointer(type) && !is_type_integer(type)) {
9276 errorf(&source_position, "cannot convert to a pointer type");
9277 } else if (type != type_void_ptr) {
9278 warningf(&source_position,
9279 "type of computed goto expression should be 'void*' not '%T'", type);
9281 expression = create_implicit_cast(expression, type_void_ptr);
9284 statement = allocate_statement_zero(STATEMENT_GOTO);
9285 statement->base.source_position = source_position;
9286 statement->gotos.expression = expression;
9288 if (token.type != T_IDENTIFIER) {
9290 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9292 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9296 symbol_t *symbol = token.v.symbol;
9299 statement = allocate_statement_zero(STATEMENT_GOTO);
9300 statement->base.source_position = source_position;
9301 statement->gotos.label = get_label(symbol);
9304 /* remember the goto's in a list for later checking */
9305 if (goto_last == NULL) {
9306 goto_first = &statement->gotos;
9308 goto_last->next = &statement->gotos;
9310 goto_last = &statement->gotos;
9316 return create_invalid_statement();
9320 * Parse a continue statement.
9322 static statement_t *parse_continue(void)
9324 if (current_loop == NULL) {
9325 errorf(HERE, "continue statement not within loop");
9328 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9329 statement->base.source_position = token.source_position;
9339 * Parse a break statement.
9341 static statement_t *parse_break(void)
9343 if (current_switch == NULL && current_loop == NULL) {
9344 errorf(HERE, "break statement not within loop or switch");
9347 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9348 statement->base.source_position = token.source_position;
9358 * Parse a __leave statement.
9360 static statement_t *parse_leave_statement(void)
9362 if (current_try == NULL) {
9363 errorf(HERE, "__leave statement not within __try");
9366 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9367 statement->base.source_position = token.source_position;
9377 * Check if a given declaration represents a local variable.
9379 static bool is_local_var_declaration(const declaration_t *declaration)
9381 switch ((storage_class_tag_t) declaration->storage_class) {
9382 case STORAGE_CLASS_AUTO:
9383 case STORAGE_CLASS_REGISTER: {
9384 const type_t *type = skip_typeref(declaration->type);
9385 if (is_type_function(type)) {
9397 * Check if a given declaration represents a variable.
9399 static bool is_var_declaration(const declaration_t *declaration)
9401 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9404 const type_t *type = skip_typeref(declaration->type);
9405 return !is_type_function(type);
9409 * Check if a given expression represents a local variable.
9411 static bool is_local_variable(const expression_t *expression)
9413 if (expression->base.kind != EXPR_REFERENCE) {
9416 const declaration_t *declaration = expression->reference.declaration;
9417 return is_local_var_declaration(declaration);
9421 * Check if a given expression represents a local variable and
9422 * return its declaration then, else return NULL.
9424 declaration_t *expr_is_variable(const expression_t *expression)
9426 if (expression->base.kind != EXPR_REFERENCE) {
9429 declaration_t *declaration = expression->reference.declaration;
9430 if (is_var_declaration(declaration))
9436 * Parse a return statement.
9438 static statement_t *parse_return(void)
9440 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9441 statement->base.source_position = token.source_position;
9445 expression_t *return_value = NULL;
9446 if (token.type != ';') {
9447 return_value = parse_expression();
9450 const type_t *const func_type = current_function->type;
9451 assert(is_type_function(func_type));
9452 type_t *const return_type = skip_typeref(func_type->function.return_type);
9454 if (return_value != NULL) {
9455 type_t *return_value_type = skip_typeref(return_value->base.type);
9457 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9458 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9459 warningf(&statement->base.source_position,
9460 "'return' with a value, in function returning void");
9461 return_value = NULL;
9463 assign_error_t error = semantic_assign(return_type, return_value);
9464 report_assign_error(error, return_type, return_value, "'return'",
9465 &statement->base.source_position);
9466 return_value = create_implicit_cast(return_value, return_type);
9468 /* check for returning address of a local var */
9469 if (return_value != NULL &&
9470 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9471 const expression_t *expression = return_value->unary.value;
9472 if (is_local_variable(expression)) {
9473 warningf(&statement->base.source_position,
9474 "function returns address of local variable");
9478 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9479 warningf(&statement->base.source_position,
9480 "'return' without value, in function returning non-void");
9483 statement->returns.value = return_value;
9492 * Parse a declaration statement.
9494 static statement_t *parse_declaration_statement(void)
9496 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9498 statement->base.source_position = token.source_position;
9500 declaration_t *before = last_declaration;
9502 parse_external_declaration();
9504 parse_declaration(record_declaration);
9506 if (before == NULL) {
9507 statement->declaration.declarations_begin = scope->declarations;
9509 statement->declaration.declarations_begin = before->next;
9511 statement->declaration.declarations_end = last_declaration;
9517 * Parse an expression statement, ie. expr ';'.
9519 static statement_t *parse_expression_statement(void)
9521 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9523 statement->base.source_position = token.source_position;
9524 expression_t *const expr = parse_expression();
9525 statement->expression.expression = expr;
9534 * Parse a microsoft __try { } __finally { } or
9535 * __try{ } __except() { }
9537 static statement_t *parse_ms_try_statment(void)
9539 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9540 statement->base.source_position = token.source_position;
9543 PUSH_PARENT(statement);
9545 ms_try_statement_t *rem = current_try;
9546 current_try = &statement->ms_try;
9547 statement->ms_try.try_statement = parse_compound_statement(false);
9552 if (token.type == T___except) {
9555 add_anchor_token(')');
9556 expression_t *const expr = parse_expression();
9557 type_t * type = skip_typeref(expr->base.type);
9558 if (is_type_integer(type)) {
9559 type = promote_integer(type);
9560 } else if (is_type_valid(type)) {
9561 errorf(&expr->base.source_position,
9562 "__expect expression is not an integer, but '%T'", type);
9563 type = type_error_type;
9565 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9566 rem_anchor_token(')');
9568 statement->ms_try.final_statement = parse_compound_statement(false);
9569 } else if (token.type == T__finally) {
9571 statement->ms_try.final_statement = parse_compound_statement(false);
9573 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9574 return create_invalid_statement();
9578 return create_invalid_statement();
9581 static statement_t *parse_empty_statement(void)
9583 if (warning.empty_statement) {
9584 warningf(HERE, "statement is empty");
9586 statement_t *const statement = create_empty_statement();
9591 static statement_t *parse_local_label_declaration(void) {
9592 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9593 statement->base.source_position = token.source_position;
9597 declaration_t *begin = NULL, *end = NULL;
9600 if (token.type != T_IDENTIFIER) {
9601 parse_error_expected("while parsing local label declaration",
9602 T_IDENTIFIER, NULL);
9605 symbol_t *symbol = token.v.symbol;
9606 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9607 if (declaration != NULL) {
9608 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9609 symbol, &declaration->source_position);
9611 declaration = allocate_declaration_zero();
9612 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9613 declaration->source_position = token.source_position;
9614 declaration->symbol = symbol;
9615 declaration->parent_scope = scope;
9616 declaration->init.statement = NULL;
9619 end->next = declaration;
9622 begin = declaration;
9624 local_label_push(declaration);
9628 if (token.type != ',')
9634 statement->declaration.declarations_begin = begin;
9635 statement->declaration.declarations_end = end;
9640 * Parse a statement.
9641 * There's also parse_statement() which additionally checks for
9642 * "statement has no effect" warnings
9644 static statement_t *intern_parse_statement(void)
9646 statement_t *statement = NULL;
9648 /* declaration or statement */
9649 add_anchor_token(';');
9650 switch (token.type) {
9651 case T_IDENTIFIER: {
9652 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9653 if (la1_type == ':') {
9654 statement = parse_label_statement();
9655 } else if (is_typedef_symbol(token.v.symbol)) {
9656 statement = parse_declaration_statement();
9657 } else switch (la1_type) {
9659 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9660 goto expression_statment;
9665 statement = parse_declaration_statement();
9669 expression_statment:
9670 statement = parse_expression_statement();
9676 case T___extension__:
9677 /* This can be a prefix to a declaration or an expression statement.
9678 * We simply eat it now and parse the rest with tail recursion. */
9681 } while (token.type == T___extension__);
9682 bool old_gcc_extension = in_gcc_extension;
9683 in_gcc_extension = true;
9684 statement = parse_statement();
9685 in_gcc_extension = old_gcc_extension;
9689 statement = parse_declaration_statement();
9693 statement = parse_local_label_declaration();
9696 case ';': statement = parse_empty_statement(); break;
9697 case '{': statement = parse_compound_statement(false); break;
9698 case T___leave: statement = parse_leave_statement(); break;
9699 case T___try: statement = parse_ms_try_statment(); break;
9700 case T_asm: statement = parse_asm_statement(); break;
9701 case T_break: statement = parse_break(); break;
9702 case T_case: statement = parse_case_statement(); break;
9703 case T_continue: statement = parse_continue(); break;
9704 case T_default: statement = parse_default_statement(); break;
9705 case T_do: statement = parse_do(); break;
9706 case T_for: statement = parse_for(); break;
9707 case T_goto: statement = parse_goto(); break;
9708 case T_if: statement = parse_if (); break;
9709 case T_return: statement = parse_return(); break;
9710 case T_switch: statement = parse_switch(); break;
9711 case T_while: statement = parse_while(); break;
9721 case T_CHARACTER_CONSTANT:
9722 case T_FLOATINGPOINT:
9726 case T_STRING_LITERAL:
9727 case T_WIDE_CHARACTER_CONSTANT:
9728 case T_WIDE_STRING_LITERAL:
9729 case T___FUNCDNAME__:
9731 case T___FUNCTION__:
9732 case T___PRETTY_FUNCTION__:
9733 case T___builtin_alloca:
9734 case T___builtin_classify_type:
9735 case T___builtin_constant_p:
9736 case T___builtin_expect:
9737 case T___builtin_huge_val:
9738 case T___builtin_isgreater:
9739 case T___builtin_isgreaterequal:
9740 case T___builtin_isless:
9741 case T___builtin_islessequal:
9742 case T___builtin_islessgreater:
9743 case T___builtin_isunordered:
9744 case T___builtin_nan:
9745 case T___builtin_nand:
9746 case T___builtin_nanf:
9747 case T___builtin_offsetof:
9748 case T___builtin_prefetch:
9749 case T___builtin_va_arg:
9750 case T___builtin_va_end:
9751 case T___builtin_va_start:
9755 statement = parse_expression_statement();
9759 errorf(HERE, "unexpected token %K while parsing statement", &token);
9760 statement = create_invalid_statement();
9765 rem_anchor_token(';');
9767 assert(statement != NULL
9768 && statement->base.source_position.input_name != NULL);
9774 * parse a statement and emits "statement has no effect" warning if needed
9775 * (This is really a wrapper around intern_parse_statement with check for 1
9776 * single warning. It is needed, because for statement expressions we have
9777 * to avoid the warning on the last statement)
9779 static statement_t *parse_statement(void)
9781 statement_t *statement = intern_parse_statement();
9783 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9784 expression_t *expression = statement->expression.expression;
9785 if (!expression_has_effect(expression)) {
9786 warningf(&expression->base.source_position,
9787 "statement has no effect");
9795 * Parse a compound statement.
9797 static statement_t *parse_compound_statement(bool inside_expression_statement)
9799 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9800 statement->base.source_position = token.source_position;
9802 PUSH_PARENT(statement);
9805 add_anchor_token('}');
9807 int top = environment_top();
9808 int top_local = local_label_top();
9809 scope_push(&statement->compound.scope);
9811 statement_t **anchor = &statement->compound.statements;
9812 bool only_decls_so_far = true;
9813 while (token.type != '}' && token.type != T_EOF) {
9814 statement_t *sub_statement = intern_parse_statement();
9815 if (is_invalid_statement(sub_statement)) {
9816 /* an error occurred. if we are at an anchor, return */
9822 if (warning.declaration_after_statement) {
9823 if (sub_statement->kind != STATEMENT_DECLARATION) {
9824 only_decls_so_far = false;
9825 } else if (!only_decls_so_far) {
9826 warningf(&sub_statement->base.source_position,
9827 "ISO C90 forbids mixed declarations and code");
9831 *anchor = sub_statement;
9833 while (sub_statement->base.next != NULL)
9834 sub_statement = sub_statement->base.next;
9836 anchor = &sub_statement->base.next;
9839 if (token.type == '}') {
9842 errorf(&statement->base.source_position,
9843 "end of file while looking for closing '}'");
9846 /* look over all statements again to produce no effect warnings */
9847 if (warning.unused_value) {
9848 statement_t *sub_statement = statement->compound.statements;
9849 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9850 if (sub_statement->kind != STATEMENT_EXPRESSION)
9852 /* don't emit a warning for the last expression in an expression
9853 * statement as it has always an effect */
9854 if (inside_expression_statement && sub_statement->base.next == NULL)
9857 expression_t *expression = sub_statement->expression.expression;
9858 if (!expression_has_effect(expression)) {
9859 warningf(&expression->base.source_position,
9860 "statement has no effect");
9866 rem_anchor_token('}');
9867 assert(scope == &statement->compound.scope);
9869 environment_pop_to(top);
9870 local_label_pop_to(top_local);
9877 * Initialize builtin types.
9879 static void initialize_builtin_types(void)
9881 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9882 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9883 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9884 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9885 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9886 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9887 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9888 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9890 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9891 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9892 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9893 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9895 /* const version of wchar_t */
9896 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9897 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9898 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9900 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9904 * Check for unused global static functions and variables
9906 static void check_unused_globals(void)
9908 if (!warning.unused_function && !warning.unused_variable)
9911 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9913 decl->modifiers & DM_UNUSED ||
9914 decl->modifiers & DM_USED ||
9915 decl->storage_class != STORAGE_CLASS_STATIC)
9918 type_t *const type = decl->type;
9920 if (is_type_function(skip_typeref(type))) {
9921 if (!warning.unused_function || decl->is_inline)
9924 s = (decl->init.statement != NULL ? "defined" : "declared");
9926 if (!warning.unused_variable)
9932 warningf(&decl->source_position, "'%#T' %s but not used",
9933 type, decl->symbol, s);
9937 static void parse_global_asm(void)
9942 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9943 statement->base.source_position = token.source_position;
9944 statement->asms.asm_text = parse_string_literals();
9945 statement->base.next = unit->global_asm;
9946 unit->global_asm = statement;
9955 * Parse a translation unit.
9957 static void parse_translation_unit(void)
9961 bool anchor_leak = false;
9962 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9963 unsigned char count = token_anchor_set[i];
9965 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9969 if (in_gcc_extension) {
9970 errorf(HERE, "Leaked __extension__");
9978 switch (token.type) {
9981 case T___extension__:
9982 parse_external_declaration();
9993 /* TODO error in strict mode */
9994 warningf(HERE, "stray ';' outside of function");
9999 errorf(HERE, "stray %K outside of function", &token);
10000 if (token.type == '(' || token.type == '{' || token.type == '[')
10001 eat_until_matching_token(token.type);
10011 * @return the translation unit or NULL if errors occurred.
10013 void start_parsing(void)
10015 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10016 label_stack = NEW_ARR_F(stack_entry_t, 0);
10017 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10018 diagnostic_count = 0;
10022 type_set_output(stderr);
10023 ast_set_output(stderr);
10025 assert(unit == NULL);
10026 unit = allocate_ast_zero(sizeof(unit[0]));
10028 assert(global_scope == NULL);
10029 global_scope = &unit->scope;
10031 assert(scope == NULL);
10032 scope_push(&unit->scope);
10034 initialize_builtin_types();
10037 translation_unit_t *finish_parsing(void)
10039 /* do NOT use scope_pop() here, this will crash, will it by hand */
10040 assert(scope == &unit->scope);
10042 last_declaration = NULL;
10044 assert(global_scope == &unit->scope);
10045 check_unused_globals();
10046 global_scope = NULL;
10048 DEL_ARR_F(environment_stack);
10049 DEL_ARR_F(label_stack);
10050 DEL_ARR_F(local_label_stack);
10052 translation_unit_t *result = unit;
10059 lookahead_bufpos = 0;
10060 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10063 parse_translation_unit();
10067 * Initialize the parser.
10069 void init_parser(void)
10071 sym_anonymous = symbol_table_insert("<anonymous>");
10073 if (c_mode & _MS) {
10074 /* add predefined symbols for extended-decl-modifier */
10075 sym_align = symbol_table_insert("align");
10076 sym_allocate = symbol_table_insert("allocate");
10077 sym_dllimport = symbol_table_insert("dllimport");
10078 sym_dllexport = symbol_table_insert("dllexport");
10079 sym_naked = symbol_table_insert("naked");
10080 sym_noinline = symbol_table_insert("noinline");
10081 sym_noreturn = symbol_table_insert("noreturn");
10082 sym_nothrow = symbol_table_insert("nothrow");
10083 sym_novtable = symbol_table_insert("novtable");
10084 sym_property = symbol_table_insert("property");
10085 sym_get = symbol_table_insert("get");
10086 sym_put = symbol_table_insert("put");
10087 sym_selectany = symbol_table_insert("selectany");
10088 sym_thread = symbol_table_insert("thread");
10089 sym_uuid = symbol_table_insert("uuid");
10090 sym_deprecated = symbol_table_insert("deprecated");
10091 sym_restrict = symbol_table_insert("restrict");
10092 sym_noalias = symbol_table_insert("noalias");
10094 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10096 init_expression_parsers();
10097 obstack_init(&temp_obst);
10099 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10100 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10104 * Terminate the parser.
10106 void exit_parser(void)
10108 obstack_free(&temp_obst, NULL);