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 scope->depth == previous_declaration->parent_scope->depth + 1) {
4430 errorf(&declaration->source_position,
4431 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4432 orig_type, symbol, previous_declaration->type, symbol,
4433 &previous_declaration->source_position);
4436 if (previous_declaration != NULL &&
4437 previous_declaration->parent_scope == scope) {
4438 /* can happen for K&R style declarations */
4439 if (previous_declaration->type == NULL) {
4440 previous_declaration->type = declaration->type;
4443 const type_t *prev_type = skip_typeref(previous_declaration->type);
4444 if (!types_compatible(type, prev_type)) {
4445 errorf(&declaration->source_position,
4446 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4447 orig_type, symbol, previous_declaration->type, symbol,
4448 &previous_declaration->source_position);
4450 unsigned old_storage_class = previous_declaration->storage_class;
4451 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4452 errorf(&declaration->source_position,
4453 "redeclaration of enum entry '%Y' (declared %P)",
4454 symbol, &previous_declaration->source_position);
4455 return previous_declaration;
4458 if (warning.redundant_decls &&
4460 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4461 !(previous_declaration->modifiers & DM_USED) &&
4462 !previous_declaration->used) {
4463 warningf(&previous_declaration->source_position,
4464 "unnecessary static forward declaration for '%#T'",
4465 previous_declaration->type, symbol);
4468 unsigned new_storage_class = declaration->storage_class;
4470 if (is_type_incomplete(prev_type)) {
4471 previous_declaration->type = type;
4475 /* pretend no storage class means extern for function
4476 * declarations (except if the previous declaration is neither
4477 * none nor extern) */
4478 if (is_type_function(type)) {
4479 if (prev_type->function.unspecified_parameters) {
4480 previous_declaration->type = type;
4484 switch (old_storage_class) {
4485 case STORAGE_CLASS_NONE:
4486 old_storage_class = STORAGE_CLASS_EXTERN;
4489 case STORAGE_CLASS_EXTERN:
4490 if (is_definition) {
4491 if (warning.missing_prototypes &&
4492 prev_type->function.unspecified_parameters &&
4493 !is_sym_main(symbol)) {
4494 warningf(&declaration->source_position,
4495 "no previous prototype for '%#T'",
4498 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4499 new_storage_class = STORAGE_CLASS_EXTERN;
4508 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4509 new_storage_class == STORAGE_CLASS_EXTERN) {
4510 warn_redundant_declaration:
4511 if (!is_definition &&
4512 warning.redundant_decls &&
4513 is_type_valid(prev_type) &&
4514 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4515 warningf(&declaration->source_position,
4516 "redundant declaration for '%Y' (declared %P)",
4517 symbol, &previous_declaration->source_position);
4519 } else if (current_function == NULL) {
4520 if (old_storage_class != STORAGE_CLASS_STATIC &&
4521 new_storage_class == STORAGE_CLASS_STATIC) {
4522 errorf(&declaration->source_position,
4523 "static declaration of '%Y' follows non-static declaration (declared %P)",
4524 symbol, &previous_declaration->source_position);
4525 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4526 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4527 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4529 goto warn_redundant_declaration;
4531 } else if (is_type_valid(prev_type)) {
4532 if (old_storage_class == new_storage_class) {
4533 errorf(&declaration->source_position,
4534 "redeclaration of '%Y' (declared %P)",
4535 symbol, &previous_declaration->source_position);
4537 errorf(&declaration->source_position,
4538 "redeclaration of '%Y' with different linkage (declared %P)",
4539 symbol, &previous_declaration->source_position);
4544 previous_declaration->modifiers |= declaration->modifiers;
4545 previous_declaration->is_inline |= declaration->is_inline;
4546 return previous_declaration;
4547 } else if (is_type_function(type)) {
4548 if (is_definition &&
4549 declaration->storage_class != STORAGE_CLASS_STATIC) {
4550 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4551 warningf(&declaration->source_position,
4552 "no previous prototype for '%#T'", orig_type, symbol);
4553 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4554 warningf(&declaration->source_position,
4555 "no previous declaration for '%#T'", orig_type,
4560 if (warning.missing_declarations &&
4561 scope == global_scope && (
4562 declaration->storage_class == STORAGE_CLASS_NONE ||
4563 declaration->storage_class == STORAGE_CLASS_THREAD
4565 warningf(&declaration->source_position,
4566 "no previous declaration for '%#T'", orig_type, symbol);
4570 assert(declaration->parent_scope == NULL);
4571 assert(scope != NULL);
4573 declaration->parent_scope = scope;
4575 environment_push(declaration);
4576 return append_declaration(declaration);
4579 static void parser_error_multiple_definition(declaration_t *declaration,
4580 const source_position_t *source_position)
4582 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4583 declaration->symbol, &declaration->source_position);
4586 static bool is_declaration_specifier(const token_t *token,
4587 bool only_specifiers_qualifiers)
4589 switch (token->type) {
4594 return is_typedef_symbol(token->v.symbol);
4596 case T___extension__:
4598 return !only_specifiers_qualifiers;
4605 static void parse_init_declarator_rest(declaration_t *declaration)
4609 type_t *orig_type = declaration->type;
4610 type_t *type = skip_typeref(orig_type);
4612 if (declaration->init.initializer != NULL) {
4613 parser_error_multiple_definition(declaration, HERE);
4616 bool must_be_constant = false;
4617 if (declaration->storage_class == STORAGE_CLASS_STATIC
4618 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4619 || declaration->parent_scope == global_scope) {
4620 must_be_constant = true;
4623 if (is_type_function(type)) {
4624 errorf(&declaration->source_position,
4625 "function '%#T' is initialized like a variable",
4626 orig_type, declaration->symbol);
4627 orig_type = type_error_type;
4630 parse_initializer_env_t env;
4631 env.type = orig_type;
4632 env.must_be_constant = must_be_constant;
4633 env.declaration = current_init_decl = declaration;
4635 initializer_t *initializer = parse_initializer(&env);
4636 current_init_decl = NULL;
4638 if (!is_type_function(type)) {
4639 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4640 * the array type size */
4641 declaration->type = env.type;
4642 declaration->init.initializer = initializer;
4646 /* parse rest of a declaration without any declarator */
4647 static void parse_anonymous_declaration_rest(
4648 const declaration_specifiers_t *specifiers)
4652 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4653 warningf(&specifiers->source_position,
4654 "useless storage class in empty declaration");
4657 type_t *type = specifiers->type;
4658 switch (type->kind) {
4659 case TYPE_COMPOUND_STRUCT:
4660 case TYPE_COMPOUND_UNION: {
4661 if (type->compound.declaration->symbol == NULL) {
4662 warningf(&specifiers->source_position,
4663 "unnamed struct/union that defines no instances");
4672 warningf(&specifiers->source_position, "empty declaration");
4676 #ifdef RECORD_EMPTY_DECLARATIONS
4677 declaration_t *const declaration = allocate_declaration_zero();
4678 declaration->type = specifiers->type;
4679 declaration->declared_storage_class = specifiers->declared_storage_class;
4680 declaration->source_position = specifiers->source_position;
4681 declaration->modifiers = specifiers->modifiers;
4682 declaration->storage_class = STORAGE_CLASS_NONE;
4684 append_declaration(declaration);
4688 static void parse_declaration_rest(declaration_t *ndeclaration,
4689 const declaration_specifiers_t *specifiers,
4690 parsed_declaration_func finished_declaration)
4692 add_anchor_token(';');
4693 add_anchor_token(',');
4695 declaration_t *declaration =
4696 finished_declaration(ndeclaration, token.type == '=');
4698 type_t *orig_type = declaration->type;
4699 type_t *type = skip_typeref(orig_type);
4701 if (type->kind != TYPE_FUNCTION &&
4702 declaration->is_inline &&
4703 is_type_valid(type)) {
4704 warningf(&declaration->source_position,
4705 "variable '%Y' declared 'inline'\n", declaration->symbol);
4708 if (token.type == '=') {
4709 parse_init_declarator_rest(declaration);
4712 if (token.type != ',')
4716 add_anchor_token('=');
4717 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4718 rem_anchor_token('=');
4723 rem_anchor_token(';');
4724 rem_anchor_token(',');
4727 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4729 symbol_t *symbol = declaration->symbol;
4730 if (symbol == NULL) {
4731 errorf(HERE, "anonymous declaration not valid as function parameter");
4734 namespace_t namespc = (namespace_t) declaration->namespc;
4735 if (namespc != NAMESPACE_NORMAL) {
4736 return record_declaration(declaration, false);
4739 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4740 if (previous_declaration == NULL ||
4741 previous_declaration->parent_scope != scope) {
4742 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4747 if (is_definition) {
4748 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4751 if (previous_declaration->type == NULL) {
4752 previous_declaration->type = declaration->type;
4753 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4754 previous_declaration->storage_class = declaration->storage_class;
4755 previous_declaration->parent_scope = scope;
4756 return previous_declaration;
4758 return record_declaration(declaration, false);
4762 static void parse_declaration(parsed_declaration_func finished_declaration)
4764 declaration_specifiers_t specifiers;
4765 memset(&specifiers, 0, sizeof(specifiers));
4767 add_anchor_token(';');
4768 parse_declaration_specifiers(&specifiers);
4769 rem_anchor_token(';');
4771 if (token.type == ';') {
4772 parse_anonymous_declaration_rest(&specifiers);
4774 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4775 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4779 static type_t *get_default_promoted_type(type_t *orig_type)
4781 type_t *result = orig_type;
4783 type_t *type = skip_typeref(orig_type);
4784 if (is_type_integer(type)) {
4785 result = promote_integer(type);
4786 } else if (type == type_float) {
4787 result = type_double;
4793 static void parse_kr_declaration_list(declaration_t *declaration)
4795 type_t *type = skip_typeref(declaration->type);
4796 if (!is_type_function(type))
4799 if (!type->function.kr_style_parameters)
4802 add_anchor_token('{');
4804 /* push function parameters */
4805 int top = environment_top();
4806 scope_push(&declaration->scope);
4808 declaration_t *parameter = declaration->scope.declarations;
4809 for ( ; parameter != NULL; parameter = parameter->next) {
4810 assert(parameter->parent_scope == NULL);
4811 parameter->parent_scope = scope;
4812 environment_push(parameter);
4815 /* parse declaration list */
4816 while (is_declaration_specifier(&token, false)) {
4817 parse_declaration(finished_kr_declaration);
4820 /* pop function parameters */
4821 assert(scope == &declaration->scope);
4823 environment_pop_to(top);
4825 /* update function type */
4826 type_t *new_type = duplicate_type(type);
4828 function_parameter_t *parameters = NULL;
4829 function_parameter_t *last_parameter = NULL;
4831 declaration_t *parameter_declaration = declaration->scope.declarations;
4832 for( ; parameter_declaration != NULL;
4833 parameter_declaration = parameter_declaration->next) {
4834 type_t *parameter_type = parameter_declaration->type;
4835 if (parameter_type == NULL) {
4837 errorf(HERE, "no type specified for function parameter '%Y'",
4838 parameter_declaration->symbol);
4840 if (warning.implicit_int) {
4841 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4842 parameter_declaration->symbol);
4844 parameter_type = type_int;
4845 parameter_declaration->type = parameter_type;
4849 semantic_parameter(parameter_declaration);
4850 parameter_type = parameter_declaration->type;
4853 * we need the default promoted types for the function type
4855 parameter_type = get_default_promoted_type(parameter_type);
4857 function_parameter_t *function_parameter
4858 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4859 memset(function_parameter, 0, sizeof(function_parameter[0]));
4861 function_parameter->type = parameter_type;
4862 if (last_parameter != NULL) {
4863 last_parameter->next = function_parameter;
4865 parameters = function_parameter;
4867 last_parameter = function_parameter;
4870 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4872 new_type->function.parameters = parameters;
4873 new_type->function.unspecified_parameters = true;
4875 type = typehash_insert(new_type);
4876 if (type != new_type) {
4877 obstack_free(type_obst, new_type);
4880 declaration->type = type;
4882 rem_anchor_token('{');
4885 static bool first_err = true;
4888 * When called with first_err set, prints the name of the current function,
4891 static void print_in_function(void)
4895 diagnosticf("%s: In function '%Y':\n",
4896 current_function->source_position.input_name,
4897 current_function->symbol);
4902 * Check if all labels are defined in the current function.
4903 * Check if all labels are used in the current function.
4905 static void check_labels(void)
4907 for (const goto_statement_t *goto_statement = goto_first;
4908 goto_statement != NULL;
4909 goto_statement = goto_statement->next) {
4910 /* skip computed gotos */
4911 if (goto_statement->expression != NULL)
4914 declaration_t *label = goto_statement->label;
4917 if (label->source_position.input_name == NULL) {
4918 print_in_function();
4919 errorf(&goto_statement->base.source_position,
4920 "label '%Y' used but not defined", label->symbol);
4923 goto_first = goto_last = NULL;
4925 if (warning.unused_label) {
4926 for (const label_statement_t *label_statement = label_first;
4927 label_statement != NULL;
4928 label_statement = label_statement->next) {
4929 const declaration_t *label = label_statement->label;
4931 if (! label->used) {
4932 print_in_function();
4933 warningf(&label_statement->base.source_position,
4934 "label '%Y' defined but not used", label->symbol);
4938 label_first = label_last = NULL;
4942 * Check declarations of current_function for unused entities.
4944 static void check_declarations(void)
4946 if (warning.unused_parameter) {
4947 const scope_t *scope = ¤t_function->scope;
4949 if (is_sym_main(current_function->symbol)) {
4950 /* do not issue unused warnings for main */
4953 const declaration_t *parameter = scope->declarations;
4954 for (; parameter != NULL; parameter = parameter->next) {
4955 if (! parameter->used) {
4956 print_in_function();
4957 warningf(¶meter->source_position,
4958 "unused parameter '%Y'", parameter->symbol);
4962 if (warning.unused_variable) {
4966 static int determine_truth(expression_t const* const cond)
4969 !is_constant_expression(cond) ? 0 :
4970 fold_constant(cond) != 0 ? 1 :
4974 static bool noreturn_candidate;
4976 static void check_reachable(statement_t *const stmt)
4978 if (stmt->base.reachable)
4980 if (stmt->kind != STATEMENT_DO_WHILE)
4981 stmt->base.reachable = true;
4983 statement_t *last = stmt;
4985 switch (stmt->kind) {
4986 case STATEMENT_INVALID:
4987 case STATEMENT_EMPTY:
4988 case STATEMENT_DECLARATION:
4990 next = stmt->base.next;
4993 case STATEMENT_COMPOUND:
4994 next = stmt->compound.statements;
4997 case STATEMENT_RETURN:
4998 noreturn_candidate = false;
5001 case STATEMENT_IF: {
5002 if_statement_t const* const ifs = &stmt->ifs;
5003 int const val = determine_truth(ifs->condition);
5006 check_reachable(ifs->true_statement);
5011 if (ifs->false_statement != NULL) {
5012 check_reachable(ifs->false_statement);
5016 next = stmt->base.next;
5020 case STATEMENT_SWITCH: {
5021 switch_statement_t const *const switchs = &stmt->switchs;
5022 expression_t const *const expr = switchs->expression;
5024 if (is_constant_expression(expr)) {
5025 long const val = fold_constant(expr);
5026 case_label_statement_t * defaults = NULL;
5027 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5028 if (i->expression == NULL) {
5033 if (i->first_case <= val && val <= i->last_case) {
5034 check_reachable((statement_t*)i);
5039 if (defaults != NULL) {
5040 check_reachable((statement_t*)defaults);
5044 bool has_default = false;
5045 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5046 if (i->expression == NULL)
5049 check_reachable((statement_t*)i);
5056 next = stmt->base.next;
5060 case STATEMENT_EXPRESSION: {
5061 /* Check for noreturn function call */
5062 expression_t const *const expr = stmt->expression.expression;
5063 if (expr->kind == EXPR_CALL) {
5064 expression_t const *const func = expr->call.function;
5065 if (func->kind == EXPR_REFERENCE) {
5066 declaration_t const *const decl = func->reference.declaration;
5067 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5073 next = stmt->base.next;
5077 case STATEMENT_CONTINUE: {
5078 statement_t *parent = stmt;
5080 parent = parent->base.parent;
5081 if (parent == NULL) /* continue not within loop */
5085 switch (parent->kind) {
5086 case STATEMENT_WHILE: goto continue_while;
5087 case STATEMENT_DO_WHILE: goto continue_do_while;
5088 case STATEMENT_FOR: goto continue_for;
5095 case STATEMENT_BREAK: {
5096 statement_t *parent = stmt;
5098 parent = parent->base.parent;
5099 if (parent == NULL) /* break not within loop/switch */
5102 switch (parent->kind) {
5103 case STATEMENT_SWITCH:
5104 case STATEMENT_WHILE:
5105 case STATEMENT_DO_WHILE:
5108 next = parent->base.next;
5109 goto found_break_parent;
5118 case STATEMENT_GOTO:
5119 if (stmt->gotos.expression) {
5120 statement_t *parent = stmt->base.parent;
5121 if (parent == NULL) /* top level goto */
5125 next = stmt->gotos.label->init.statement;
5126 if (next == NULL) /* missing label */
5131 case STATEMENT_LABEL:
5132 next = stmt->label.statement;
5135 case STATEMENT_CASE_LABEL:
5136 next = stmt->case_label.statement;
5139 case STATEMENT_WHILE: {
5140 while_statement_t const *const whiles = &stmt->whiles;
5141 int const val = determine_truth(whiles->condition);
5144 check_reachable(whiles->body);
5149 next = stmt->base.next;
5153 case STATEMENT_DO_WHILE:
5154 next = stmt->do_while.body;
5157 case STATEMENT_FOR: {
5158 for_statement_t *const fors = &stmt->fors;
5160 if (fors->condition_reachable)
5162 fors->condition_reachable = true;
5164 expression_t const *const cond = fors->condition;
5166 cond == NULL ? 1 : determine_truth(cond);
5169 check_reachable(fors->body);
5174 next = stmt->base.next;
5178 case STATEMENT_MS_TRY: {
5179 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5180 check_reachable(ms_try->try_statement);
5181 next = ms_try->final_statement;
5185 case STATEMENT_LEAVE: {
5186 statement_t *parent = stmt;
5188 parent = parent->base.parent;
5189 if (parent == NULL) /* __leave not within __try */
5192 if (parent->kind == STATEMENT_MS_TRY) {
5194 next = parent->ms_try.final_statement;
5202 while (next == NULL) {
5203 next = last->base.parent;
5205 noreturn_candidate = false;
5207 type_t *const type = current_function->type;
5208 assert(is_type_function(type));
5209 type_t *const ret = skip_typeref(type->function.return_type);
5210 if (warning.return_type &&
5211 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5212 is_type_valid(ret) &&
5213 !is_sym_main(current_function->symbol)) {
5214 warningf(&stmt->base.source_position,
5215 "control reaches end of non-void function");
5220 switch (next->kind) {
5221 case STATEMENT_INVALID:
5222 case STATEMENT_EMPTY:
5223 case STATEMENT_DECLARATION:
5224 case STATEMENT_EXPRESSION:
5226 case STATEMENT_RETURN:
5227 case STATEMENT_CONTINUE:
5228 case STATEMENT_BREAK:
5229 case STATEMENT_GOTO:
5230 case STATEMENT_LEAVE:
5231 panic("invalid control flow in function");
5233 case STATEMENT_COMPOUND:
5235 case STATEMENT_SWITCH:
5236 case STATEMENT_LABEL:
5237 case STATEMENT_CASE_LABEL:
5239 next = next->base.next;
5242 case STATEMENT_WHILE: {
5244 if (next->base.reachable)
5246 next->base.reachable = true;
5248 while_statement_t const *const whiles = &next->whiles;
5249 int const val = determine_truth(whiles->condition);
5252 check_reachable(whiles->body);
5258 next = next->base.next;
5262 case STATEMENT_DO_WHILE: {
5264 if (next->base.reachable)
5266 next->base.reachable = true;
5268 do_while_statement_t const *const dw = &next->do_while;
5269 int const val = determine_truth(dw->condition);
5272 check_reachable(dw->body);
5278 next = next->base.next;
5282 case STATEMENT_FOR: {
5284 for_statement_t *const fors = &next->fors;
5286 fors->step_reachable = true;
5288 if (fors->condition_reachable)
5290 fors->condition_reachable = true;
5292 expression_t const *const cond = fors->condition;
5294 cond == NULL ? 1 : determine_truth(cond);
5297 check_reachable(fors->body);
5303 next = next->base.next;
5307 case STATEMENT_MS_TRY:
5309 next = next->ms_try.final_statement;
5315 next = stmt->base.parent;
5317 warningf(&stmt->base.source_position,
5318 "control reaches end of non-void function");
5322 check_reachable(next);
5325 static void check_unreachable(statement_t const* const stmt)
5327 if (!stmt->base.reachable &&
5328 stmt->kind != STATEMENT_DO_WHILE &&
5329 stmt->kind != STATEMENT_FOR &&
5330 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5331 warningf(&stmt->base.source_position, "statement is unreachable");
5334 switch (stmt->kind) {
5335 case STATEMENT_INVALID:
5336 case STATEMENT_EMPTY:
5337 case STATEMENT_RETURN:
5338 case STATEMENT_DECLARATION:
5339 case STATEMENT_EXPRESSION:
5340 case STATEMENT_CONTINUE:
5341 case STATEMENT_BREAK:
5342 case STATEMENT_GOTO:
5344 case STATEMENT_LEAVE:
5347 case STATEMENT_COMPOUND:
5348 if (stmt->compound.statements)
5349 check_unreachable(stmt->compound.statements);
5353 check_unreachable(stmt->ifs.true_statement);
5354 if (stmt->ifs.false_statement != NULL)
5355 check_unreachable(stmt->ifs.false_statement);
5358 case STATEMENT_SWITCH:
5359 check_unreachable(stmt->switchs.body);
5362 case STATEMENT_LABEL:
5363 check_unreachable(stmt->label.statement);
5366 case STATEMENT_CASE_LABEL:
5367 check_unreachable(stmt->case_label.statement);
5370 case STATEMENT_WHILE:
5371 check_unreachable(stmt->whiles.body);
5374 case STATEMENT_DO_WHILE:
5375 check_unreachable(stmt->do_while.body);
5376 if (!stmt->base.reachable) {
5377 expression_t const *const cond = stmt->do_while.condition;
5378 if (determine_truth(cond) >= 0) {
5379 warningf(&cond->base.source_position,
5380 "condition of do-while-loop is unreachable");
5385 case STATEMENT_FOR: {
5386 for_statement_t const* const fors = &stmt->fors;
5388 // if init and step are unreachable, cond is unreachable, too
5389 if (!stmt->base.reachable && !fors->step_reachable) {
5390 warningf(&stmt->base.source_position, "statement is unreachable");
5392 if (!stmt->base.reachable && fors->initialisation != NULL) {
5393 warningf(&fors->initialisation->base.source_position,
5394 "initialisation of for-statement is unreachable");
5397 if (!fors->condition_reachable && fors->condition != NULL) {
5398 warningf(&fors->condition->base.source_position,
5399 "condition of for-statement is unreachable");
5402 if (!fors->step_reachable && fors->step != NULL) {
5403 warningf(&fors->step->base.source_position,
5404 "step of for-statement is unreachable");
5408 check_unreachable(fors->body);
5412 case STATEMENT_MS_TRY: {
5413 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5414 check_unreachable(ms_try->try_statement);
5415 check_unreachable(ms_try->final_statement);
5419 if (stmt->base.next)
5420 check_unreachable(stmt->base.next);
5423 static void parse_external_declaration(void)
5425 /* function-definitions and declarations both start with declaration
5427 declaration_specifiers_t specifiers;
5428 memset(&specifiers, 0, sizeof(specifiers));
5430 add_anchor_token(';');
5431 parse_declaration_specifiers(&specifiers);
5432 rem_anchor_token(';');
5434 /* must be a declaration */
5435 if (token.type == ';') {
5436 parse_anonymous_declaration_rest(&specifiers);
5440 add_anchor_token(',');
5441 add_anchor_token('=');
5442 add_anchor_token(';');
5443 add_anchor_token('{');
5445 /* declarator is common to both function-definitions and declarations */
5446 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5448 rem_anchor_token('{');
5449 rem_anchor_token(';');
5450 rem_anchor_token('=');
5451 rem_anchor_token(',');
5453 /* must be a declaration */
5454 switch (token.type) {
5458 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5462 /* must be a function definition */
5463 parse_kr_declaration_list(ndeclaration);
5465 if (token.type != '{') {
5466 parse_error_expected("while parsing function definition", '{', NULL);
5467 eat_until_matching_token(';');
5471 type_t *type = ndeclaration->type;
5473 /* note that we don't skip typerefs: the standard doesn't allow them here
5474 * (so we can't use is_type_function here) */
5475 if (type->kind != TYPE_FUNCTION) {
5476 if (is_type_valid(type)) {
5477 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5478 type, ndeclaration->symbol);
5484 if (warning.aggregate_return &&
5485 is_type_compound(skip_typeref(type->function.return_type))) {
5486 warningf(HERE, "function '%Y' returns an aggregate",
5487 ndeclaration->symbol);
5489 if (warning.traditional && !type->function.unspecified_parameters) {
5490 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5491 ndeclaration->symbol);
5493 if (warning.old_style_definition && type->function.unspecified_parameters) {
5494 warningf(HERE, "old-style function definition '%Y'",
5495 ndeclaration->symbol);
5498 /* § 6.7.5.3 (14) a function definition with () means no
5499 * parameters (and not unspecified parameters) */
5500 if (type->function.unspecified_parameters
5501 && type->function.parameters == NULL
5502 && !type->function.kr_style_parameters) {
5503 type_t *duplicate = duplicate_type(type);
5504 duplicate->function.unspecified_parameters = false;
5506 type = typehash_insert(duplicate);
5507 if (type != duplicate) {
5508 obstack_free(type_obst, duplicate);
5510 ndeclaration->type = type;
5513 declaration_t *const declaration = record_declaration(ndeclaration, true);
5514 if (ndeclaration != declaration) {
5515 declaration->scope = ndeclaration->scope;
5517 type = skip_typeref(declaration->type);
5519 /* push function parameters and switch scope */
5520 int top = environment_top();
5521 scope_push(&declaration->scope);
5523 declaration_t *parameter = declaration->scope.declarations;
5524 for( ; parameter != NULL; parameter = parameter->next) {
5525 if (parameter->parent_scope == &ndeclaration->scope) {
5526 parameter->parent_scope = scope;
5528 assert(parameter->parent_scope == NULL
5529 || parameter->parent_scope == scope);
5530 parameter->parent_scope = scope;
5531 if (parameter->symbol == NULL) {
5532 errorf(¶meter->source_position, "parameter name omitted");
5535 environment_push(parameter);
5538 if (declaration->init.statement != NULL) {
5539 parser_error_multiple_definition(declaration, HERE);
5542 /* parse function body */
5543 int label_stack_top = label_top();
5544 declaration_t *old_current_function = current_function;
5545 current_function = declaration;
5546 current_parent = NULL;
5548 statement_t *const body = parse_compound_statement(false);
5549 declaration->init.statement = body;
5552 check_declarations();
5553 if (warning.return_type ||
5554 warning.unreachable_code ||
5555 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5556 noreturn_candidate = true;
5557 check_reachable(body);
5558 if (warning.unreachable_code)
5559 check_unreachable(body);
5560 if (warning.missing_noreturn &&
5561 noreturn_candidate &&
5562 !(declaration->modifiers & DM_NORETURN)) {
5563 warningf(&body->base.source_position,
5564 "function '%#T' is candidate for attribute 'noreturn'",
5565 type, declaration->symbol);
5569 assert(current_parent == NULL);
5570 assert(current_function == declaration);
5571 current_function = old_current_function;
5572 label_pop_to(label_stack_top);
5575 assert(scope == &declaration->scope);
5577 environment_pop_to(top);
5580 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5581 source_position_t *source_position,
5582 const symbol_t *symbol)
5584 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5586 type->bitfield.base_type = base_type;
5587 type->bitfield.size_expression = size;
5590 type_t *skipped_type = skip_typeref(base_type);
5591 if (!is_type_integer(skipped_type)) {
5592 errorf(HERE, "bitfield base type '%T' is not an integer type",
5596 bit_size = skipped_type->base.size * 8;
5599 if (is_constant_expression(size)) {
5600 long v = fold_constant(size);
5603 errorf(source_position, "negative width in bit-field '%Y'",
5605 } else if (v == 0) {
5606 errorf(source_position, "zero width for bit-field '%Y'",
5608 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5609 errorf(source_position, "width of '%Y' exceeds its type",
5612 type->bitfield.bit_size = v;
5619 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5622 declaration_t *iter = compound_declaration->scope.declarations;
5623 for( ; iter != NULL; iter = iter->next) {
5624 if (iter->namespc != NAMESPACE_NORMAL)
5627 if (iter->symbol == NULL) {
5628 type_t *type = skip_typeref(iter->type);
5629 if (is_type_compound(type)) {
5630 declaration_t *result
5631 = find_compound_entry(type->compound.declaration, symbol);
5638 if (iter->symbol == symbol) {
5646 static void parse_compound_declarators(declaration_t *struct_declaration,
5647 const declaration_specifiers_t *specifiers)
5649 declaration_t *last_declaration = struct_declaration->scope.declarations;
5650 if (last_declaration != NULL) {
5651 while (last_declaration->next != NULL) {
5652 last_declaration = last_declaration->next;
5657 declaration_t *declaration;
5659 if (token.type == ':') {
5660 source_position_t source_position = *HERE;
5663 type_t *base_type = specifiers->type;
5664 expression_t *size = parse_constant_expression();
5666 type_t *type = make_bitfield_type(base_type, size,
5667 &source_position, sym_anonymous);
5669 declaration = allocate_declaration_zero();
5670 declaration->namespc = NAMESPACE_NORMAL;
5671 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5672 declaration->storage_class = STORAGE_CLASS_NONE;
5673 declaration->source_position = source_position;
5674 declaration->modifiers = specifiers->modifiers;
5675 declaration->type = type;
5677 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5679 type_t *orig_type = declaration->type;
5680 type_t *type = skip_typeref(orig_type);
5682 if (token.type == ':') {
5683 source_position_t source_position = *HERE;
5685 expression_t *size = parse_constant_expression();
5687 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5688 &source_position, declaration->symbol);
5689 declaration->type = bitfield_type;
5691 /* TODO we ignore arrays for now... what is missing is a check
5692 * that they're at the end of the struct */
5693 if (is_type_incomplete(type) && !is_type_array(type)) {
5695 "compound member '%Y' has incomplete type '%T'",
5696 declaration->symbol, orig_type);
5697 } else if (is_type_function(type)) {
5698 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5699 declaration->symbol, orig_type);
5704 /* make sure we don't define a symbol multiple times */
5705 symbol_t *symbol = declaration->symbol;
5706 if (symbol != NULL) {
5707 declaration_t *prev_decl
5708 = find_compound_entry(struct_declaration, symbol);
5710 if (prev_decl != NULL) {
5711 assert(prev_decl->symbol == symbol);
5712 errorf(&declaration->source_position,
5713 "multiple declarations of symbol '%Y' (declared %P)",
5714 symbol, &prev_decl->source_position);
5718 /* append declaration */
5719 if (last_declaration != NULL) {
5720 last_declaration->next = declaration;
5722 struct_declaration->scope.declarations = declaration;
5724 last_declaration = declaration;
5726 if (token.type != ',')
5736 static void parse_compound_type_entries(declaration_t *compound_declaration)
5739 add_anchor_token('}');
5741 while (token.type != '}' && token.type != T_EOF) {
5742 declaration_specifiers_t specifiers;
5743 memset(&specifiers, 0, sizeof(specifiers));
5744 parse_declaration_specifiers(&specifiers);
5746 parse_compound_declarators(compound_declaration, &specifiers);
5748 rem_anchor_token('}');
5750 if (token.type == T_EOF) {
5751 errorf(HERE, "EOF while parsing struct");
5756 static type_t *parse_typename(void)
5758 declaration_specifiers_t specifiers;
5759 memset(&specifiers, 0, sizeof(specifiers));
5760 parse_declaration_specifiers(&specifiers);
5761 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5762 /* TODO: improve error message, user does probably not know what a
5763 * storage class is...
5765 errorf(HERE, "typename may not have a storage class");
5768 type_t *result = parse_abstract_declarator(specifiers.type);
5776 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5777 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5778 expression_t *left);
5780 typedef struct expression_parser_function_t expression_parser_function_t;
5781 struct expression_parser_function_t {
5782 unsigned precedence;
5783 parse_expression_function parser;
5784 unsigned infix_precedence;
5785 parse_expression_infix_function infix_parser;
5788 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5791 * Prints an error message if an expression was expected but not read
5793 static expression_t *expected_expression_error(void)
5795 /* skip the error message if the error token was read */
5796 if (token.type != T_ERROR) {
5797 errorf(HERE, "expected expression, got token '%K'", &token);
5801 return create_invalid_expression();
5805 * Parse a string constant.
5807 static expression_t *parse_string_const(void)
5810 if (token.type == T_STRING_LITERAL) {
5811 string_t res = token.v.string;
5813 while (token.type == T_STRING_LITERAL) {
5814 res = concat_strings(&res, &token.v.string);
5817 if (token.type != T_WIDE_STRING_LITERAL) {
5818 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5819 /* note: that we use type_char_ptr here, which is already the
5820 * automatic converted type. revert_automatic_type_conversion
5821 * will construct the array type */
5822 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5823 cnst->string.value = res;
5827 wres = concat_string_wide_string(&res, &token.v.wide_string);
5829 wres = token.v.wide_string;
5834 switch (token.type) {
5835 case T_WIDE_STRING_LITERAL:
5836 wres = concat_wide_strings(&wres, &token.v.wide_string);
5839 case T_STRING_LITERAL:
5840 wres = concat_wide_string_string(&wres, &token.v.string);
5844 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5845 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5846 cnst->wide_string.value = wres;
5855 * Parse an integer constant.
5857 static expression_t *parse_int_const(void)
5859 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5860 cnst->base.source_position = *HERE;
5861 cnst->base.type = token.datatype;
5862 cnst->conste.v.int_value = token.v.intvalue;
5870 * Parse a character constant.
5872 static expression_t *parse_character_constant(void)
5874 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5876 cnst->base.source_position = *HERE;
5877 cnst->base.type = token.datatype;
5878 cnst->conste.v.character = token.v.string;
5880 if (cnst->conste.v.character.size != 1) {
5881 if (warning.multichar && GNU_MODE) {
5882 warningf(HERE, "multi-character character constant");
5884 errorf(HERE, "more than 1 characters in character constant");
5893 * Parse a wide character constant.
5895 static expression_t *parse_wide_character_constant(void)
5897 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5899 cnst->base.source_position = *HERE;
5900 cnst->base.type = token.datatype;
5901 cnst->conste.v.wide_character = token.v.wide_string;
5903 if (cnst->conste.v.wide_character.size != 1) {
5904 if (warning.multichar && GNU_MODE) {
5905 warningf(HERE, "multi-character character constant");
5907 errorf(HERE, "more than 1 characters in character constant");
5916 * Parse a float constant.
5918 static expression_t *parse_float_const(void)
5920 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5921 cnst->base.type = token.datatype;
5922 cnst->conste.v.float_value = token.v.floatvalue;
5929 static declaration_t *create_implicit_function(symbol_t *symbol,
5930 const source_position_t *source_position)
5932 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5933 ntype->function.return_type = type_int;
5934 ntype->function.unspecified_parameters = true;
5936 type_t *type = typehash_insert(ntype);
5937 if (type != ntype) {
5941 declaration_t *const declaration = allocate_declaration_zero();
5942 declaration->storage_class = STORAGE_CLASS_EXTERN;
5943 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5944 declaration->type = type;
5945 declaration->symbol = symbol;
5946 declaration->source_position = *source_position;
5947 declaration->implicit = true;
5949 bool strict_prototypes_old = warning.strict_prototypes;
5950 warning.strict_prototypes = false;
5951 record_declaration(declaration, false);
5952 warning.strict_prototypes = strict_prototypes_old;
5958 * Creates a return_type (func)(argument_type) function type if not
5961 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5962 type_t *argument_type2)
5964 function_parameter_t *parameter2
5965 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5966 memset(parameter2, 0, sizeof(parameter2[0]));
5967 parameter2->type = argument_type2;
5969 function_parameter_t *parameter1
5970 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5971 memset(parameter1, 0, sizeof(parameter1[0]));
5972 parameter1->type = argument_type1;
5973 parameter1->next = parameter2;
5975 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5976 type->function.return_type = return_type;
5977 type->function.parameters = parameter1;
5979 type_t *result = typehash_insert(type);
5980 if (result != type) {
5988 * Creates a return_type (func)(argument_type) function type if not
5991 * @param return_type the return type
5992 * @param argument_type the argument type
5994 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5996 function_parameter_t *parameter
5997 = obstack_alloc(type_obst, sizeof(parameter[0]));
5998 memset(parameter, 0, sizeof(parameter[0]));
5999 parameter->type = argument_type;
6001 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
6002 type->function.return_type = return_type;
6003 type->function.parameters = parameter;
6005 type_t *result = typehash_insert(type);
6006 if (result != type) {
6013 static type_t *make_function_0_type(type_t *return_type)
6015 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
6016 type->function.return_type = return_type;
6017 type->function.parameters = NULL;
6019 type_t *result = typehash_insert(type);
6020 if (result != type) {
6028 * Creates a function type for some function like builtins.
6030 * @param symbol the symbol describing the builtin
6032 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6034 switch(symbol->ID) {
6035 case T___builtin_alloca:
6036 return make_function_1_type(type_void_ptr, type_size_t);
6037 case T___builtin_huge_val:
6038 return make_function_0_type(type_double);
6039 case T___builtin_nan:
6040 return make_function_1_type(type_double, type_char_ptr);
6041 case T___builtin_nanf:
6042 return make_function_1_type(type_float, type_char_ptr);
6043 case T___builtin_nand:
6044 return make_function_1_type(type_long_double, type_char_ptr);
6045 case T___builtin_va_end:
6046 return make_function_1_type(type_void, type_valist);
6047 case T___builtin_expect:
6048 return make_function_2_type(type_long, type_long, type_long);
6050 internal_errorf(HERE, "not implemented builtin symbol found");
6055 * Performs automatic type cast as described in § 6.3.2.1.
6057 * @param orig_type the original type
6059 static type_t *automatic_type_conversion(type_t *orig_type)
6061 type_t *type = skip_typeref(orig_type);
6062 if (is_type_array(type)) {
6063 array_type_t *array_type = &type->array;
6064 type_t *element_type = array_type->element_type;
6065 unsigned qualifiers = array_type->base.qualifiers;
6067 return make_pointer_type(element_type, qualifiers);
6070 if (is_type_function(type)) {
6071 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6078 * reverts the automatic casts of array to pointer types and function
6079 * to function-pointer types as defined § 6.3.2.1
6081 type_t *revert_automatic_type_conversion(const expression_t *expression)
6083 switch (expression->kind) {
6084 case EXPR_REFERENCE: return expression->reference.declaration->type;
6087 return get_qualified_type(expression->select.compound_entry->type,
6088 expression->base.type->base.qualifiers);
6090 case EXPR_UNARY_DEREFERENCE: {
6091 const expression_t *const value = expression->unary.value;
6092 type_t *const type = skip_typeref(value->base.type);
6093 assert(is_type_pointer(type));
6094 return type->pointer.points_to;
6097 case EXPR_BUILTIN_SYMBOL:
6098 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6100 case EXPR_ARRAY_ACCESS: {
6101 const expression_t *array_ref = expression->array_access.array_ref;
6102 type_t *type_left = skip_typeref(array_ref->base.type);
6103 if (!is_type_valid(type_left))
6105 assert(is_type_pointer(type_left));
6106 return type_left->pointer.points_to;
6109 case EXPR_STRING_LITERAL: {
6110 size_t size = expression->string.value.size;
6111 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6114 case EXPR_WIDE_STRING_LITERAL: {
6115 size_t size = expression->wide_string.value.size;
6116 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6119 case EXPR_COMPOUND_LITERAL:
6120 return expression->compound_literal.type;
6125 return expression->base.type;
6128 static expression_t *parse_reference(void)
6130 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6132 reference_expression_t *ref = &expression->reference;
6133 symbol_t *const symbol = token.v.symbol;
6135 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6137 if (declaration == NULL) {
6138 if (!strict_mode && look_ahead(1)->type == '(') {
6139 /* an implicitly declared function */
6140 if (warning.implicit_function_declaration) {
6141 warningf(HERE, "implicit declaration of function '%Y'",
6145 declaration = create_implicit_function(symbol, HERE);
6147 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6148 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6152 type_t *orig_type = declaration->type;
6154 /* we always do the auto-type conversions; the & and sizeof parser contains
6155 * code to revert this! */
6156 type_t *type = automatic_type_conversion(orig_type);
6158 ref->declaration = declaration;
6159 ref->base.type = type;
6161 /* this declaration is used */
6162 declaration->used = true;
6164 if (declaration->parent_scope != global_scope &&
6165 declaration->parent_scope->depth < current_function->scope.depth &&
6166 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6167 /* access of a variable from an outer function */
6168 declaration->address_taken = true;
6169 ref->is_outer_ref = true;
6170 current_function->need_closure = true;
6173 /* check for deprecated functions */
6174 if (warning.deprecated_declarations &&
6175 declaration->modifiers & DM_DEPRECATED) {
6176 char const *const prefix = is_type_function(declaration->type) ?
6177 "function" : "variable";
6179 if (declaration->deprecated_string != NULL) {
6180 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6181 prefix, declaration->symbol, &declaration->source_position,
6182 declaration->deprecated_string);
6184 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6185 declaration->symbol, &declaration->source_position);
6188 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6189 current_init_decl = NULL;
6190 warningf(HERE, "variable '%#T' is initialized by itself",
6191 declaration->type, declaration->symbol);
6198 static bool semantic_cast(expression_t *cast)
6200 expression_t *expression = cast->unary.value;
6201 type_t *orig_dest_type = cast->base.type;
6202 type_t *orig_type_right = expression->base.type;
6203 type_t const *dst_type = skip_typeref(orig_dest_type);
6204 type_t const *src_type = skip_typeref(orig_type_right);
6205 source_position_t const *pos = &cast->base.source_position;
6207 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6208 if (dst_type == type_void)
6211 /* only integer and pointer can be casted to pointer */
6212 if (is_type_pointer(dst_type) &&
6213 !is_type_pointer(src_type) &&
6214 !is_type_integer(src_type) &&
6215 is_type_valid(src_type)) {
6216 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6220 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6221 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6225 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6226 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6230 if (warning.cast_qual &&
6231 is_type_pointer(src_type) &&
6232 is_type_pointer(dst_type)) {
6233 type_t *src = skip_typeref(src_type->pointer.points_to);
6234 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6235 unsigned missing_qualifiers =
6236 src->base.qualifiers & ~dst->base.qualifiers;
6237 if (missing_qualifiers != 0) {
6239 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6240 missing_qualifiers, orig_type_right);
6246 static expression_t *parse_compound_literal(type_t *type)
6248 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6250 parse_initializer_env_t env;
6252 env.declaration = NULL;
6253 env.must_be_constant = false;
6254 initializer_t *initializer = parse_initializer(&env);
6257 expression->compound_literal.initializer = initializer;
6258 expression->compound_literal.type = type;
6259 expression->base.type = automatic_type_conversion(type);
6265 * Parse a cast expression.
6267 static expression_t *parse_cast(void)
6269 add_anchor_token(')');
6271 source_position_t source_position = token.source_position;
6273 type_t *type = parse_typename();
6275 rem_anchor_token(')');
6278 if (token.type == '{') {
6279 return parse_compound_literal(type);
6282 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6283 cast->base.source_position = source_position;
6285 expression_t *value = parse_sub_expression(20);
6286 cast->base.type = type;
6287 cast->unary.value = value;
6289 if (! semantic_cast(cast)) {
6290 /* TODO: record the error in the AST. else it is impossible to detect it */
6295 return create_invalid_expression();
6299 * Parse a statement expression.
6301 static expression_t *parse_statement_expression(void)
6303 add_anchor_token(')');
6305 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6307 statement_t *statement = parse_compound_statement(true);
6308 expression->statement.statement = statement;
6309 expression->base.source_position = statement->base.source_position;
6311 /* find last statement and use its type */
6312 type_t *type = type_void;
6313 const statement_t *stmt = statement->compound.statements;
6315 while (stmt->base.next != NULL)
6316 stmt = stmt->base.next;
6318 if (stmt->kind == STATEMENT_EXPRESSION) {
6319 type = stmt->expression.expression->base.type;
6322 warningf(&expression->base.source_position, "empty statement expression ({})");
6324 expression->base.type = type;
6326 rem_anchor_token(')');
6334 * Parse a parenthesized expression.
6336 static expression_t *parse_parenthesized_expression(void)
6340 switch(token.type) {
6342 /* gcc extension: a statement expression */
6343 return parse_statement_expression();
6347 return parse_cast();
6349 if (is_typedef_symbol(token.v.symbol)) {
6350 return parse_cast();
6354 add_anchor_token(')');
6355 expression_t *result = parse_expression();
6356 rem_anchor_token(')');
6363 static expression_t *parse_function_keyword(void)
6368 if (current_function == NULL) {
6369 errorf(HERE, "'__func__' used outside of a function");
6372 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6373 expression->base.type = type_char_ptr;
6374 expression->funcname.kind = FUNCNAME_FUNCTION;
6379 static expression_t *parse_pretty_function_keyword(void)
6381 eat(T___PRETTY_FUNCTION__);
6383 if (current_function == NULL) {
6384 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6387 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6388 expression->base.type = type_char_ptr;
6389 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6394 static expression_t *parse_funcsig_keyword(void)
6398 if (current_function == NULL) {
6399 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6402 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6403 expression->base.type = type_char_ptr;
6404 expression->funcname.kind = FUNCNAME_FUNCSIG;
6409 static expression_t *parse_funcdname_keyword(void)
6411 eat(T___FUNCDNAME__);
6413 if (current_function == NULL) {
6414 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6417 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6418 expression->base.type = type_char_ptr;
6419 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6424 static designator_t *parse_designator(void)
6426 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6427 result->source_position = *HERE;
6429 if (token.type != T_IDENTIFIER) {
6430 parse_error_expected("while parsing member designator",
6431 T_IDENTIFIER, NULL);
6434 result->symbol = token.v.symbol;
6437 designator_t *last_designator = result;
6439 if (token.type == '.') {
6441 if (token.type != T_IDENTIFIER) {
6442 parse_error_expected("while parsing member designator",
6443 T_IDENTIFIER, NULL);
6446 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6447 designator->source_position = *HERE;
6448 designator->symbol = token.v.symbol;
6451 last_designator->next = designator;
6452 last_designator = designator;
6455 if (token.type == '[') {
6457 add_anchor_token(']');
6458 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6459 designator->source_position = *HERE;
6460 designator->array_index = parse_expression();
6461 rem_anchor_token(']');
6463 if (designator->array_index == NULL) {
6467 last_designator->next = designator;
6468 last_designator = designator;
6480 * Parse the __builtin_offsetof() expression.
6482 static expression_t *parse_offsetof(void)
6484 eat(T___builtin_offsetof);
6486 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6487 expression->base.type = type_size_t;
6490 add_anchor_token(',');
6491 type_t *type = parse_typename();
6492 rem_anchor_token(',');
6494 add_anchor_token(')');
6495 designator_t *designator = parse_designator();
6496 rem_anchor_token(')');
6499 expression->offsetofe.type = type;
6500 expression->offsetofe.designator = designator;
6503 memset(&path, 0, sizeof(path));
6504 path.top_type = type;
6505 path.path = NEW_ARR_F(type_path_entry_t, 0);
6507 descend_into_subtype(&path);
6509 if (!walk_designator(&path, designator, true)) {
6510 return create_invalid_expression();
6513 DEL_ARR_F(path.path);
6517 return create_invalid_expression();
6521 * Parses a _builtin_va_start() expression.
6523 static expression_t *parse_va_start(void)
6525 eat(T___builtin_va_start);
6527 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6530 add_anchor_token(',');
6531 expression->va_starte.ap = parse_assignment_expression();
6532 rem_anchor_token(',');
6534 expression_t *const expr = parse_assignment_expression();
6535 if (expr->kind == EXPR_REFERENCE) {
6536 declaration_t *const decl = expr->reference.declaration;
6537 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6538 errorf(&expr->base.source_position,
6539 "second argument of 'va_start' must be last parameter of the current function");
6541 expression->va_starte.parameter = decl;
6547 return create_invalid_expression();
6551 * Parses a _builtin_va_arg() expression.
6553 static expression_t *parse_va_arg(void)
6555 eat(T___builtin_va_arg);
6557 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6560 expression->va_arge.ap = parse_assignment_expression();
6562 expression->base.type = parse_typename();
6567 return create_invalid_expression();
6570 static expression_t *parse_builtin_symbol(void)
6572 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6574 symbol_t *symbol = token.v.symbol;
6576 expression->builtin_symbol.symbol = symbol;
6579 type_t *type = get_builtin_symbol_type(symbol);
6580 type = automatic_type_conversion(type);
6582 expression->base.type = type;
6587 * Parses a __builtin_constant() expression.
6589 static expression_t *parse_builtin_constant(void)
6591 eat(T___builtin_constant_p);
6593 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6596 add_anchor_token(')');
6597 expression->builtin_constant.value = parse_assignment_expression();
6598 rem_anchor_token(')');
6600 expression->base.type = type_int;
6604 return create_invalid_expression();
6608 * Parses a __builtin_prefetch() expression.
6610 static expression_t *parse_builtin_prefetch(void)
6612 eat(T___builtin_prefetch);
6614 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6617 add_anchor_token(')');
6618 expression->builtin_prefetch.adr = parse_assignment_expression();
6619 if (token.type == ',') {
6621 expression->builtin_prefetch.rw = parse_assignment_expression();
6623 if (token.type == ',') {
6625 expression->builtin_prefetch.locality = parse_assignment_expression();
6627 rem_anchor_token(')');
6629 expression->base.type = type_void;
6633 return create_invalid_expression();
6637 * Parses a __builtin_is_*() compare expression.
6639 static expression_t *parse_compare_builtin(void)
6641 expression_t *expression;
6643 switch(token.type) {
6644 case T___builtin_isgreater:
6645 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6647 case T___builtin_isgreaterequal:
6648 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6650 case T___builtin_isless:
6651 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6653 case T___builtin_islessequal:
6654 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6656 case T___builtin_islessgreater:
6657 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6659 case T___builtin_isunordered:
6660 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6663 internal_errorf(HERE, "invalid compare builtin found");
6666 expression->base.source_position = *HERE;
6670 expression->binary.left = parse_assignment_expression();
6672 expression->binary.right = parse_assignment_expression();
6675 type_t *const orig_type_left = expression->binary.left->base.type;
6676 type_t *const orig_type_right = expression->binary.right->base.type;
6678 type_t *const type_left = skip_typeref(orig_type_left);
6679 type_t *const type_right = skip_typeref(orig_type_right);
6680 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6681 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6682 type_error_incompatible("invalid operands in comparison",
6683 &expression->base.source_position, orig_type_left, orig_type_right);
6686 semantic_comparison(&expression->binary);
6691 return create_invalid_expression();
6696 * Parses a __builtin_expect() expression.
6698 static expression_t *parse_builtin_expect(void)
6700 eat(T___builtin_expect);
6702 expression_t *expression
6703 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6706 expression->binary.left = parse_assignment_expression();
6708 expression->binary.right = parse_constant_expression();
6711 expression->base.type = expression->binary.left->base.type;
6715 return create_invalid_expression();
6720 * Parses a MS assume() expression.
6722 static expression_t *parse_assume(void)
6726 expression_t *expression
6727 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6730 add_anchor_token(')');
6731 expression->unary.value = parse_assignment_expression();
6732 rem_anchor_token(')');
6735 expression->base.type = type_void;
6738 return create_invalid_expression();
6742 * Return the declaration for a given label symbol or create a new one.
6744 * @param symbol the symbol of the label
6746 static declaration_t *get_label(symbol_t *symbol)
6748 declaration_t *candidate;
6749 assert(current_function != NULL);
6751 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6752 /* if we found a local label, we already created the declaration */
6753 if (candidate != NULL) {
6754 if (candidate->parent_scope != scope) {
6755 assert(candidate->parent_scope->depth < scope->depth);
6756 current_function->goto_to_outer = true;
6761 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6762 /* if we found a label in the same function, then we already created the
6764 if (candidate != NULL
6765 && candidate->parent_scope == ¤t_function->scope) {
6769 /* otherwise we need to create a new one */
6770 declaration_t *const declaration = allocate_declaration_zero();
6771 declaration->namespc = NAMESPACE_LABEL;
6772 declaration->symbol = symbol;
6774 label_push(declaration);
6780 * Parses a GNU && label address expression.
6782 static expression_t *parse_label_address(void)
6784 source_position_t source_position = token.source_position;
6786 if (token.type != T_IDENTIFIER) {
6787 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6790 symbol_t *symbol = token.v.symbol;
6793 declaration_t *label = get_label(symbol);
6796 label->address_taken = true;
6798 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6799 expression->base.source_position = source_position;
6801 /* label address is threaten as a void pointer */
6802 expression->base.type = type_void_ptr;
6803 expression->label_address.declaration = label;
6806 return create_invalid_expression();
6810 * Parse a microsoft __noop expression.
6812 static expression_t *parse_noop_expression(void)
6814 source_position_t source_position = *HERE;
6817 if (token.type == '(') {
6818 /* parse arguments */
6820 add_anchor_token(')');
6821 add_anchor_token(',');
6823 if (token.type != ')') {
6825 (void)parse_assignment_expression();
6826 if (token.type != ',')
6832 rem_anchor_token(',');
6833 rem_anchor_token(')');
6836 /* the result is a (int)0 */
6837 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6838 cnst->base.source_position = source_position;
6839 cnst->base.type = type_int;
6840 cnst->conste.v.int_value = 0;
6841 cnst->conste.is_ms_noop = true;
6846 return create_invalid_expression();
6850 * Parses a primary expression.
6852 static expression_t *parse_primary_expression(void)
6854 switch (token.type) {
6855 case T_INTEGER: return parse_int_const();
6856 case T_CHARACTER_CONSTANT: return parse_character_constant();
6857 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6858 case T_FLOATINGPOINT: return parse_float_const();
6859 case T_STRING_LITERAL:
6860 case T_WIDE_STRING_LITERAL: return parse_string_const();
6861 case T_IDENTIFIER: return parse_reference();
6862 case T___FUNCTION__:
6863 case T___func__: return parse_function_keyword();
6864 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6865 case T___FUNCSIG__: return parse_funcsig_keyword();
6866 case T___FUNCDNAME__: return parse_funcdname_keyword();
6867 case T___builtin_offsetof: return parse_offsetof();
6868 case T___builtin_va_start: return parse_va_start();
6869 case T___builtin_va_arg: return parse_va_arg();
6870 case T___builtin_expect:
6871 case T___builtin_alloca:
6872 case T___builtin_nan:
6873 case T___builtin_nand:
6874 case T___builtin_nanf:
6875 case T___builtin_huge_val:
6876 case T___builtin_va_end: return parse_builtin_symbol();
6877 case T___builtin_isgreater:
6878 case T___builtin_isgreaterequal:
6879 case T___builtin_isless:
6880 case T___builtin_islessequal:
6881 case T___builtin_islessgreater:
6882 case T___builtin_isunordered: return parse_compare_builtin();
6883 case T___builtin_constant_p: return parse_builtin_constant();
6884 case T___builtin_prefetch: return parse_builtin_prefetch();
6885 case T__assume: return parse_assume();
6888 return parse_label_address();
6891 case '(': return parse_parenthesized_expression();
6892 case T___noop: return parse_noop_expression();
6895 errorf(HERE, "unexpected token %K, expected an expression", &token);
6896 return create_invalid_expression();
6900 * Check if the expression has the character type and issue a warning then.
6902 static void check_for_char_index_type(const expression_t *expression)
6904 type_t *const type = expression->base.type;
6905 const type_t *const base_type = skip_typeref(type);
6907 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6908 warning.char_subscripts) {
6909 warningf(&expression->base.source_position,
6910 "array subscript has type '%T'", type);
6914 static expression_t *parse_array_expression(unsigned precedence,
6920 add_anchor_token(']');
6922 expression_t *inside = parse_expression();
6924 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6926 array_access_expression_t *array_access = &expression->array_access;
6928 type_t *const orig_type_left = left->base.type;
6929 type_t *const orig_type_inside = inside->base.type;
6931 type_t *const type_left = skip_typeref(orig_type_left);
6932 type_t *const type_inside = skip_typeref(orig_type_inside);
6934 type_t *return_type;
6935 if (is_type_pointer(type_left)) {
6936 return_type = type_left->pointer.points_to;
6937 array_access->array_ref = left;
6938 array_access->index = inside;
6939 check_for_char_index_type(inside);
6940 } else if (is_type_pointer(type_inside)) {
6941 return_type = type_inside->pointer.points_to;
6942 array_access->array_ref = inside;
6943 array_access->index = left;
6944 array_access->flipped = true;
6945 check_for_char_index_type(left);
6947 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6949 "array access on object with non-pointer types '%T', '%T'",
6950 orig_type_left, orig_type_inside);
6952 return_type = type_error_type;
6953 array_access->array_ref = left;
6954 array_access->index = inside;
6957 expression->base.type = automatic_type_conversion(return_type);
6959 rem_anchor_token(']');
6960 if (token.type == ']') {
6963 parse_error_expected("Problem while parsing array access", ']', NULL);
6968 static expression_t *parse_typeprop(expression_kind_t const kind,
6969 source_position_t const pos,
6970 unsigned const precedence)
6972 expression_t *tp_expression = allocate_expression_zero(kind);
6973 tp_expression->base.type = type_size_t;
6974 tp_expression->base.source_position = pos;
6976 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6978 /* we only refer to a type property, mark this case */
6979 bool old = in_type_prop;
6980 in_type_prop = true;
6981 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6983 add_anchor_token(')');
6984 type_t* const orig_type = parse_typename();
6985 tp_expression->typeprop.type = orig_type;
6987 type_t const* const type = skip_typeref(orig_type);
6988 char const* const wrong_type =
6989 is_type_incomplete(type) ? "incomplete" :
6990 type->kind == TYPE_FUNCTION ? "function designator" :
6991 type->kind == TYPE_BITFIELD ? "bitfield" :
6993 if (wrong_type != NULL) {
6994 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6995 what, wrong_type, type);
6998 rem_anchor_token(')');
7001 expression_t *expression = parse_sub_expression(precedence);
7003 type_t* const orig_type = revert_automatic_type_conversion(expression);
7004 expression->base.type = orig_type;
7006 type_t const* const type = skip_typeref(orig_type);
7007 char const* const wrong_type =
7008 is_type_incomplete(type) ? "incomplete" :
7009 type->kind == TYPE_FUNCTION ? "function designator" :
7010 type->kind == TYPE_BITFIELD ? "bitfield" :
7012 if (wrong_type != NULL) {
7013 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
7016 tp_expression->typeprop.type = expression->base.type;
7017 tp_expression->typeprop.tp_expression = expression;
7022 return tp_expression;
7025 static expression_t *parse_sizeof(unsigned precedence)
7027 source_position_t pos = *HERE;
7029 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
7032 static expression_t *parse_alignof(unsigned precedence)
7034 source_position_t pos = *HERE;
7036 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
7039 static expression_t *parse_select_expression(unsigned precedence,
7040 expression_t *compound)
7043 assert(token.type == '.' || token.type == T_MINUSGREATER);
7045 bool is_pointer = (token.type == T_MINUSGREATER);
7048 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7049 select->select.compound = compound;
7051 if (token.type != T_IDENTIFIER) {
7052 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7055 symbol_t *symbol = token.v.symbol;
7058 type_t *const orig_type = compound->base.type;
7059 type_t *const type = skip_typeref(orig_type);
7062 bool saw_error = false;
7063 if (is_type_pointer(type)) {
7066 "request for member '%Y' in something not a struct or union, but '%T'",
7070 type_left = skip_typeref(type->pointer.points_to);
7072 if (is_pointer && is_type_valid(type)) {
7073 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7079 declaration_t *entry;
7080 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7081 type_left->kind == TYPE_COMPOUND_UNION) {
7082 declaration_t *const declaration = type_left->compound.declaration;
7084 if (!declaration->init.complete) {
7085 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7087 goto create_error_entry;
7090 entry = find_compound_entry(declaration, symbol);
7091 if (entry == NULL) {
7092 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7093 goto create_error_entry;
7096 if (is_type_valid(type_left) && !saw_error) {
7098 "request for member '%Y' in something not a struct or union, but '%T'",
7102 entry = allocate_declaration_zero();
7103 entry->symbol = symbol;
7106 select->select.compound_entry = entry;
7108 type_t *const res_type =
7109 get_qualified_type(entry->type, type_left->base.qualifiers);
7111 /* we always do the auto-type conversions; the & and sizeof parser contains
7112 * code to revert this! */
7113 select->base.type = automatic_type_conversion(res_type);
7115 type_t *skipped = skip_typeref(res_type);
7116 if (skipped->kind == TYPE_BITFIELD) {
7117 select->base.type = skipped->bitfield.base_type;
7123 static void check_call_argument(const function_parameter_t *parameter,
7124 call_argument_t *argument, unsigned pos)
7126 type_t *expected_type = parameter->type;
7127 type_t *expected_type_skip = skip_typeref(expected_type);
7128 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7129 expression_t *arg_expr = argument->expression;
7130 type_t *arg_type = skip_typeref(arg_expr->base.type);
7132 /* handle transparent union gnu extension */
7133 if (is_type_union(expected_type_skip)
7134 && (expected_type_skip->base.modifiers
7135 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7136 declaration_t *union_decl = expected_type_skip->compound.declaration;
7138 declaration_t *declaration = union_decl->scope.declarations;
7139 type_t *best_type = NULL;
7140 for ( ; declaration != NULL; declaration = declaration->next) {
7141 type_t *decl_type = declaration->type;
7142 error = semantic_assign(decl_type, arg_expr);
7143 if (error == ASSIGN_ERROR_INCOMPATIBLE
7144 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7147 if (error == ASSIGN_SUCCESS) {
7148 best_type = decl_type;
7149 } else if (best_type == NULL) {
7150 best_type = decl_type;
7154 if (best_type != NULL) {
7155 expected_type = best_type;
7159 error = semantic_assign(expected_type, arg_expr);
7160 argument->expression = create_implicit_cast(argument->expression,
7163 if (error != ASSIGN_SUCCESS) {
7164 /* report exact scope in error messages (like "in argument 3") */
7166 snprintf(buf, sizeof(buf), "call argument %u", pos);
7167 report_assign_error(error, expected_type, arg_expr, buf,
7168 &arg_expr->base.source_position);
7169 } else if (warning.traditional || warning.conversion) {
7170 type_t *const promoted_type = get_default_promoted_type(arg_type);
7171 if (!types_compatible(expected_type_skip, promoted_type) &&
7172 !types_compatible(expected_type_skip, type_void_ptr) &&
7173 !types_compatible(type_void_ptr, promoted_type)) {
7174 /* Deliberately show the skipped types in this warning */
7175 warningf(&arg_expr->base.source_position,
7176 "passing call argument %u as '%T' rather than '%T' due to prototype",
7177 pos, expected_type_skip, promoted_type);
7183 * Parse a call expression, ie. expression '( ... )'.
7185 * @param expression the function address
7187 static expression_t *parse_call_expression(unsigned precedence,
7188 expression_t *expression)
7191 expression_t *result = allocate_expression_zero(EXPR_CALL);
7192 result->base.source_position = expression->base.source_position;
7194 call_expression_t *call = &result->call;
7195 call->function = expression;
7197 type_t *const orig_type = expression->base.type;
7198 type_t *const type = skip_typeref(orig_type);
7200 function_type_t *function_type = NULL;
7201 if (is_type_pointer(type)) {
7202 type_t *const to_type = skip_typeref(type->pointer.points_to);
7204 if (is_type_function(to_type)) {
7205 function_type = &to_type->function;
7206 call->base.type = function_type->return_type;
7210 if (function_type == NULL && is_type_valid(type)) {
7211 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7214 /* parse arguments */
7216 add_anchor_token(')');
7217 add_anchor_token(',');
7219 if (token.type != ')') {
7220 call_argument_t *last_argument = NULL;
7223 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7225 argument->expression = parse_assignment_expression();
7226 if (last_argument == NULL) {
7227 call->arguments = argument;
7229 last_argument->next = argument;
7231 last_argument = argument;
7233 if (token.type != ',')
7238 rem_anchor_token(',');
7239 rem_anchor_token(')');
7242 if (function_type == NULL)
7245 function_parameter_t *parameter = function_type->parameters;
7246 call_argument_t *argument = call->arguments;
7247 if (!function_type->unspecified_parameters) {
7248 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7249 parameter = parameter->next, argument = argument->next) {
7250 check_call_argument(parameter, argument, ++pos);
7253 if (parameter != NULL) {
7254 errorf(HERE, "too few arguments to function '%E'", expression);
7255 } else if (argument != NULL && !function_type->variadic) {
7256 errorf(HERE, "too many arguments to function '%E'", expression);
7260 /* do default promotion */
7261 for( ; argument != NULL; argument = argument->next) {
7262 type_t *type = argument->expression->base.type;
7264 type = get_default_promoted_type(type);
7266 argument->expression
7267 = create_implicit_cast(argument->expression, type);
7270 check_format(&result->call);
7272 if (warning.aggregate_return &&
7273 is_type_compound(skip_typeref(function_type->return_type))) {
7274 warningf(&result->base.source_position,
7275 "function call has aggregate value");
7282 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7284 static bool same_compound_type(const type_t *type1, const type_t *type2)
7287 is_type_compound(type1) &&
7288 type1->kind == type2->kind &&
7289 type1->compound.declaration == type2->compound.declaration;
7293 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7295 * @param expression the conditional expression
7297 static expression_t *parse_conditional_expression(unsigned precedence,
7298 expression_t *expression)
7300 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7302 conditional_expression_t *conditional = &result->conditional;
7303 conditional->base.source_position = *HERE;
7304 conditional->condition = expression;
7307 add_anchor_token(':');
7310 type_t *const condition_type_orig = expression->base.type;
7311 type_t *const condition_type = skip_typeref(condition_type_orig);
7312 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7313 type_error("expected a scalar type in conditional condition",
7314 &expression->base.source_position, condition_type_orig);
7317 expression_t *true_expression = expression;
7318 bool gnu_cond = false;
7319 if (GNU_MODE && token.type == ':') {
7322 true_expression = parse_expression();
7323 rem_anchor_token(':');
7325 expression_t *false_expression = parse_sub_expression(precedence);
7327 type_t *const orig_true_type = true_expression->base.type;
7328 type_t *const orig_false_type = false_expression->base.type;
7329 type_t *const true_type = skip_typeref(orig_true_type);
7330 type_t *const false_type = skip_typeref(orig_false_type);
7333 type_t *result_type;
7334 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7335 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7336 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7337 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7338 warningf(&conditional->base.source_position,
7339 "ISO C forbids conditional expression with only one void side");
7341 result_type = type_void;
7342 } else if (is_type_arithmetic(true_type)
7343 && is_type_arithmetic(false_type)) {
7344 result_type = semantic_arithmetic(true_type, false_type);
7346 true_expression = create_implicit_cast(true_expression, result_type);
7347 false_expression = create_implicit_cast(false_expression, result_type);
7349 conditional->true_expression = true_expression;
7350 conditional->false_expression = false_expression;
7351 conditional->base.type = result_type;
7352 } else if (same_compound_type(true_type, false_type)) {
7353 /* just take 1 of the 2 types */
7354 result_type = true_type;
7355 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7356 type_t *pointer_type;
7358 expression_t *other_expression;
7359 if (is_type_pointer(true_type) &&
7360 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7361 pointer_type = true_type;
7362 other_type = false_type;
7363 other_expression = false_expression;
7365 pointer_type = false_type;
7366 other_type = true_type;
7367 other_expression = true_expression;
7370 if (is_null_pointer_constant(other_expression)) {
7371 result_type = pointer_type;
7372 } else if (is_type_pointer(other_type)) {
7373 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7374 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7377 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7378 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7380 } else if (types_compatible(get_unqualified_type(to1),
7381 get_unqualified_type(to2))) {
7384 warningf(&conditional->base.source_position,
7385 "pointer types '%T' and '%T' in conditional expression are incompatible",
7386 true_type, false_type);
7390 type_t *const type =
7391 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7392 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7393 } else if (is_type_integer(other_type)) {
7394 warningf(&conditional->base.source_position,
7395 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7396 result_type = pointer_type;
7398 type_error_incompatible("while parsing conditional",
7399 &expression->base.source_position, true_type, false_type);
7400 result_type = type_error_type;
7403 /* TODO: one pointer to void*, other some pointer */
7405 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7406 type_error_incompatible("while parsing conditional",
7407 &conditional->base.source_position, true_type,
7410 result_type = type_error_type;
7413 conditional->true_expression
7414 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7415 conditional->false_expression
7416 = create_implicit_cast(false_expression, result_type);
7417 conditional->base.type = result_type;
7420 return create_invalid_expression();
7424 * Parse an extension expression.
7426 static expression_t *parse_extension(unsigned precedence)
7428 eat(T___extension__);
7430 bool old_gcc_extension = in_gcc_extension;
7431 in_gcc_extension = true;
7432 expression_t *expression = parse_sub_expression(precedence);
7433 in_gcc_extension = old_gcc_extension;
7438 * Parse a __builtin_classify_type() expression.
7440 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7442 eat(T___builtin_classify_type);
7444 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7445 result->base.type = type_int;
7448 add_anchor_token(')');
7449 expression_t *expression = parse_sub_expression(precedence);
7450 rem_anchor_token(')');
7452 result->classify_type.type_expression = expression;
7456 return create_invalid_expression();
7459 static bool check_pointer_arithmetic(const source_position_t *source_position,
7460 type_t *pointer_type,
7461 type_t *orig_pointer_type)
7463 type_t *points_to = pointer_type->pointer.points_to;
7464 points_to = skip_typeref(points_to);
7466 if (is_type_incomplete(points_to)) {
7467 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7468 errorf(source_position,
7469 "arithmetic with pointer to incomplete type '%T' not allowed",
7472 } else if (warning.pointer_arith) {
7473 warningf(source_position,
7474 "pointer of type '%T' used in arithmetic",
7477 } else if (is_type_function(points_to)) {
7479 errorf(source_position,
7480 "arithmetic with pointer to function type '%T' not allowed",
7483 } else if (warning.pointer_arith) {
7484 warningf(source_position,
7485 "pointer to a function '%T' used in arithmetic",
7492 static bool is_lvalue(const expression_t *expression)
7494 switch (expression->kind) {
7495 case EXPR_REFERENCE:
7496 case EXPR_ARRAY_ACCESS:
7498 case EXPR_UNARY_DEREFERENCE:
7506 static void semantic_incdec(unary_expression_t *expression)
7508 type_t *const orig_type = expression->value->base.type;
7509 type_t *const type = skip_typeref(orig_type);
7510 if (is_type_pointer(type)) {
7511 if (!check_pointer_arithmetic(&expression->base.source_position,
7515 } else if (!is_type_real(type) && is_type_valid(type)) {
7516 /* TODO: improve error message */
7517 errorf(&expression->base.source_position,
7518 "operation needs an arithmetic or pointer type");
7521 if (!is_lvalue(expression->value)) {
7522 /* TODO: improve error message */
7523 errorf(&expression->base.source_position, "lvalue required as operand");
7525 expression->base.type = orig_type;
7528 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7530 type_t *const orig_type = expression->value->base.type;
7531 type_t *const type = skip_typeref(orig_type);
7532 if (!is_type_arithmetic(type)) {
7533 if (is_type_valid(type)) {
7534 /* TODO: improve error message */
7535 errorf(&expression->base.source_position,
7536 "operation needs an arithmetic type");
7541 expression->base.type = orig_type;
7544 static void semantic_unexpr_plus(unary_expression_t *expression)
7546 semantic_unexpr_arithmetic(expression);
7547 if (warning.traditional)
7548 warningf(&expression->base.source_position,
7549 "traditional C rejects the unary plus operator");
7552 static expression_t const *get_reference_address(expression_t const *expr)
7554 bool regular_take_address = true;
7556 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7557 expr = expr->unary.value;
7559 regular_take_address = false;
7562 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7565 expr = expr->unary.value;
7568 if (expr->kind != EXPR_REFERENCE)
7571 if (!regular_take_address &&
7572 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7579 static void warn_function_address_as_bool(expression_t const* expr)
7581 if (!warning.address)
7584 expr = get_reference_address(expr);
7586 warningf(&expr->base.source_position,
7587 "the address of '%Y' will always evaluate as 'true'",
7588 expr->reference.declaration->symbol);
7592 static void semantic_not(unary_expression_t *expression)
7594 type_t *const orig_type = expression->value->base.type;
7595 type_t *const type = skip_typeref(orig_type);
7596 if (!is_type_scalar(type) && is_type_valid(type)) {
7597 errorf(&expression->base.source_position,
7598 "operand of ! must be of scalar type");
7601 warn_function_address_as_bool(expression->value);
7603 expression->base.type = type_int;
7606 static void semantic_unexpr_integer(unary_expression_t *expression)
7608 type_t *const orig_type = expression->value->base.type;
7609 type_t *const type = skip_typeref(orig_type);
7610 if (!is_type_integer(type)) {
7611 if (is_type_valid(type)) {
7612 errorf(&expression->base.source_position,
7613 "operand of ~ must be of integer type");
7618 expression->base.type = orig_type;
7621 static void semantic_dereference(unary_expression_t *expression)
7623 type_t *const orig_type = expression->value->base.type;
7624 type_t *const type = skip_typeref(orig_type);
7625 if (!is_type_pointer(type)) {
7626 if (is_type_valid(type)) {
7627 errorf(&expression->base.source_position,
7628 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7633 type_t *result_type = type->pointer.points_to;
7634 result_type = automatic_type_conversion(result_type);
7635 expression->base.type = result_type;
7639 * Record that an address is taken (expression represents an lvalue).
7641 * @param expression the expression
7642 * @param may_be_register if true, the expression might be an register
7644 static void set_address_taken(expression_t *expression, bool may_be_register)
7646 if (expression->kind != EXPR_REFERENCE)
7649 declaration_t *const declaration = expression->reference.declaration;
7650 /* happens for parse errors */
7651 if (declaration == NULL)
7654 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7655 errorf(&expression->base.source_position,
7656 "address of register variable '%Y' requested",
7657 declaration->symbol);
7659 declaration->address_taken = 1;
7664 * Check the semantic of the address taken expression.
7666 static void semantic_take_addr(unary_expression_t *expression)
7668 expression_t *value = expression->value;
7669 value->base.type = revert_automatic_type_conversion(value);
7671 type_t *orig_type = value->base.type;
7672 if (!is_type_valid(orig_type))
7675 set_address_taken(value, false);
7677 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7680 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7681 static expression_t *parse_##unexpression_type(unsigned precedence) \
7683 expression_t *unary_expression \
7684 = allocate_expression_zero(unexpression_type); \
7685 unary_expression->base.source_position = *HERE; \
7687 unary_expression->unary.value = parse_sub_expression(precedence); \
7689 sfunc(&unary_expression->unary); \
7691 return unary_expression; \
7694 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7695 semantic_unexpr_arithmetic)
7696 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7697 semantic_unexpr_plus)
7698 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7700 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7701 semantic_dereference)
7702 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7704 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7705 semantic_unexpr_integer)
7706 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7708 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7711 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7713 static expression_t *parse_##unexpression_type(unsigned precedence, \
7714 expression_t *left) \
7716 (void) precedence; \
7718 expression_t *unary_expression \
7719 = allocate_expression_zero(unexpression_type); \
7720 unary_expression->base.source_position = *HERE; \
7722 unary_expression->unary.value = left; \
7724 sfunc(&unary_expression->unary); \
7726 return unary_expression; \
7729 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7730 EXPR_UNARY_POSTFIX_INCREMENT,
7732 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7733 EXPR_UNARY_POSTFIX_DECREMENT,
7736 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7738 /* TODO: handle complex + imaginary types */
7740 type_left = get_unqualified_type(type_left);
7741 type_right = get_unqualified_type(type_right);
7743 /* § 6.3.1.8 Usual arithmetic conversions */
7744 if (type_left == type_long_double || type_right == type_long_double) {
7745 return type_long_double;
7746 } else if (type_left == type_double || type_right == type_double) {
7748 } else if (type_left == type_float || type_right == type_float) {
7752 type_left = promote_integer(type_left);
7753 type_right = promote_integer(type_right);
7755 if (type_left == type_right)
7758 bool const signed_left = is_type_signed(type_left);
7759 bool const signed_right = is_type_signed(type_right);
7760 int const rank_left = get_rank(type_left);
7761 int const rank_right = get_rank(type_right);
7763 if (signed_left == signed_right)
7764 return rank_left >= rank_right ? type_left : type_right;
7773 u_rank = rank_right;
7774 u_type = type_right;
7776 s_rank = rank_right;
7777 s_type = type_right;
7782 if (u_rank >= s_rank)
7785 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7787 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7788 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7792 case ATOMIC_TYPE_INT: return type_unsigned_int;
7793 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7794 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7796 default: panic("invalid atomic type");
7801 * Check the semantic restrictions for a binary expression.
7803 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7805 expression_t *const left = expression->left;
7806 expression_t *const right = expression->right;
7807 type_t *const orig_type_left = left->base.type;
7808 type_t *const orig_type_right = right->base.type;
7809 type_t *const type_left = skip_typeref(orig_type_left);
7810 type_t *const type_right = skip_typeref(orig_type_right);
7812 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7813 /* TODO: improve error message */
7814 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7815 errorf(&expression->base.source_position,
7816 "operation needs arithmetic types");
7821 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7822 expression->left = create_implicit_cast(left, arithmetic_type);
7823 expression->right = create_implicit_cast(right, arithmetic_type);
7824 expression->base.type = arithmetic_type;
7827 static void warn_div_by_zero(binary_expression_t const *const expression)
7829 if (!warning.div_by_zero ||
7830 !is_type_integer(expression->base.type))
7833 expression_t const *const right = expression->right;
7834 /* The type of the right operand can be different for /= */
7835 if (is_type_integer(right->base.type) &&
7836 is_constant_expression(right) &&
7837 fold_constant(right) == 0) {
7838 warningf(&expression->base.source_position, "division by zero");
7843 * Check the semantic restrictions for a div/mod expression.
7845 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7846 semantic_binexpr_arithmetic(expression);
7847 warn_div_by_zero(expression);
7850 static void semantic_shift_op(binary_expression_t *expression)
7852 expression_t *const left = expression->left;
7853 expression_t *const right = expression->right;
7854 type_t *const orig_type_left = left->base.type;
7855 type_t *const orig_type_right = right->base.type;
7856 type_t * type_left = skip_typeref(orig_type_left);
7857 type_t * type_right = skip_typeref(orig_type_right);
7859 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7860 /* TODO: improve error message */
7861 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7862 errorf(&expression->base.source_position,
7863 "operands of shift operation must have integer types");
7868 type_left = promote_integer(type_left);
7869 type_right = promote_integer(type_right);
7871 expression->left = create_implicit_cast(left, type_left);
7872 expression->right = create_implicit_cast(right, type_right);
7873 expression->base.type = type_left;
7876 static void semantic_add(binary_expression_t *expression)
7878 expression_t *const left = expression->left;
7879 expression_t *const right = expression->right;
7880 type_t *const orig_type_left = left->base.type;
7881 type_t *const orig_type_right = right->base.type;
7882 type_t *const type_left = skip_typeref(orig_type_left);
7883 type_t *const type_right = skip_typeref(orig_type_right);
7886 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7887 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7888 expression->left = create_implicit_cast(left, arithmetic_type);
7889 expression->right = create_implicit_cast(right, arithmetic_type);
7890 expression->base.type = arithmetic_type;
7892 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7893 check_pointer_arithmetic(&expression->base.source_position,
7894 type_left, orig_type_left);
7895 expression->base.type = type_left;
7896 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7897 check_pointer_arithmetic(&expression->base.source_position,
7898 type_right, orig_type_right);
7899 expression->base.type = type_right;
7900 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7901 errorf(&expression->base.source_position,
7902 "invalid operands to binary + ('%T', '%T')",
7903 orig_type_left, orig_type_right);
7907 static void semantic_sub(binary_expression_t *expression)
7909 expression_t *const left = expression->left;
7910 expression_t *const right = expression->right;
7911 type_t *const orig_type_left = left->base.type;
7912 type_t *const orig_type_right = right->base.type;
7913 type_t *const type_left = skip_typeref(orig_type_left);
7914 type_t *const type_right = skip_typeref(orig_type_right);
7915 source_position_t const *const pos = &expression->base.source_position;
7918 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7919 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7920 expression->left = create_implicit_cast(left, arithmetic_type);
7921 expression->right = create_implicit_cast(right, arithmetic_type);
7922 expression->base.type = arithmetic_type;
7924 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7925 check_pointer_arithmetic(&expression->base.source_position,
7926 type_left, orig_type_left);
7927 expression->base.type = type_left;
7928 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7929 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7930 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7931 if (!types_compatible(unqual_left, unqual_right)) {
7933 "subtracting pointers to incompatible types '%T' and '%T'",
7934 orig_type_left, orig_type_right);
7935 } else if (!is_type_object(unqual_left)) {
7936 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7937 warningf(pos, "subtracting pointers to void");
7939 errorf(pos, "subtracting pointers to non-object types '%T'",
7943 expression->base.type = type_ptrdiff_t;
7944 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7945 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7946 orig_type_left, orig_type_right);
7950 static void warn_string_literal_address(expression_t const* expr)
7952 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7953 expr = expr->unary.value;
7954 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7956 expr = expr->unary.value;
7959 if (expr->kind == EXPR_STRING_LITERAL ||
7960 expr->kind == EXPR_WIDE_STRING_LITERAL) {
7961 warningf(&expr->base.source_position,
7962 "comparison with string literal results in unspecified behaviour");
7967 * Check the semantics of comparison expressions.
7969 * @param expression The expression to check.
7971 static void semantic_comparison(binary_expression_t *expression)
7973 expression_t *left = expression->left;
7974 expression_t *right = expression->right;
7976 if (warning.address) {
7977 warn_string_literal_address(left);
7978 warn_string_literal_address(right);
7980 expression_t const* const func_left = get_reference_address(left);
7981 if (func_left != NULL && is_null_pointer_constant(right)) {
7982 warningf(&expression->base.source_position,
7983 "the address of '%Y' will never be NULL",
7984 func_left->reference.declaration->symbol);
7987 expression_t const* const func_right = get_reference_address(right);
7988 if (func_right != NULL && is_null_pointer_constant(right)) {
7989 warningf(&expression->base.source_position,
7990 "the address of '%Y' will never be NULL",
7991 func_right->reference.declaration->symbol);
7995 type_t *orig_type_left = left->base.type;
7996 type_t *orig_type_right = right->base.type;
7997 type_t *type_left = skip_typeref(orig_type_left);
7998 type_t *type_right = skip_typeref(orig_type_right);
8000 /* TODO non-arithmetic types */
8001 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8002 /* test for signed vs unsigned compares */
8003 if (warning.sign_compare &&
8004 (expression->base.kind != EXPR_BINARY_EQUAL &&
8005 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8006 (is_type_signed(type_left) != is_type_signed(type_right))) {
8008 /* check if 1 of the operands is a constant, in this case we just
8009 * check wether we can safely represent the resulting constant in
8010 * the type of the other operand. */
8011 expression_t *const_expr = NULL;
8012 expression_t *other_expr = NULL;
8014 if (is_constant_expression(left)) {
8017 } else if (is_constant_expression(right)) {
8022 if (const_expr != NULL) {
8023 type_t *other_type = skip_typeref(other_expr->base.type);
8024 long val = fold_constant(const_expr);
8025 /* TODO: check if val can be represented by other_type */
8029 warningf(&expression->base.source_position,
8030 "comparison between signed and unsigned");
8032 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8033 expression->left = create_implicit_cast(left, arithmetic_type);
8034 expression->right = create_implicit_cast(right, arithmetic_type);
8035 expression->base.type = arithmetic_type;
8036 if (warning.float_equal &&
8037 (expression->base.kind == EXPR_BINARY_EQUAL ||
8038 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8039 is_type_float(arithmetic_type)) {
8040 warningf(&expression->base.source_position,
8041 "comparing floating point with == or != is unsafe");
8043 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8044 /* TODO check compatibility */
8045 } else if (is_type_pointer(type_left)) {
8046 expression->right = create_implicit_cast(right, type_left);
8047 } else if (is_type_pointer(type_right)) {
8048 expression->left = create_implicit_cast(left, type_right);
8049 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8050 type_error_incompatible("invalid operands in comparison",
8051 &expression->base.source_position,
8052 type_left, type_right);
8054 expression->base.type = type_int;
8058 * Checks if a compound type has constant fields.
8060 static bool has_const_fields(const compound_type_t *type)
8062 const scope_t *scope = &type->declaration->scope;
8063 const declaration_t *declaration = scope->declarations;
8065 for (; declaration != NULL; declaration = declaration->next) {
8066 if (declaration->namespc != NAMESPACE_NORMAL)
8069 const type_t *decl_type = skip_typeref(declaration->type);
8070 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8077 static bool is_valid_assignment_lhs(expression_t const* const left)
8079 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8080 type_t *const type_left = skip_typeref(orig_type_left);
8082 if (!is_lvalue(left)) {
8083 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8088 if (is_type_array(type_left)) {
8089 errorf(HERE, "cannot assign to arrays ('%E')", left);
8092 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8093 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8097 if (is_type_incomplete(type_left)) {
8098 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8099 left, orig_type_left);
8102 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8103 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8104 left, orig_type_left);
8111 static void semantic_arithmetic_assign(binary_expression_t *expression)
8113 expression_t *left = expression->left;
8114 expression_t *right = expression->right;
8115 type_t *orig_type_left = left->base.type;
8116 type_t *orig_type_right = right->base.type;
8118 if (!is_valid_assignment_lhs(left))
8121 type_t *type_left = skip_typeref(orig_type_left);
8122 type_t *type_right = skip_typeref(orig_type_right);
8124 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8125 /* TODO: improve error message */
8126 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8127 errorf(&expression->base.source_position,
8128 "operation needs arithmetic types");
8133 /* combined instructions are tricky. We can't create an implicit cast on
8134 * the left side, because we need the uncasted form for the store.
8135 * The ast2firm pass has to know that left_type must be right_type
8136 * for the arithmetic operation and create a cast by itself */
8137 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8138 expression->right = create_implicit_cast(right, arithmetic_type);
8139 expression->base.type = type_left;
8142 static void semantic_divmod_assign(binary_expression_t *expression)
8144 semantic_arithmetic_assign(expression);
8145 warn_div_by_zero(expression);
8148 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8150 expression_t *const left = expression->left;
8151 expression_t *const right = expression->right;
8152 type_t *const orig_type_left = left->base.type;
8153 type_t *const orig_type_right = right->base.type;
8154 type_t *const type_left = skip_typeref(orig_type_left);
8155 type_t *const type_right = skip_typeref(orig_type_right);
8157 if (!is_valid_assignment_lhs(left))
8160 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8161 /* combined instructions are tricky. We can't create an implicit cast on
8162 * the left side, because we need the uncasted form for the store.
8163 * The ast2firm pass has to know that left_type must be right_type
8164 * for the arithmetic operation and create a cast by itself */
8165 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8166 expression->right = create_implicit_cast(right, arithmetic_type);
8167 expression->base.type = type_left;
8168 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8169 check_pointer_arithmetic(&expression->base.source_position,
8170 type_left, orig_type_left);
8171 expression->base.type = type_left;
8172 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8173 errorf(&expression->base.source_position,
8174 "incompatible types '%T' and '%T' in assignment",
8175 orig_type_left, orig_type_right);
8180 * Check the semantic restrictions of a logical expression.
8182 static void semantic_logical_op(binary_expression_t *expression)
8184 expression_t *const left = expression->left;
8185 expression_t *const right = expression->right;
8186 type_t *const orig_type_left = left->base.type;
8187 type_t *const orig_type_right = right->base.type;
8188 type_t *const type_left = skip_typeref(orig_type_left);
8189 type_t *const type_right = skip_typeref(orig_type_right);
8191 warn_function_address_as_bool(left);
8192 warn_function_address_as_bool(right);
8194 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8195 /* TODO: improve error message */
8196 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8197 errorf(&expression->base.source_position,
8198 "operation needs scalar types");
8203 expression->base.type = type_int;
8207 * Check the semantic restrictions of a binary assign expression.
8209 static void semantic_binexpr_assign(binary_expression_t *expression)
8211 expression_t *left = expression->left;
8212 type_t *orig_type_left = left->base.type;
8214 if (!is_valid_assignment_lhs(left))
8217 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8218 report_assign_error(error, orig_type_left, expression->right,
8219 "assignment", &left->base.source_position);
8220 expression->right = create_implicit_cast(expression->right, orig_type_left);
8221 expression->base.type = orig_type_left;
8225 * Determine if the outermost operation (or parts thereof) of the given
8226 * expression has no effect in order to generate a warning about this fact.
8227 * Therefore in some cases this only examines some of the operands of the
8228 * expression (see comments in the function and examples below).
8230 * f() + 23; // warning, because + has no effect
8231 * x || f(); // no warning, because x controls execution of f()
8232 * x ? y : f(); // warning, because y has no effect
8233 * (void)x; // no warning to be able to suppress the warning
8234 * This function can NOT be used for an "expression has definitely no effect"-
8236 static bool expression_has_effect(const expression_t *const expr)
8238 switch (expr->kind) {
8239 case EXPR_UNKNOWN: break;
8240 case EXPR_INVALID: return true; /* do NOT warn */
8241 case EXPR_REFERENCE: return false;
8242 /* suppress the warning for microsoft __noop operations */
8243 case EXPR_CONST: return expr->conste.is_ms_noop;
8244 case EXPR_CHARACTER_CONSTANT: return false;
8245 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8246 case EXPR_STRING_LITERAL: return false;
8247 case EXPR_WIDE_STRING_LITERAL: return false;
8248 case EXPR_LABEL_ADDRESS: return false;
8251 const call_expression_t *const call = &expr->call;
8252 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8255 switch (call->function->builtin_symbol.symbol->ID) {
8256 case T___builtin_va_end: return true;
8257 default: return false;
8261 /* Generate the warning if either the left or right hand side of a
8262 * conditional expression has no effect */
8263 case EXPR_CONDITIONAL: {
8264 const conditional_expression_t *const cond = &expr->conditional;
8266 expression_has_effect(cond->true_expression) &&
8267 expression_has_effect(cond->false_expression);
8270 case EXPR_SELECT: return false;
8271 case EXPR_ARRAY_ACCESS: return false;
8272 case EXPR_SIZEOF: return false;
8273 case EXPR_CLASSIFY_TYPE: return false;
8274 case EXPR_ALIGNOF: return false;
8276 case EXPR_FUNCNAME: return false;
8277 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8278 case EXPR_BUILTIN_CONSTANT_P: return false;
8279 case EXPR_BUILTIN_PREFETCH: return true;
8280 case EXPR_OFFSETOF: return false;
8281 case EXPR_VA_START: return true;
8282 case EXPR_VA_ARG: return true;
8283 case EXPR_STATEMENT: return true; // TODO
8284 case EXPR_COMPOUND_LITERAL: return false;
8286 case EXPR_UNARY_NEGATE: return false;
8287 case EXPR_UNARY_PLUS: return false;
8288 case EXPR_UNARY_BITWISE_NEGATE: return false;
8289 case EXPR_UNARY_NOT: return false;
8290 case EXPR_UNARY_DEREFERENCE: return false;
8291 case EXPR_UNARY_TAKE_ADDRESS: return false;
8292 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8293 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8294 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8295 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8297 /* Treat void casts as if they have an effect in order to being able to
8298 * suppress the warning */
8299 case EXPR_UNARY_CAST: {
8300 type_t *const type = skip_typeref(expr->base.type);
8301 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8304 case EXPR_UNARY_CAST_IMPLICIT: return true;
8305 case EXPR_UNARY_ASSUME: return true;
8307 case EXPR_BINARY_ADD: return false;
8308 case EXPR_BINARY_SUB: return false;
8309 case EXPR_BINARY_MUL: return false;
8310 case EXPR_BINARY_DIV: return false;
8311 case EXPR_BINARY_MOD: return false;
8312 case EXPR_BINARY_EQUAL: return false;
8313 case EXPR_BINARY_NOTEQUAL: return false;
8314 case EXPR_BINARY_LESS: return false;
8315 case EXPR_BINARY_LESSEQUAL: return false;
8316 case EXPR_BINARY_GREATER: return false;
8317 case EXPR_BINARY_GREATEREQUAL: return false;
8318 case EXPR_BINARY_BITWISE_AND: return false;
8319 case EXPR_BINARY_BITWISE_OR: return false;
8320 case EXPR_BINARY_BITWISE_XOR: return false;
8321 case EXPR_BINARY_SHIFTLEFT: return false;
8322 case EXPR_BINARY_SHIFTRIGHT: return false;
8323 case EXPR_BINARY_ASSIGN: return true;
8324 case EXPR_BINARY_MUL_ASSIGN: return true;
8325 case EXPR_BINARY_DIV_ASSIGN: return true;
8326 case EXPR_BINARY_MOD_ASSIGN: return true;
8327 case EXPR_BINARY_ADD_ASSIGN: return true;
8328 case EXPR_BINARY_SUB_ASSIGN: return true;
8329 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8330 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8331 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8332 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8333 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8335 /* Only examine the right hand side of && and ||, because the left hand
8336 * side already has the effect of controlling the execution of the right
8338 case EXPR_BINARY_LOGICAL_AND:
8339 case EXPR_BINARY_LOGICAL_OR:
8340 /* Only examine the right hand side of a comma expression, because the left
8341 * hand side has a separate warning */
8342 case EXPR_BINARY_COMMA:
8343 return expression_has_effect(expr->binary.right);
8345 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8346 case EXPR_BINARY_ISGREATER: return false;
8347 case EXPR_BINARY_ISGREATEREQUAL: return false;
8348 case EXPR_BINARY_ISLESS: return false;
8349 case EXPR_BINARY_ISLESSEQUAL: return false;
8350 case EXPR_BINARY_ISLESSGREATER: return false;
8351 case EXPR_BINARY_ISUNORDERED: return false;
8354 internal_errorf(HERE, "unexpected expression");
8357 static void semantic_comma(binary_expression_t *expression)
8359 if (warning.unused_value) {
8360 const expression_t *const left = expression->left;
8361 if (!expression_has_effect(left)) {
8362 warningf(&left->base.source_position,
8363 "left-hand operand of comma expression has no effect");
8366 expression->base.type = expression->right->base.type;
8369 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8370 static expression_t *parse_##binexpression_type(unsigned precedence, \
8371 expression_t *left) \
8373 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8374 binexpr->base.source_position = *HERE; \
8375 binexpr->binary.left = left; \
8378 expression_t *right = parse_sub_expression(precedence + lr); \
8380 binexpr->binary.right = right; \
8381 sfunc(&binexpr->binary); \
8386 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8387 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8388 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8389 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8390 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8391 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8392 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8393 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8394 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8396 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8397 semantic_comparison, 1)
8398 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8399 semantic_comparison, 1)
8400 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8401 semantic_comparison, 1)
8402 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8403 semantic_comparison, 1)
8405 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8406 semantic_binexpr_arithmetic, 1)
8407 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8408 semantic_binexpr_arithmetic, 1)
8409 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8410 semantic_binexpr_arithmetic, 1)
8411 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8412 semantic_logical_op, 1)
8413 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8414 semantic_logical_op, 1)
8415 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8416 semantic_shift_op, 1)
8417 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8418 semantic_shift_op, 1)
8419 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8420 semantic_arithmetic_addsubb_assign, 0)
8421 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8422 semantic_arithmetic_addsubb_assign, 0)
8423 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8424 semantic_arithmetic_assign, 0)
8425 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8426 semantic_divmod_assign, 0)
8427 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8428 semantic_divmod_assign, 0)
8429 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8430 semantic_arithmetic_assign, 0)
8431 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8432 semantic_arithmetic_assign, 0)
8433 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8434 semantic_arithmetic_assign, 0)
8435 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8436 semantic_arithmetic_assign, 0)
8437 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8438 semantic_arithmetic_assign, 0)
8440 static expression_t *parse_sub_expression(unsigned precedence)
8442 if (token.type < 0) {
8443 return expected_expression_error();
8446 expression_parser_function_t *parser
8447 = &expression_parsers[token.type];
8448 source_position_t source_position = token.source_position;
8451 if (parser->parser != NULL) {
8452 left = parser->parser(parser->precedence);
8454 left = parse_primary_expression();
8456 assert(left != NULL);
8457 left->base.source_position = source_position;
8460 if (token.type < 0) {
8461 return expected_expression_error();
8464 parser = &expression_parsers[token.type];
8465 if (parser->infix_parser == NULL)
8467 if (parser->infix_precedence < precedence)
8470 left = parser->infix_parser(parser->infix_precedence, left);
8472 assert(left != NULL);
8473 assert(left->kind != EXPR_UNKNOWN);
8474 left->base.source_position = source_position;
8481 * Parse an expression.
8483 static expression_t *parse_expression(void)
8485 return parse_sub_expression(1);
8489 * Register a parser for a prefix-like operator with given precedence.
8491 * @param parser the parser function
8492 * @param token_type the token type of the prefix token
8493 * @param precedence the precedence of the operator
8495 static void register_expression_parser(parse_expression_function parser,
8496 int token_type, unsigned precedence)
8498 expression_parser_function_t *entry = &expression_parsers[token_type];
8500 if (entry->parser != NULL) {
8501 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8502 panic("trying to register multiple expression parsers for a token");
8504 entry->parser = parser;
8505 entry->precedence = precedence;
8509 * Register a parser for an infix operator with given precedence.
8511 * @param parser the parser function
8512 * @param token_type the token type of the infix operator
8513 * @param precedence the precedence of the operator
8515 static void register_infix_parser(parse_expression_infix_function parser,
8516 int token_type, unsigned precedence)
8518 expression_parser_function_t *entry = &expression_parsers[token_type];
8520 if (entry->infix_parser != NULL) {
8521 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8522 panic("trying to register multiple infix expression parsers for a "
8525 entry->infix_parser = parser;
8526 entry->infix_precedence = precedence;
8530 * Initialize the expression parsers.
8532 static void init_expression_parsers(void)
8534 memset(&expression_parsers, 0, sizeof(expression_parsers));
8536 register_infix_parser(parse_array_expression, '[', 30);
8537 register_infix_parser(parse_call_expression, '(', 30);
8538 register_infix_parser(parse_select_expression, '.', 30);
8539 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8540 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8542 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8545 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8546 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8547 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8548 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8549 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8550 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8551 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8552 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8553 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8554 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8555 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8556 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8557 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8558 T_EXCLAMATIONMARKEQUAL, 13);
8559 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8560 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8561 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8562 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8563 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8564 register_infix_parser(parse_conditional_expression, '?', 7);
8565 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8566 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8567 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8568 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8569 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8570 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8571 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8572 T_LESSLESSEQUAL, 2);
8573 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8574 T_GREATERGREATEREQUAL, 2);
8575 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8577 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8579 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8582 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8584 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8585 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8586 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8587 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8588 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8589 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8590 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8592 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8594 register_expression_parser(parse_sizeof, T_sizeof, 25);
8595 register_expression_parser(parse_alignof, T___alignof__, 25);
8596 register_expression_parser(parse_extension, T___extension__, 25);
8597 register_expression_parser(parse_builtin_classify_type,
8598 T___builtin_classify_type, 25);
8602 * Parse a asm statement arguments specification.
8604 static asm_argument_t *parse_asm_arguments(bool is_out)
8606 asm_argument_t *result = NULL;
8607 asm_argument_t *last = NULL;
8609 while (token.type == T_STRING_LITERAL || token.type == '[') {
8610 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8611 memset(argument, 0, sizeof(argument[0]));
8613 if (token.type == '[') {
8615 if (token.type != T_IDENTIFIER) {
8616 parse_error_expected("while parsing asm argument",
8617 T_IDENTIFIER, NULL);
8620 argument->symbol = token.v.symbol;
8625 argument->constraints = parse_string_literals();
8627 add_anchor_token(')');
8628 expression_t *expression = parse_expression();
8629 rem_anchor_token(')');
8631 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8632 * change size or type representation (e.g. int -> long is ok, but
8633 * int -> float is not) */
8634 if (expression->kind == EXPR_UNARY_CAST) {
8635 type_t *const type = expression->base.type;
8636 type_kind_t const kind = type->kind;
8637 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8640 if (kind == TYPE_ATOMIC) {
8641 atomic_type_kind_t const akind = type->atomic.akind;
8642 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8643 size = get_atomic_type_size(akind);
8645 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8646 size = get_atomic_type_size(get_intptr_kind());
8650 expression_t *const value = expression->unary.value;
8651 type_t *const value_type = value->base.type;
8652 type_kind_t const value_kind = value_type->kind;
8654 unsigned value_flags;
8655 unsigned value_size;
8656 if (value_kind == TYPE_ATOMIC) {
8657 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8658 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8659 value_size = get_atomic_type_size(value_akind);
8660 } else if (value_kind == TYPE_POINTER) {
8661 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8662 value_size = get_atomic_type_size(get_intptr_kind());
8667 if (value_flags != flags || value_size != size)
8671 } while (expression->kind == EXPR_UNARY_CAST);
8675 if (!is_lvalue(expression)) {
8676 errorf(&expression->base.source_position,
8677 "asm output argument is not an lvalue");
8680 argument->expression = expression;
8683 set_address_taken(expression, true);
8686 last->next = argument;
8692 if (token.type != ',')
8703 * Parse a asm statement clobber specification.
8705 static asm_clobber_t *parse_asm_clobbers(void)
8707 asm_clobber_t *result = NULL;
8708 asm_clobber_t *last = NULL;
8710 while(token.type == T_STRING_LITERAL) {
8711 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8712 clobber->clobber = parse_string_literals();
8715 last->next = clobber;
8721 if (token.type != ',')
8730 * Parse an asm statement.
8732 static statement_t *parse_asm_statement(void)
8736 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8737 statement->base.source_position = token.source_position;
8739 asm_statement_t *asm_statement = &statement->asms;
8741 if (token.type == T_volatile) {
8743 asm_statement->is_volatile = true;
8747 add_anchor_token(')');
8748 add_anchor_token(':');
8749 asm_statement->asm_text = parse_string_literals();
8751 if (token.type != ':') {
8752 rem_anchor_token(':');
8757 asm_statement->outputs = parse_asm_arguments(true);
8758 if (token.type != ':') {
8759 rem_anchor_token(':');
8764 asm_statement->inputs = parse_asm_arguments(false);
8765 if (token.type != ':') {
8766 rem_anchor_token(':');
8769 rem_anchor_token(':');
8772 asm_statement->clobbers = parse_asm_clobbers();
8775 rem_anchor_token(')');
8779 if (asm_statement->outputs == NULL) {
8780 /* GCC: An 'asm' instruction without any output operands will be treated
8781 * identically to a volatile 'asm' instruction. */
8782 asm_statement->is_volatile = true;
8787 return create_invalid_statement();
8791 * Parse a case statement.
8793 static statement_t *parse_case_statement(void)
8797 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8798 source_position_t *const pos = &statement->base.source_position;
8800 *pos = token.source_position;
8801 expression_t *const expression = parse_expression();
8802 statement->case_label.expression = expression;
8803 if (!is_constant_expression(expression)) {
8804 /* This check does not prevent the error message in all cases of an
8805 * prior error while parsing the expression. At least it catches the
8806 * common case of a mistyped enum entry. */
8807 if (is_type_valid(expression->base.type)) {
8808 errorf(pos, "case label does not reduce to an integer constant");
8810 statement->case_label.is_bad = true;
8812 long const val = fold_constant(expression);
8813 statement->case_label.first_case = val;
8814 statement->case_label.last_case = val;
8818 if (token.type == T_DOTDOTDOT) {
8820 expression_t *const end_range = parse_expression();
8821 statement->case_label.end_range = end_range;
8822 if (!is_constant_expression(end_range)) {
8823 /* This check does not prevent the error message in all cases of an
8824 * prior error while parsing the expression. At least it catches the
8825 * common case of a mistyped enum entry. */
8826 if (is_type_valid(end_range->base.type)) {
8827 errorf(pos, "case range does not reduce to an integer constant");
8829 statement->case_label.is_bad = true;
8831 long const val = fold_constant(end_range);
8832 statement->case_label.last_case = val;
8834 if (val < statement->case_label.first_case) {
8835 statement->case_label.is_empty_range = true;
8836 warningf(pos, "empty range specified");
8842 PUSH_PARENT(statement);
8846 if (current_switch != NULL) {
8847 if (! statement->case_label.is_bad) {
8848 /* Check for duplicate case values */
8849 case_label_statement_t *c = &statement->case_label;
8850 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8851 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8854 if (c->last_case < l->first_case || c->first_case > l->last_case)
8857 errorf(pos, "duplicate case value (previously used %P)",
8858 &l->base.source_position);
8862 /* link all cases into the switch statement */
8863 if (current_switch->last_case == NULL) {
8864 current_switch->first_case = &statement->case_label;
8866 current_switch->last_case->next = &statement->case_label;
8868 current_switch->last_case = &statement->case_label;
8870 errorf(pos, "case label not within a switch statement");
8873 statement_t *const inner_stmt = parse_statement();
8874 statement->case_label.statement = inner_stmt;
8875 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8876 errorf(&inner_stmt->base.source_position, "declaration after case label");
8883 return create_invalid_statement();
8887 * Parse a default statement.
8889 static statement_t *parse_default_statement(void)
8893 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8894 statement->base.source_position = token.source_position;
8896 PUSH_PARENT(statement);
8899 if (current_switch != NULL) {
8900 const case_label_statement_t *def_label = current_switch->default_label;
8901 if (def_label != NULL) {
8902 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8903 &def_label->base.source_position);
8905 current_switch->default_label = &statement->case_label;
8907 /* link all cases into the switch statement */
8908 if (current_switch->last_case == NULL) {
8909 current_switch->first_case = &statement->case_label;
8911 current_switch->last_case->next = &statement->case_label;
8913 current_switch->last_case = &statement->case_label;
8916 errorf(&statement->base.source_position,
8917 "'default' label not within a switch statement");
8920 statement_t *const inner_stmt = parse_statement();
8921 statement->case_label.statement = inner_stmt;
8922 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8923 errorf(&inner_stmt->base.source_position, "declaration after default label");
8930 return create_invalid_statement();
8934 * Parse a label statement.
8936 static statement_t *parse_label_statement(void)
8938 assert(token.type == T_IDENTIFIER);
8939 symbol_t *symbol = token.v.symbol;
8942 declaration_t *label = get_label(symbol);
8944 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8945 statement->base.source_position = token.source_position;
8946 statement->label.label = label;
8948 PUSH_PARENT(statement);
8950 /* if statement is already set then the label is defined twice,
8951 * otherwise it was just mentioned in a goto/local label declaration so far */
8952 if (label->init.statement != NULL) {
8953 errorf(HERE, "duplicate label '%Y' (declared %P)",
8954 symbol, &label->source_position);
8956 label->source_position = token.source_position;
8957 label->init.statement = statement;
8962 if (token.type == '}') {
8963 /* TODO only warn? */
8965 warningf(HERE, "label at end of compound statement");
8966 statement->label.statement = create_empty_statement();
8968 errorf(HERE, "label at end of compound statement");
8969 statement->label.statement = create_invalid_statement();
8971 } else if (token.type == ';') {
8972 /* Eat an empty statement here, to avoid the warning about an empty
8973 * statement after a label. label:; is commonly used to have a label
8974 * before a closing brace. */
8975 statement->label.statement = create_empty_statement();
8978 statement_t *const inner_stmt = parse_statement();
8979 statement->label.statement = inner_stmt;
8980 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8981 errorf(&inner_stmt->base.source_position, "declaration after label");
8985 /* remember the labels in a list for later checking */
8986 if (label_last == NULL) {
8987 label_first = &statement->label;
8989 label_last->next = &statement->label;
8991 label_last = &statement->label;
8998 * Parse an if statement.
9000 static statement_t *parse_if(void)
9004 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9005 statement->base.source_position = token.source_position;
9007 PUSH_PARENT(statement);
9010 add_anchor_token(')');
9011 statement->ifs.condition = parse_expression();
9012 rem_anchor_token(')');
9015 add_anchor_token(T_else);
9016 statement->ifs.true_statement = parse_statement();
9017 rem_anchor_token(T_else);
9019 if (token.type == T_else) {
9021 statement->ifs.false_statement = parse_statement();
9028 return create_invalid_statement();
9032 * Check that all enums are handled in a switch.
9034 * @param statement the switch statement to check
9036 static void check_enum_cases(const switch_statement_t *statement) {
9037 const type_t *type = skip_typeref(statement->expression->base.type);
9038 if (! is_type_enum(type))
9040 const enum_type_t *enumt = &type->enumt;
9042 /* if we have a default, no warnings */
9043 if (statement->default_label != NULL)
9046 /* FIXME: calculation of value should be done while parsing */
9047 const declaration_t *declaration;
9048 long last_value = -1;
9049 for (declaration = enumt->declaration->next;
9050 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9051 declaration = declaration->next) {
9052 const expression_t *expression = declaration->init.enum_value;
9053 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9055 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9056 if (l->expression == NULL)
9058 if (l->first_case <= value && value <= l->last_case) {
9064 warningf(&statement->base.source_position,
9065 "enumeration value '%Y' not handled in switch", declaration->symbol);
9072 * Parse a switch statement.
9074 static statement_t *parse_switch(void)
9078 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9079 statement->base.source_position = token.source_position;
9081 PUSH_PARENT(statement);
9084 add_anchor_token(')');
9085 expression_t *const expr = parse_expression();
9086 type_t * type = skip_typeref(expr->base.type);
9087 if (is_type_integer(type)) {
9088 type = promote_integer(type);
9089 if (warning.traditional) {
9090 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9091 warningf(&expr->base.source_position,
9092 "'%T' switch expression not converted to '%T' in ISO C",
9096 } else if (is_type_valid(type)) {
9097 errorf(&expr->base.source_position,
9098 "switch quantity is not an integer, but '%T'", type);
9099 type = type_error_type;
9101 statement->switchs.expression = create_implicit_cast(expr, type);
9103 rem_anchor_token(')');
9105 switch_statement_t *rem = current_switch;
9106 current_switch = &statement->switchs;
9107 statement->switchs.body = parse_statement();
9108 current_switch = rem;
9110 if (warning.switch_default &&
9111 statement->switchs.default_label == NULL) {
9112 warningf(&statement->base.source_position, "switch has no default case");
9114 if (warning.switch_enum)
9115 check_enum_cases(&statement->switchs);
9121 return create_invalid_statement();
9124 static statement_t *parse_loop_body(statement_t *const loop)
9126 statement_t *const rem = current_loop;
9127 current_loop = loop;
9129 statement_t *const body = parse_statement();
9136 * Parse a while statement.
9138 static statement_t *parse_while(void)
9142 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9143 statement->base.source_position = token.source_position;
9145 PUSH_PARENT(statement);
9148 add_anchor_token(')');
9149 statement->whiles.condition = parse_expression();
9150 rem_anchor_token(')');
9153 statement->whiles.body = parse_loop_body(statement);
9159 return create_invalid_statement();
9163 * Parse a do statement.
9165 static statement_t *parse_do(void)
9169 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9170 statement->base.source_position = token.source_position;
9172 PUSH_PARENT(statement)
9174 add_anchor_token(T_while);
9175 statement->do_while.body = parse_loop_body(statement);
9176 rem_anchor_token(T_while);
9180 add_anchor_token(')');
9181 statement->do_while.condition = parse_expression();
9182 rem_anchor_token(')');
9190 return create_invalid_statement();
9194 * Parse a for statement.
9196 static statement_t *parse_for(void)
9200 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9201 statement->base.source_position = token.source_position;
9203 PUSH_PARENT(statement);
9205 int top = environment_top();
9206 scope_push(&statement->fors.scope);
9209 add_anchor_token(')');
9211 if (token.type != ';') {
9212 if (is_declaration_specifier(&token, false)) {
9213 parse_declaration(record_declaration);
9215 add_anchor_token(';');
9216 expression_t *const init = parse_expression();
9217 statement->fors.initialisation = init;
9218 if (warning.unused_value && !expression_has_effect(init)) {
9219 warningf(&init->base.source_position,
9220 "initialisation of 'for'-statement has no effect");
9222 rem_anchor_token(';');
9229 if (token.type != ';') {
9230 add_anchor_token(';');
9231 statement->fors.condition = parse_expression();
9232 rem_anchor_token(';');
9235 if (token.type != ')') {
9236 expression_t *const step = parse_expression();
9237 statement->fors.step = step;
9238 if (warning.unused_value && !expression_has_effect(step)) {
9239 warningf(&step->base.source_position,
9240 "step of 'for'-statement has no effect");
9243 rem_anchor_token(')');
9245 statement->fors.body = parse_loop_body(statement);
9247 assert(scope == &statement->fors.scope);
9249 environment_pop_to(top);
9256 rem_anchor_token(')');
9257 assert(scope == &statement->fors.scope);
9259 environment_pop_to(top);
9261 return create_invalid_statement();
9265 * Parse a goto statement.
9267 static statement_t *parse_goto(void)
9269 source_position_t source_position = token.source_position;
9272 statement_t *statement;
9273 if (GNU_MODE && token.type == '*') {
9275 expression_t *expression = parse_expression();
9277 /* Argh: although documentation say the expression must be of type void *,
9278 * gcc excepts anything that can be casted into void * without error */
9279 type_t *type = expression->base.type;
9281 if (type != type_error_type) {
9282 if (!is_type_pointer(type) && !is_type_integer(type)) {
9283 errorf(&source_position, "cannot convert to a pointer type");
9284 } else if (type != type_void_ptr) {
9285 warningf(&source_position,
9286 "type of computed goto expression should be 'void*' not '%T'", type);
9288 expression = create_implicit_cast(expression, type_void_ptr);
9291 statement = allocate_statement_zero(STATEMENT_GOTO);
9292 statement->base.source_position = source_position;
9293 statement->gotos.expression = expression;
9295 if (token.type != T_IDENTIFIER) {
9297 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9299 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9303 symbol_t *symbol = token.v.symbol;
9306 statement = allocate_statement_zero(STATEMENT_GOTO);
9307 statement->base.source_position = source_position;
9308 statement->gotos.label = get_label(symbol);
9310 if (statement->gotos.label->parent_scope->depth < current_function->scope.depth) {
9311 statement->gotos.outer_fkt_jmp = true;
9315 /* remember the goto's in a list for later checking */
9316 if (goto_last == NULL) {
9317 goto_first = &statement->gotos;
9319 goto_last->next = &statement->gotos;
9321 goto_last = &statement->gotos;
9327 return create_invalid_statement();
9331 * Parse a continue statement.
9333 static statement_t *parse_continue(void)
9335 if (current_loop == NULL) {
9336 errorf(HERE, "continue statement not within loop");
9339 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9340 statement->base.source_position = token.source_position;
9350 * Parse a break statement.
9352 static statement_t *parse_break(void)
9354 if (current_switch == NULL && current_loop == NULL) {
9355 errorf(HERE, "break statement not within loop or switch");
9358 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9359 statement->base.source_position = token.source_position;
9369 * Parse a __leave statement.
9371 static statement_t *parse_leave_statement(void)
9373 if (current_try == NULL) {
9374 errorf(HERE, "__leave statement not within __try");
9377 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9378 statement->base.source_position = token.source_position;
9388 * Check if a given declaration represents a local variable.
9390 static bool is_local_var_declaration(const declaration_t *declaration)
9392 switch ((storage_class_tag_t) declaration->storage_class) {
9393 case STORAGE_CLASS_AUTO:
9394 case STORAGE_CLASS_REGISTER: {
9395 const type_t *type = skip_typeref(declaration->type);
9396 if (is_type_function(type)) {
9408 * Check if a given declaration represents a variable.
9410 static bool is_var_declaration(const declaration_t *declaration)
9412 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9415 const type_t *type = skip_typeref(declaration->type);
9416 return !is_type_function(type);
9420 * Check if a given expression represents a local variable.
9422 static bool is_local_variable(const expression_t *expression)
9424 if (expression->base.kind != EXPR_REFERENCE) {
9427 const declaration_t *declaration = expression->reference.declaration;
9428 return is_local_var_declaration(declaration);
9432 * Check if a given expression represents a local variable and
9433 * return its declaration then, else return NULL.
9435 declaration_t *expr_is_variable(const expression_t *expression)
9437 if (expression->base.kind != EXPR_REFERENCE) {
9440 declaration_t *declaration = expression->reference.declaration;
9441 if (is_var_declaration(declaration))
9447 * Parse a return statement.
9449 static statement_t *parse_return(void)
9451 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9452 statement->base.source_position = token.source_position;
9456 expression_t *return_value = NULL;
9457 if (token.type != ';') {
9458 return_value = parse_expression();
9461 const type_t *const func_type = current_function->type;
9462 assert(is_type_function(func_type));
9463 type_t *const return_type = skip_typeref(func_type->function.return_type);
9465 if (return_value != NULL) {
9466 type_t *return_value_type = skip_typeref(return_value->base.type);
9468 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9469 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9470 warningf(&statement->base.source_position,
9471 "'return' with a value, in function returning void");
9472 return_value = NULL;
9474 assign_error_t error = semantic_assign(return_type, return_value);
9475 report_assign_error(error, return_type, return_value, "'return'",
9476 &statement->base.source_position);
9477 return_value = create_implicit_cast(return_value, return_type);
9479 /* check for returning address of a local var */
9480 if (return_value != NULL &&
9481 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9482 const expression_t *expression = return_value->unary.value;
9483 if (is_local_variable(expression)) {
9484 warningf(&statement->base.source_position,
9485 "function returns address of local variable");
9489 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9490 warningf(&statement->base.source_position,
9491 "'return' without value, in function returning non-void");
9494 statement->returns.value = return_value;
9503 * Parse a declaration statement.
9505 static statement_t *parse_declaration_statement(void)
9507 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9509 statement->base.source_position = token.source_position;
9511 declaration_t *before = last_declaration;
9513 parse_external_declaration();
9515 parse_declaration(record_declaration);
9517 if (before == NULL) {
9518 statement->declaration.declarations_begin = scope->declarations;
9520 statement->declaration.declarations_begin = before->next;
9522 statement->declaration.declarations_end = last_declaration;
9528 * Parse an expression statement, ie. expr ';'.
9530 static statement_t *parse_expression_statement(void)
9532 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9534 statement->base.source_position = token.source_position;
9535 expression_t *const expr = parse_expression();
9536 statement->expression.expression = expr;
9545 * Parse a microsoft __try { } __finally { } or
9546 * __try{ } __except() { }
9548 static statement_t *parse_ms_try_statment(void)
9550 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9551 statement->base.source_position = token.source_position;
9554 PUSH_PARENT(statement);
9556 ms_try_statement_t *rem = current_try;
9557 current_try = &statement->ms_try;
9558 statement->ms_try.try_statement = parse_compound_statement(false);
9563 if (token.type == T___except) {
9566 add_anchor_token(')');
9567 expression_t *const expr = parse_expression();
9568 type_t * type = skip_typeref(expr->base.type);
9569 if (is_type_integer(type)) {
9570 type = promote_integer(type);
9571 } else if (is_type_valid(type)) {
9572 errorf(&expr->base.source_position,
9573 "__expect expression is not an integer, but '%T'", type);
9574 type = type_error_type;
9576 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9577 rem_anchor_token(')');
9579 statement->ms_try.final_statement = parse_compound_statement(false);
9580 } else if (token.type == T__finally) {
9582 statement->ms_try.final_statement = parse_compound_statement(false);
9584 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9585 return create_invalid_statement();
9589 return create_invalid_statement();
9592 static statement_t *parse_empty_statement(void)
9594 if (warning.empty_statement) {
9595 warningf(HERE, "statement is empty");
9597 statement_t *const statement = create_empty_statement();
9602 static statement_t *parse_local_label_declaration(void) {
9603 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9604 statement->base.source_position = token.source_position;
9608 declaration_t *begin = NULL, *end = NULL;
9611 if (token.type != T_IDENTIFIER) {
9612 parse_error_expected("while parsing local label declaration",
9613 T_IDENTIFIER, NULL);
9616 symbol_t *symbol = token.v.symbol;
9617 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9618 if (declaration != NULL) {
9619 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9620 symbol, &declaration->source_position);
9622 declaration = allocate_declaration_zero();
9623 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9624 declaration->source_position = token.source_position;
9625 declaration->symbol = symbol;
9626 declaration->parent_scope = scope;
9627 declaration->init.statement = NULL;
9630 end->next = declaration;
9633 begin = declaration;
9635 local_label_push(declaration);
9639 if (token.type != ',')
9645 statement->declaration.declarations_begin = begin;
9646 statement->declaration.declarations_end = end;
9651 * Parse a statement.
9652 * There's also parse_statement() which additionally checks for
9653 * "statement has no effect" warnings
9655 static statement_t *intern_parse_statement(void)
9657 statement_t *statement = NULL;
9659 /* declaration or statement */
9660 add_anchor_token(';');
9661 switch (token.type) {
9662 case T_IDENTIFIER: {
9663 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9664 if (la1_type == ':') {
9665 statement = parse_label_statement();
9666 } else if (is_typedef_symbol(token.v.symbol)) {
9667 statement = parse_declaration_statement();
9668 } else switch (la1_type) {
9670 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9671 goto expression_statment;
9676 statement = parse_declaration_statement();
9680 expression_statment:
9681 statement = parse_expression_statement();
9687 case T___extension__:
9688 /* This can be a prefix to a declaration or an expression statement.
9689 * We simply eat it now and parse the rest with tail recursion. */
9692 } while (token.type == T___extension__);
9693 bool old_gcc_extension = in_gcc_extension;
9694 in_gcc_extension = true;
9695 statement = parse_statement();
9696 in_gcc_extension = old_gcc_extension;
9700 statement = parse_declaration_statement();
9704 statement = parse_local_label_declaration();
9707 case ';': statement = parse_empty_statement(); break;
9708 case '{': statement = parse_compound_statement(false); break;
9709 case T___leave: statement = parse_leave_statement(); break;
9710 case T___try: statement = parse_ms_try_statment(); break;
9711 case T_asm: statement = parse_asm_statement(); break;
9712 case T_break: statement = parse_break(); break;
9713 case T_case: statement = parse_case_statement(); break;
9714 case T_continue: statement = parse_continue(); break;
9715 case T_default: statement = parse_default_statement(); break;
9716 case T_do: statement = parse_do(); break;
9717 case T_for: statement = parse_for(); break;
9718 case T_goto: statement = parse_goto(); break;
9719 case T_if: statement = parse_if (); break;
9720 case T_return: statement = parse_return(); break;
9721 case T_switch: statement = parse_switch(); break;
9722 case T_while: statement = parse_while(); break;
9732 case T_CHARACTER_CONSTANT:
9733 case T_FLOATINGPOINT:
9737 case T_STRING_LITERAL:
9738 case T_WIDE_CHARACTER_CONSTANT:
9739 case T_WIDE_STRING_LITERAL:
9740 case T___FUNCDNAME__:
9742 case T___FUNCTION__:
9743 case T___PRETTY_FUNCTION__:
9744 case T___builtin_alloca:
9745 case T___builtin_classify_type:
9746 case T___builtin_constant_p:
9747 case T___builtin_expect:
9748 case T___builtin_huge_val:
9749 case T___builtin_isgreater:
9750 case T___builtin_isgreaterequal:
9751 case T___builtin_isless:
9752 case T___builtin_islessequal:
9753 case T___builtin_islessgreater:
9754 case T___builtin_isunordered:
9755 case T___builtin_nan:
9756 case T___builtin_nand:
9757 case T___builtin_nanf:
9758 case T___builtin_offsetof:
9759 case T___builtin_prefetch:
9760 case T___builtin_va_arg:
9761 case T___builtin_va_end:
9762 case T___builtin_va_start:
9766 statement = parse_expression_statement();
9770 errorf(HERE, "unexpected token %K while parsing statement", &token);
9771 statement = create_invalid_statement();
9776 rem_anchor_token(';');
9778 assert(statement != NULL
9779 && statement->base.source_position.input_name != NULL);
9785 * parse a statement and emits "statement has no effect" warning if needed
9786 * (This is really a wrapper around intern_parse_statement with check for 1
9787 * single warning. It is needed, because for statement expressions we have
9788 * to avoid the warning on the last statement)
9790 static statement_t *parse_statement(void)
9792 statement_t *statement = intern_parse_statement();
9794 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9795 expression_t *expression = statement->expression.expression;
9796 if (!expression_has_effect(expression)) {
9797 warningf(&expression->base.source_position,
9798 "statement has no effect");
9806 * Parse a compound statement.
9808 static statement_t *parse_compound_statement(bool inside_expression_statement)
9810 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9811 statement->base.source_position = token.source_position;
9813 PUSH_PARENT(statement);
9816 add_anchor_token('}');
9818 int top = environment_top();
9819 int top_local = local_label_top();
9820 scope_push(&statement->compound.scope);
9822 statement_t **anchor = &statement->compound.statements;
9823 bool only_decls_so_far = true;
9824 while (token.type != '}' && token.type != T_EOF) {
9825 statement_t *sub_statement = intern_parse_statement();
9826 if (is_invalid_statement(sub_statement)) {
9827 /* an error occurred. if we are at an anchor, return */
9833 if (warning.declaration_after_statement) {
9834 if (sub_statement->kind != STATEMENT_DECLARATION) {
9835 only_decls_so_far = false;
9836 } else if (!only_decls_so_far) {
9837 warningf(&sub_statement->base.source_position,
9838 "ISO C90 forbids mixed declarations and code");
9842 *anchor = sub_statement;
9844 while (sub_statement->base.next != NULL)
9845 sub_statement = sub_statement->base.next;
9847 anchor = &sub_statement->base.next;
9850 if (token.type == '}') {
9853 errorf(&statement->base.source_position,
9854 "end of file while looking for closing '}'");
9857 /* look over all statements again to produce no effect warnings */
9858 if (warning.unused_value) {
9859 statement_t *sub_statement = statement->compound.statements;
9860 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9861 if (sub_statement->kind != STATEMENT_EXPRESSION)
9863 /* don't emit a warning for the last expression in an expression
9864 * statement as it has always an effect */
9865 if (inside_expression_statement && sub_statement->base.next == NULL)
9868 expression_t *expression = sub_statement->expression.expression;
9869 if (!expression_has_effect(expression)) {
9870 warningf(&expression->base.source_position,
9871 "statement has no effect");
9877 rem_anchor_token('}');
9878 assert(scope == &statement->compound.scope);
9880 environment_pop_to(top);
9881 local_label_pop_to(top_local);
9888 * Initialize builtin types.
9890 static void initialize_builtin_types(void)
9892 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9893 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9894 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9895 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9896 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9897 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9898 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9899 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9901 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9902 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9903 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9904 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9906 /* const version of wchar_t */
9907 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9908 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9909 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9911 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9915 * Check for unused global static functions and variables
9917 static void check_unused_globals(void)
9919 if (!warning.unused_function && !warning.unused_variable)
9922 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9924 decl->modifiers & DM_UNUSED ||
9925 decl->modifiers & DM_USED ||
9926 decl->storage_class != STORAGE_CLASS_STATIC)
9929 type_t *const type = decl->type;
9931 if (is_type_function(skip_typeref(type))) {
9932 if (!warning.unused_function || decl->is_inline)
9935 s = (decl->init.statement != NULL ? "defined" : "declared");
9937 if (!warning.unused_variable)
9943 warningf(&decl->source_position, "'%#T' %s but not used",
9944 type, decl->symbol, s);
9948 static void parse_global_asm(void)
9953 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9954 statement->base.source_position = token.source_position;
9955 statement->asms.asm_text = parse_string_literals();
9956 statement->base.next = unit->global_asm;
9957 unit->global_asm = statement;
9966 * Parse a translation unit.
9968 static void parse_translation_unit(void)
9972 bool anchor_leak = false;
9973 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9974 unsigned char count = token_anchor_set[i];
9976 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9980 if (in_gcc_extension) {
9981 errorf(HERE, "Leaked __extension__");
9989 switch (token.type) {
9992 case T___extension__:
9993 parse_external_declaration();
10004 /* TODO error in strict mode */
10005 warningf(HERE, "stray ';' outside of function");
10010 errorf(HERE, "stray %K outside of function", &token);
10011 if (token.type == '(' || token.type == '{' || token.type == '[')
10012 eat_until_matching_token(token.type);
10022 * @return the translation unit or NULL if errors occurred.
10024 void start_parsing(void)
10026 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10027 label_stack = NEW_ARR_F(stack_entry_t, 0);
10028 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10029 diagnostic_count = 0;
10033 type_set_output(stderr);
10034 ast_set_output(stderr);
10036 assert(unit == NULL);
10037 unit = allocate_ast_zero(sizeof(unit[0]));
10039 assert(global_scope == NULL);
10040 global_scope = &unit->scope;
10042 assert(scope == NULL);
10043 scope_push(&unit->scope);
10045 initialize_builtin_types();
10048 translation_unit_t *finish_parsing(void)
10050 /* do NOT use scope_pop() here, this will crash, will it by hand */
10051 assert(scope == &unit->scope);
10053 last_declaration = NULL;
10055 assert(global_scope == &unit->scope);
10056 check_unused_globals();
10057 global_scope = NULL;
10059 DEL_ARR_F(environment_stack);
10060 DEL_ARR_F(label_stack);
10061 DEL_ARR_F(local_label_stack);
10063 translation_unit_t *result = unit;
10070 lookahead_bufpos = 0;
10071 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10074 parse_translation_unit();
10078 * Initialize the parser.
10080 void init_parser(void)
10082 sym_anonymous = symbol_table_insert("<anonymous>");
10084 if (c_mode & _MS) {
10085 /* add predefined symbols for extended-decl-modifier */
10086 sym_align = symbol_table_insert("align");
10087 sym_allocate = symbol_table_insert("allocate");
10088 sym_dllimport = symbol_table_insert("dllimport");
10089 sym_dllexport = symbol_table_insert("dllexport");
10090 sym_naked = symbol_table_insert("naked");
10091 sym_noinline = symbol_table_insert("noinline");
10092 sym_noreturn = symbol_table_insert("noreturn");
10093 sym_nothrow = symbol_table_insert("nothrow");
10094 sym_novtable = symbol_table_insert("novtable");
10095 sym_property = symbol_table_insert("property");
10096 sym_get = symbol_table_insert("get");
10097 sym_put = symbol_table_insert("put");
10098 sym_selectany = symbol_table_insert("selectany");
10099 sym_thread = symbol_table_insert("thread");
10100 sym_uuid = symbol_table_insert("uuid");
10101 sym_deprecated = symbol_table_insert("deprecated");
10102 sym_restrict = symbol_table_insert("restrict");
10103 sym_noalias = symbol_table_insert("noalias");
10105 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10107 init_expression_parsers();
10108 obstack_init(&temp_obst);
10110 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10111 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10115 * Terminate the parser.
10117 void exit_parser(void)
10119 obstack_free(&temp_obst, NULL);