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 static token_t token;
109 static token_t lookahead_buffer[MAX_LOOKAHEAD];
110 static int lookahead_bufpos;
111 static stack_entry_t *environment_stack = NULL;
112 static stack_entry_t *label_stack = NULL;
113 static stack_entry_t *local_label_stack = NULL;
114 static scope_t *global_scope = NULL;
115 static scope_t *scope = NULL;
116 static declaration_t *last_declaration = NULL;
117 static declaration_t *current_function = NULL;
118 static declaration_t *current_init_decl = NULL;
119 static switch_statement_t *current_switch = NULL;
120 static statement_t *current_loop = NULL;
121 static statement_t *current_parent = NULL;
122 static ms_try_statement_t *current_try = NULL;
123 static goto_statement_t *goto_first = NULL;
124 static goto_statement_t *goto_last = NULL;
125 static label_statement_t *label_first = NULL;
126 static label_statement_t *label_last = NULL;
127 static translation_unit_t *unit = NULL;
128 static struct obstack temp_obst;
130 #define PUSH_PARENT(stmt) \
131 statement_t *const prev_parent = current_parent; \
132 current_parent = (stmt);
133 #define POP_PARENT ((void)(current_parent = prev_parent))
135 static source_position_t null_position = { NULL, 0 };
137 /** special symbol used for anonymous entities. */
138 static const symbol_t *sym_anonymous = NULL;
140 /* symbols for Microsoft extended-decl-modifier */
141 static const symbol_t *sym_align = NULL;
142 static const symbol_t *sym_allocate = NULL;
143 static const symbol_t *sym_dllimport = NULL;
144 static const symbol_t *sym_dllexport = NULL;
145 static const symbol_t *sym_naked = NULL;
146 static const symbol_t *sym_noinline = NULL;
147 static const symbol_t *sym_noreturn = NULL;
148 static const symbol_t *sym_nothrow = NULL;
149 static const symbol_t *sym_novtable = NULL;
150 static const symbol_t *sym_property = NULL;
151 static const symbol_t *sym_get = NULL;
152 static const symbol_t *sym_put = NULL;
153 static const symbol_t *sym_selectany = NULL;
154 static const symbol_t *sym_thread = NULL;
155 static const symbol_t *sym_uuid = NULL;
156 static const symbol_t *sym_deprecated = NULL;
157 static const symbol_t *sym_restrict = NULL;
158 static const symbol_t *sym_noalias = NULL;
160 /** The token anchor set */
161 static unsigned char token_anchor_set[T_LAST_TOKEN];
163 /** The current source position. */
164 #define HERE (&token.source_position)
166 static type_t *type_valist;
168 static statement_t *parse_compound_statement(bool inside_expression_statement);
169 static statement_t *parse_statement(void);
171 static expression_t *parse_sub_expression(unsigned precedence);
172 static expression_t *parse_expression(void);
173 static type_t *parse_typename(void);
175 static void parse_compound_type_entries(declaration_t *compound_declaration);
176 static declaration_t *parse_declarator(
177 const declaration_specifiers_t *specifiers, bool may_be_abstract);
178 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
180 static void semantic_comparison(binary_expression_t *expression);
182 #define STORAGE_CLASSES \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #ifdef PROVIDE_COMPLEX
199 #define COMPLEX_SPECIFIERS \
201 #define IMAGINARY_SPECIFIERS \
204 #define COMPLEX_SPECIFIERS
205 #define IMAGINARY_SPECIFIERS
208 #define TYPE_SPECIFIERS \
223 case T___builtin_va_list: \
228 #define DECLARATION_START \
233 #define TYPENAME_START \
238 * Allocate an AST node with given size and
239 * initialize all fields with zero.
241 static void *allocate_ast_zero(size_t size)
243 void *res = allocate_ast(size);
244 memset(res, 0, size);
248 static declaration_t *allocate_declaration_zero(void)
250 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
251 declaration->type = type_error_type;
252 declaration->alignment = 0;
257 * Returns the size of a statement node.
259 * @param kind the statement kind
261 static size_t get_statement_struct_size(statement_kind_t kind)
263 static const size_t sizes[] = {
264 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
265 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
266 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
267 [STATEMENT_RETURN] = sizeof(return_statement_t),
268 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
269 [STATEMENT_IF] = sizeof(if_statement_t),
270 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
271 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
272 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
273 [STATEMENT_BREAK] = sizeof(statement_base_t),
274 [STATEMENT_GOTO] = sizeof(goto_statement_t),
275 [STATEMENT_LABEL] = sizeof(label_statement_t),
276 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
277 [STATEMENT_WHILE] = sizeof(while_statement_t),
278 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
279 [STATEMENT_FOR] = sizeof(for_statement_t),
280 [STATEMENT_ASM] = sizeof(asm_statement_t),
281 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
282 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
284 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
285 assert(sizes[kind] != 0);
290 * Returns the size of an expression node.
292 * @param kind the expression kind
294 static size_t get_expression_struct_size(expression_kind_t kind)
296 static const size_t sizes[] = {
297 [EXPR_INVALID] = sizeof(expression_base_t),
298 [EXPR_REFERENCE] = sizeof(reference_expression_t),
299 [EXPR_CONST] = sizeof(const_expression_t),
300 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
301 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
302 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
303 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
304 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
305 [EXPR_CALL] = sizeof(call_expression_t),
306 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
307 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
308 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
309 [EXPR_SELECT] = sizeof(select_expression_t),
310 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
311 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
312 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
313 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
314 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
315 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
316 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
317 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
318 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
319 [EXPR_VA_START] = sizeof(va_start_expression_t),
320 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
321 [EXPR_STATEMENT] = sizeof(statement_expression_t),
322 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
324 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
325 return sizes[EXPR_UNARY_FIRST];
327 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
328 return sizes[EXPR_BINARY_FIRST];
330 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
331 assert(sizes[kind] != 0);
336 * Allocate a statement node of given kind and initialize all
339 static statement_t *allocate_statement_zero(statement_kind_t kind)
341 size_t size = get_statement_struct_size(kind);
342 statement_t *res = allocate_ast_zero(size);
344 res->base.kind = kind;
345 res->base.parent = current_parent;
350 * Allocate an expression node of given kind and initialize all
353 static expression_t *allocate_expression_zero(expression_kind_t kind)
355 size_t size = get_expression_struct_size(kind);
356 expression_t *res = allocate_ast_zero(size);
358 res->base.kind = kind;
359 res->base.type = type_error_type;
364 * Creates a new invalid expression.
366 static expression_t *create_invalid_expression(void)
368 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
369 expression->base.source_position = token.source_position;
374 * Creates a new invalid statement.
376 static statement_t *create_invalid_statement(void)
378 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
379 statement->base.source_position = token.source_position;
384 * Allocate a new empty statement.
386 static statement_t *create_empty_statement(void)
388 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
389 statement->base.source_position = token.source_position;
394 * Returns the size of a type node.
396 * @param kind the type kind
398 static size_t get_type_struct_size(type_kind_t kind)
400 static const size_t sizes[] = {
401 [TYPE_ATOMIC] = sizeof(atomic_type_t),
402 [TYPE_COMPLEX] = sizeof(complex_type_t),
403 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
404 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
405 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
406 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
407 [TYPE_ENUM] = sizeof(enum_type_t),
408 [TYPE_FUNCTION] = sizeof(function_type_t),
409 [TYPE_POINTER] = sizeof(pointer_type_t),
410 [TYPE_ARRAY] = sizeof(array_type_t),
411 [TYPE_BUILTIN] = sizeof(builtin_type_t),
412 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
413 [TYPE_TYPEOF] = sizeof(typeof_type_t),
415 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
416 assert(kind <= TYPE_TYPEOF);
417 assert(sizes[kind] != 0);
422 * Allocate a type node of given kind and initialize all
425 * @param kind type kind to allocate
426 * @param source_position the source position of the type definition
428 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
430 size_t size = get_type_struct_size(kind);
431 type_t *res = obstack_alloc(type_obst, size);
432 memset(res, 0, size);
434 res->base.kind = kind;
435 res->base.source_position = *source_position;
440 * Returns the size of an initializer node.
442 * @param kind the initializer kind
444 static size_t get_initializer_size(initializer_kind_t kind)
446 static const size_t sizes[] = {
447 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
448 [INITIALIZER_STRING] = sizeof(initializer_string_t),
449 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
450 [INITIALIZER_LIST] = sizeof(initializer_list_t),
451 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
453 assert(kind < sizeof(sizes) / sizeof(*sizes));
454 assert(sizes[kind] != 0);
459 * Allocate an initializer node of given kind and initialize all
462 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
464 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
471 * Free a type from the type obstack.
473 static void free_type(void *type)
475 obstack_free(type_obst, type);
479 * Returns the index of the top element of the environment stack.
481 static size_t environment_top(void)
483 return ARR_LEN(environment_stack);
487 * Returns the index of the top element of the global label stack.
489 static size_t label_top(void)
491 return ARR_LEN(label_stack);
495 * Returns the index of the top element of the local label stack.
497 static size_t local_label_top(void)
499 return ARR_LEN(local_label_stack);
503 * Return the next token.
505 static inline void next_token(void)
507 token = lookahead_buffer[lookahead_bufpos];
508 lookahead_buffer[lookahead_bufpos] = lexer_token;
511 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
514 print_token(stderr, &token);
515 fprintf(stderr, "\n");
520 * Return the next token with a given lookahead.
522 static inline const token_t *look_ahead(int num)
524 assert(num > 0 && num <= MAX_LOOKAHEAD);
525 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
526 return &lookahead_buffer[pos];
530 * Adds a token to the token anchor set (a multi-set).
532 static void add_anchor_token(int token_type)
534 assert(0 <= token_type && token_type < T_LAST_TOKEN);
535 ++token_anchor_set[token_type];
538 static int save_and_reset_anchor_state(int token_type)
540 assert(0 <= token_type && token_type < T_LAST_TOKEN);
541 int count = token_anchor_set[token_type];
542 token_anchor_set[token_type] = 0;
546 static void restore_anchor_state(int token_type, int count)
548 assert(0 <= token_type && token_type < T_LAST_TOKEN);
549 token_anchor_set[token_type] = count;
553 * Remove a token from the token anchor set (a multi-set).
555 static void rem_anchor_token(int token_type)
557 assert(0 <= token_type && token_type < T_LAST_TOKEN);
558 assert(token_anchor_set[token_type] != 0);
559 --token_anchor_set[token_type];
562 static bool at_anchor(void)
566 return token_anchor_set[token.type];
570 * Eat tokens until a matching token is found.
572 static void eat_until_matching_token(int type)
576 case '(': end_token = ')'; break;
577 case '{': end_token = '}'; break;
578 case '[': end_token = ']'; break;
579 default: end_token = type; break;
582 unsigned parenthesis_count = 0;
583 unsigned brace_count = 0;
584 unsigned bracket_count = 0;
585 while (token.type != end_token ||
586 parenthesis_count != 0 ||
588 bracket_count != 0) {
589 switch (token.type) {
591 case '(': ++parenthesis_count; break;
592 case '{': ++brace_count; break;
593 case '[': ++bracket_count; break;
596 if (parenthesis_count > 0)
606 if (bracket_count > 0)
609 if (token.type == end_token &&
610 parenthesis_count == 0 &&
624 * Eat input tokens until an anchor is found.
626 static void eat_until_anchor(void)
628 if (token.type == T_EOF)
630 while (token_anchor_set[token.type] == 0) {
631 if (token.type == '(' || token.type == '{' || token.type == '[')
632 eat_until_matching_token(token.type);
633 if (token.type == T_EOF)
639 static void eat_block(void)
641 eat_until_matching_token('{');
642 if (token.type == '}')
646 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
649 * Report a parse error because an expected token was not found.
652 #if defined __GNUC__ && __GNUC__ >= 4
653 __attribute__((sentinel))
655 void parse_error_expected(const char *message, ...)
657 if (message != NULL) {
658 errorf(HERE, "%s", message);
661 va_start(ap, message);
662 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
667 * Report a type error.
669 static void type_error(const char *msg, const source_position_t *source_position,
672 errorf(source_position, "%s, but found type '%T'", msg, type);
676 * Report an incompatible type.
678 static void type_error_incompatible(const char *msg,
679 const source_position_t *source_position, type_t *type1, type_t *type2)
681 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
686 * Expect the the current token is the expected token.
687 * If not, generate an error, eat the current statement,
688 * and goto the end_error label.
690 #define expect(expected) \
692 if (UNLIKELY(token.type != (expected))) { \
693 parse_error_expected(NULL, (expected), NULL); \
694 add_anchor_token(expected); \
695 eat_until_anchor(); \
696 if (token.type == expected) \
698 rem_anchor_token(expected); \
704 static void set_scope(scope_t *new_scope)
707 scope->last_declaration = last_declaration;
711 last_declaration = new_scope->last_declaration;
715 * Search a symbol in a given namespace and returns its declaration or
716 * NULL if this symbol was not found.
718 static declaration_t *get_declaration(const symbol_t *const symbol,
719 const namespace_t namespc)
721 declaration_t *declaration = symbol->declaration;
722 for( ; declaration != NULL; declaration = declaration->symbol_next) {
723 if (declaration->namespc == namespc)
731 * pushs an environment_entry on the environment stack and links the
732 * corresponding symbol to the new entry
734 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
736 symbol_t *symbol = declaration->symbol;
737 namespace_t namespc = (namespace_t) declaration->namespc;
739 /* replace/add declaration into declaration list of the symbol */
740 declaration_t *iter = symbol->declaration;
742 symbol->declaration = declaration;
744 declaration_t *iter_last = NULL;
745 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
746 /* replace an entry? */
747 if (iter->namespc == namespc) {
748 if (iter_last == NULL) {
749 symbol->declaration = declaration;
751 iter_last->symbol_next = declaration;
753 declaration->symbol_next = iter->symbol_next;
758 assert(iter_last->symbol_next == NULL);
759 iter_last->symbol_next = declaration;
763 /* remember old declaration */
765 entry.symbol = symbol;
766 entry.old_declaration = iter;
767 entry.namespc = (unsigned short) namespc;
768 ARR_APP1(stack_entry_t, *stack_ptr, entry);
772 * Push a declaration on the environment stack.
774 * @param declaration the declaration
776 static void environment_push(declaration_t *declaration)
778 assert(declaration->source_position.input_name != NULL);
779 assert(declaration->parent_scope != NULL);
780 stack_push(&environment_stack, declaration);
784 * Push a declaration on the global label stack.
786 * @param declaration the declaration
788 static void label_push(declaration_t *declaration)
790 declaration->parent_scope = ¤t_function->scope;
791 stack_push(&label_stack, declaration);
795 * Push a declaration of the local label stack.
797 * @param declaration the declaration
799 static void local_label_push(declaration_t *declaration)
801 assert(declaration->parent_scope != NULL);
802 stack_push(&local_label_stack, declaration);
806 * pops symbols from the environment stack until @p new_top is the top element
808 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
810 stack_entry_t *stack = *stack_ptr;
811 size_t top = ARR_LEN(stack);
814 assert(new_top <= top);
818 for(i = top; i > new_top; --i) {
819 stack_entry_t *entry = &stack[i - 1];
821 declaration_t *old_declaration = entry->old_declaration;
822 symbol_t *symbol = entry->symbol;
823 namespace_t namespc = (namespace_t)entry->namespc;
825 /* replace/remove declaration */
826 declaration_t *declaration = symbol->declaration;
827 assert(declaration != NULL);
828 if (declaration->namespc == namespc) {
829 if (old_declaration == NULL) {
830 symbol->declaration = declaration->symbol_next;
832 symbol->declaration = old_declaration;
835 declaration_t *iter_last = declaration;
836 declaration_t *iter = declaration->symbol_next;
837 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
838 /* replace an entry? */
839 if (iter->namespc == namespc) {
840 assert(iter_last != NULL);
841 iter_last->symbol_next = old_declaration;
842 if (old_declaration != NULL) {
843 old_declaration->symbol_next = iter->symbol_next;
848 assert(iter != NULL);
852 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
856 * Pop all entries from the environment stack until the new_top
859 * @param new_top the new stack top
861 static void environment_pop_to(size_t new_top)
863 stack_pop_to(&environment_stack, new_top);
867 * Pop all entries from the global label stack until the new_top
870 * @param new_top the new stack top
872 static void label_pop_to(size_t new_top)
874 stack_pop_to(&label_stack, new_top);
878 * Pop all entries from the local label stack until the new_top
881 * @param new_top the new stack top
883 static void local_label_pop_to(size_t new_top)
885 stack_pop_to(&local_label_stack, new_top);
889 static int get_akind_rank(atomic_type_kind_t akind)
894 static int get_rank(const type_t *type)
896 assert(!is_typeref(type));
897 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
898 * and esp. footnote 108). However we can't fold constants (yet), so we
899 * can't decide whether unsigned int is possible, while int always works.
900 * (unsigned int would be preferable when possible... for stuff like
901 * struct { enum { ... } bla : 4; } ) */
902 if (type->kind == TYPE_ENUM)
903 return get_akind_rank(ATOMIC_TYPE_INT);
905 assert(type->kind == TYPE_ATOMIC);
906 return get_akind_rank(type->atomic.akind);
909 static type_t *promote_integer(type_t *type)
911 if (type->kind == TYPE_BITFIELD)
912 type = type->bitfield.base_type;
914 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
921 * Create a cast expression.
923 * @param expression the expression to cast
924 * @param dest_type the destination type
926 static expression_t *create_cast_expression(expression_t *expression,
929 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
931 cast->unary.value = expression;
932 cast->base.type = dest_type;
938 * Check if a given expression represents the 0 pointer constant.
940 static bool is_null_pointer_constant(const expression_t *expression)
942 /* skip void* cast */
943 if (expression->kind == EXPR_UNARY_CAST
944 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
945 expression = expression->unary.value;
948 /* TODO: not correct yet, should be any constant integer expression
949 * which evaluates to 0 */
950 if (expression->kind != EXPR_CONST)
953 type_t *const type = skip_typeref(expression->base.type);
954 if (!is_type_integer(type))
957 return expression->conste.v.int_value == 0;
961 * Create an implicit cast expression.
963 * @param expression the expression to cast
964 * @param dest_type the destination type
966 static expression_t *create_implicit_cast(expression_t *expression,
969 type_t *const source_type = expression->base.type;
971 if (source_type == dest_type)
974 return create_cast_expression(expression, dest_type);
977 typedef enum assign_error_t {
979 ASSIGN_ERROR_INCOMPATIBLE,
980 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
981 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
982 ASSIGN_WARNING_POINTER_FROM_INT,
983 ASSIGN_WARNING_INT_FROM_POINTER
986 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
987 const expression_t *const right,
989 const source_position_t *source_position)
991 type_t *const orig_type_right = right->base.type;
992 type_t *const type_left = skip_typeref(orig_type_left);
993 type_t *const type_right = skip_typeref(orig_type_right);
998 case ASSIGN_ERROR_INCOMPATIBLE:
999 errorf(source_position,
1000 "destination type '%T' in %s is incompatible with type '%T'",
1001 orig_type_left, context, orig_type_right);
1004 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1005 type_t *points_to_left
1006 = skip_typeref(type_left->pointer.points_to);
1007 type_t *points_to_right
1008 = skip_typeref(type_right->pointer.points_to);
1010 /* the left type has all qualifiers from the right type */
1011 unsigned missing_qualifiers
1012 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1013 warningf(source_position,
1014 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1015 orig_type_left, context, orig_type_right, missing_qualifiers);
1019 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1020 warningf(source_position,
1021 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1022 orig_type_left, context, right, orig_type_right);
1025 case ASSIGN_WARNING_POINTER_FROM_INT:
1026 warningf(source_position,
1027 "%s makes pointer '%T' from integer '%T' without a cast",
1028 context, orig_type_left, orig_type_right);
1031 case ASSIGN_WARNING_INT_FROM_POINTER:
1032 warningf(source_position,
1033 "%s makes integer '%T' from pointer '%T' without a cast",
1034 context, orig_type_left, orig_type_right);
1038 panic("invalid error value");
1042 /** Implements the rules from § 6.5.16.1 */
1043 static assign_error_t semantic_assign(type_t *orig_type_left,
1044 const expression_t *const right)
1046 type_t *const orig_type_right = right->base.type;
1047 type_t *const type_left = skip_typeref(orig_type_left);
1048 type_t *const type_right = skip_typeref(orig_type_right);
1050 if (is_type_pointer(type_left)) {
1051 if (is_null_pointer_constant(right)) {
1052 return ASSIGN_SUCCESS;
1053 } else if (is_type_pointer(type_right)) {
1054 type_t *points_to_left
1055 = skip_typeref(type_left->pointer.points_to);
1056 type_t *points_to_right
1057 = skip_typeref(type_right->pointer.points_to);
1058 assign_error_t res = ASSIGN_SUCCESS;
1060 /* the left type has all qualifiers from the right type */
1061 unsigned missing_qualifiers
1062 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1063 if (missing_qualifiers != 0) {
1064 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1067 points_to_left = get_unqualified_type(points_to_left);
1068 points_to_right = get_unqualified_type(points_to_right);
1070 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1071 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1075 if (!types_compatible(points_to_left, points_to_right)) {
1076 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1080 } else if (is_type_integer(type_right)) {
1081 return ASSIGN_WARNING_POINTER_FROM_INT;
1083 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1084 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1085 && is_type_pointer(type_right))) {
1086 return ASSIGN_SUCCESS;
1087 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1088 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1089 type_t *const unqual_type_left = get_unqualified_type(type_left);
1090 type_t *const unqual_type_right = get_unqualified_type(type_right);
1091 if (types_compatible(unqual_type_left, unqual_type_right)) {
1092 return ASSIGN_SUCCESS;
1094 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1095 return ASSIGN_WARNING_INT_FROM_POINTER;
1098 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1099 return ASSIGN_SUCCESS;
1101 return ASSIGN_ERROR_INCOMPATIBLE;
1104 static expression_t *parse_constant_expression(void)
1106 /* start parsing at precedence 7 (conditional expression) */
1107 expression_t *result = parse_sub_expression(7);
1109 if (!is_constant_expression(result)) {
1110 errorf(&result->base.source_position,
1111 "expression '%E' is not constant\n", result);
1117 static expression_t *parse_assignment_expression(void)
1119 /* start parsing at precedence 2 (assignment expression) */
1120 return parse_sub_expression(2);
1123 static type_t *make_global_typedef(const char *name, type_t *type)
1125 symbol_t *const symbol = symbol_table_insert(name);
1127 declaration_t *const declaration = allocate_declaration_zero();
1128 declaration->namespc = NAMESPACE_NORMAL;
1129 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1130 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1131 declaration->type = type;
1132 declaration->symbol = symbol;
1133 declaration->source_position = builtin_source_position;
1134 declaration->implicit = true;
1136 record_declaration(declaration, false);
1138 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1139 typedef_type->typedeft.declaration = declaration;
1141 return typedef_type;
1144 static string_t parse_string_literals(void)
1146 assert(token.type == T_STRING_LITERAL);
1147 string_t result = token.v.string;
1151 while (token.type == T_STRING_LITERAL) {
1152 result = concat_strings(&result, &token.v.string);
1159 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1160 [GNU_AK_CONST] = "const",
1161 [GNU_AK_VOLATILE] = "volatile",
1162 [GNU_AK_CDECL] = "cdecl",
1163 [GNU_AK_STDCALL] = "stdcall",
1164 [GNU_AK_FASTCALL] = "fastcall",
1165 [GNU_AK_DEPRECATED] = "deprecated",
1166 [GNU_AK_NOINLINE] = "noinline",
1167 [GNU_AK_NORETURN] = "noreturn",
1168 [GNU_AK_NAKED] = "naked",
1169 [GNU_AK_PURE] = "pure",
1170 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1171 [GNU_AK_MALLOC] = "malloc",
1172 [GNU_AK_WEAK] = "weak",
1173 [GNU_AK_CONSTRUCTOR] = "constructor",
1174 [GNU_AK_DESTRUCTOR] = "destructor",
1175 [GNU_AK_NOTHROW] = "nothrow",
1176 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1177 [GNU_AK_COMMON] = "common",
1178 [GNU_AK_NOCOMMON] = "nocommon",
1179 [GNU_AK_PACKED] = "packed",
1180 [GNU_AK_SHARED] = "shared",
1181 [GNU_AK_NOTSHARED] = "notshared",
1182 [GNU_AK_USED] = "used",
1183 [GNU_AK_UNUSED] = "unused",
1184 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1185 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1186 [GNU_AK_LONGCALL] = "longcall",
1187 [GNU_AK_SHORTCALL] = "shortcall",
1188 [GNU_AK_LONG_CALL] = "long_call",
1189 [GNU_AK_SHORT_CALL] = "short_call",
1190 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1191 [GNU_AK_INTERRUPT] = "interrupt",
1192 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1193 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1194 [GNU_AK_NESTING] = "nesting",
1195 [GNU_AK_NEAR] = "near",
1196 [GNU_AK_FAR] = "far",
1197 [GNU_AK_SIGNAL] = "signal",
1198 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1199 [GNU_AK_TINY_DATA] = "tiny_data",
1200 [GNU_AK_SAVEALL] = "saveall",
1201 [GNU_AK_FLATTEN] = "flatten",
1202 [GNU_AK_SSEREGPARM] = "sseregparm",
1203 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1204 [GNU_AK_RETURN_TWICE] = "return_twice",
1205 [GNU_AK_MAY_ALIAS] = "may_alias",
1206 [GNU_AK_MS_STRUCT] = "ms_struct",
1207 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1208 [GNU_AK_DLLIMPORT] = "dllimport",
1209 [GNU_AK_DLLEXPORT] = "dllexport",
1210 [GNU_AK_ALIGNED] = "aligned",
1211 [GNU_AK_ALIAS] = "alias",
1212 [GNU_AK_SECTION] = "section",
1213 [GNU_AK_FORMAT] = "format",
1214 [GNU_AK_FORMAT_ARG] = "format_arg",
1215 [GNU_AK_WEAKREF] = "weakref",
1216 [GNU_AK_NONNULL] = "nonnull",
1217 [GNU_AK_TLS_MODEL] = "tls_model",
1218 [GNU_AK_VISIBILITY] = "visibility",
1219 [GNU_AK_REGPARM] = "regparm",
1220 [GNU_AK_MODE] = "mode",
1221 [GNU_AK_MODEL] = "model",
1222 [GNU_AK_TRAP_EXIT] = "trap_exit",
1223 [GNU_AK_SP_SWITCH] = "sp_switch",
1224 [GNU_AK_SENTINEL] = "sentinel"
1228 * compare two string, ignoring double underscores on the second.
1230 static int strcmp_underscore(const char *s1, const char *s2)
1232 if (s2[0] == '_' && s2[1] == '_') {
1233 size_t len2 = strlen(s2);
1234 size_t len1 = strlen(s1);
1235 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1236 return strncmp(s1, s2+2, len2-4);
1240 return strcmp(s1, s2);
1244 * Allocate a new gnu temporal attribute.
1246 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1248 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1249 attribute->kind = kind;
1250 attribute->next = NULL;
1251 attribute->invalid = false;
1252 attribute->have_arguments = false;
1258 * parse one constant expression argument.
1260 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1262 expression_t *expression;
1263 add_anchor_token(')');
1264 expression = parse_constant_expression();
1265 rem_anchor_token(')');
1267 attribute->u.argument = fold_constant(expression);
1270 attribute->invalid = true;
1274 * parse a list of constant expressions arguments.
1276 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1278 argument_list_t **list = &attribute->u.arguments;
1279 argument_list_t *entry;
1280 expression_t *expression;
1281 add_anchor_token(')');
1282 add_anchor_token(',');
1284 expression = parse_constant_expression();
1285 entry = obstack_alloc(&temp_obst, sizeof(entry));
1286 entry->argument = fold_constant(expression);
1289 list = &entry->next;
1290 if (token.type != ',')
1294 rem_anchor_token(',');
1295 rem_anchor_token(')');
1299 attribute->invalid = true;
1303 * parse one string literal argument.
1305 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1308 add_anchor_token('(');
1309 if (token.type != T_STRING_LITERAL) {
1310 parse_error_expected("while parsing attribute directive",
1311 T_STRING_LITERAL, NULL);
1314 *string = parse_string_literals();
1315 rem_anchor_token('(');
1319 attribute->invalid = true;
1323 * parse one tls model.
1325 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1327 static const char *const tls_models[] = {
1333 string_t string = { NULL, 0 };
1334 parse_gnu_attribute_string_arg(attribute, &string);
1335 if (string.begin != NULL) {
1336 for(size_t i = 0; i < 4; ++i) {
1337 if (strcmp(tls_models[i], string.begin) == 0) {
1338 attribute->u.value = i;
1342 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1344 attribute->invalid = true;
1348 * parse one tls model.
1350 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1352 static const char *const visibilities[] = {
1358 string_t string = { NULL, 0 };
1359 parse_gnu_attribute_string_arg(attribute, &string);
1360 if (string.begin != NULL) {
1361 for(size_t i = 0; i < 4; ++i) {
1362 if (strcmp(visibilities[i], string.begin) == 0) {
1363 attribute->u.value = i;
1367 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1369 attribute->invalid = true;
1373 * parse one (code) model.
1375 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1377 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(int i = 0; i < 3; ++i) {
1386 if (strcmp(visibilities[i], string.begin) == 0) {
1387 attribute->u.value = i;
1391 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1393 attribute->invalid = true;
1396 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1398 /* TODO: find out what is allowed here... */
1400 /* at least: byte, word, pointer, list of machine modes
1401 * __XXX___ is interpreted as XXX */
1402 add_anchor_token(')');
1404 if (token.type != T_IDENTIFIER) {
1405 expect(T_IDENTIFIER);
1408 /* This isn't really correct, the backend should provide a list of machine
1409 * specific modes (according to gcc philosophy that is...) */
1410 const char *symbol_str = token.v.symbol->string;
1411 if (strcmp_underscore("QI", symbol_str) == 0 ||
1412 strcmp_underscore("byte", symbol_str) == 0) {
1413 attribute->u.akind = ATOMIC_TYPE_CHAR;
1414 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1415 attribute->u.akind = ATOMIC_TYPE_SHORT;
1416 } else if (strcmp_underscore("SI", symbol_str) == 0
1417 || strcmp_underscore("word", symbol_str) == 0
1418 || strcmp_underscore("pointer", symbol_str) == 0) {
1419 attribute->u.akind = ATOMIC_TYPE_INT;
1420 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1421 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1423 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1424 attribute->invalid = true;
1428 rem_anchor_token(')');
1432 attribute->invalid = true;
1436 * parse one interrupt argument.
1438 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1440 static const char *const interrupts[] = {
1447 string_t string = { NULL, 0 };
1448 parse_gnu_attribute_string_arg(attribute, &string);
1449 if (string.begin != NULL) {
1450 for(size_t i = 0; i < 5; ++i) {
1451 if (strcmp(interrupts[i], string.begin) == 0) {
1452 attribute->u.value = i;
1456 errorf(HERE, "'%s' is not an interrupt", string.begin);
1458 attribute->invalid = true;
1462 * parse ( identifier, const expression, const expression )
1464 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1466 static const char *const format_names[] = {
1474 if (token.type != T_IDENTIFIER) {
1475 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1478 const char *name = token.v.symbol->string;
1479 for(i = 0; i < 4; ++i) {
1480 if (strcmp_underscore(format_names[i], name) == 0)
1484 if (warning.attribute)
1485 warningf(HERE, "'%s' is an unrecognized format function type", name);
1490 add_anchor_token(')');
1491 add_anchor_token(',');
1492 parse_constant_expression();
1493 rem_anchor_token(',');
1494 rem_anchor_token(')');
1497 add_anchor_token(')');
1498 parse_constant_expression();
1499 rem_anchor_token(')');
1503 attribute->u.value = true;
1506 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1508 if (!attribute->have_arguments)
1511 /* should have no arguments */
1512 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1513 eat_until_matching_token('(');
1514 /* we have already consumed '(', so we stop before ')', eat it */
1516 attribute->invalid = true;
1520 * Parse one GNU attribute.
1522 * Note that attribute names can be specified WITH or WITHOUT
1523 * double underscores, ie const or __const__.
1525 * The following attributes are parsed without arguments
1550 * no_instrument_function
1551 * warn_unused_result
1568 * externally_visible
1576 * The following attributes are parsed with arguments
1577 * aligned( const expression )
1578 * alias( string literal )
1579 * section( string literal )
1580 * format( identifier, const expression, const expression )
1581 * format_arg( const expression )
1582 * tls_model( string literal )
1583 * visibility( string literal )
1584 * regparm( const expression )
1585 * model( string leteral )
1586 * trap_exit( const expression )
1587 * sp_switch( string literal )
1589 * The following attributes might have arguments
1590 * weak_ref( string literal )
1591 * non_null( const expression // ',' )
1592 * interrupt( string literal )
1593 * sentinel( constant expression )
1595 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1597 gnu_attribute_t *head = *attributes;
1598 gnu_attribute_t *last = *attributes;
1599 decl_modifiers_t modifiers = 0;
1600 gnu_attribute_t *attribute;
1602 eat(T___attribute__);
1606 if (token.type != ')') {
1607 /* find the end of the list */
1609 while (last->next != NULL)
1613 /* non-empty attribute list */
1616 if (token.type == T_const) {
1618 } else if (token.type == T_volatile) {
1620 } else if (token.type == T_cdecl) {
1621 /* __attribute__((cdecl)), WITH ms mode */
1623 } else if (token.type == T_IDENTIFIER) {
1624 const symbol_t *sym = token.v.symbol;
1627 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1634 for(i = 0; i < GNU_AK_LAST; ++i) {
1635 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1638 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1641 if (kind == GNU_AK_LAST) {
1642 if (warning.attribute)
1643 warningf(HERE, "'%s' attribute directive ignored", name);
1645 /* skip possible arguments */
1646 if (token.type == '(') {
1647 eat_until_matching_token(')');
1650 /* check for arguments */
1651 attribute = allocate_gnu_attribute(kind);
1652 if (token.type == '(') {
1654 if (token.type == ')') {
1655 /* empty args are allowed */
1658 attribute->have_arguments = true;
1663 case GNU_AK_VOLATILE:
1668 case GNU_AK_NOCOMMON:
1670 case GNU_AK_NOTSHARED:
1671 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1672 case GNU_AK_WARN_UNUSED_RESULT:
1673 case GNU_AK_LONGCALL:
1674 case GNU_AK_SHORTCALL:
1675 case GNU_AK_LONG_CALL:
1676 case GNU_AK_SHORT_CALL:
1677 case GNU_AK_FUNCTION_VECTOR:
1678 case GNU_AK_INTERRUPT_HANDLER:
1679 case GNU_AK_NMI_HANDLER:
1680 case GNU_AK_NESTING:
1684 case GNU_AK_EIGTHBIT_DATA:
1685 case GNU_AK_TINY_DATA:
1686 case GNU_AK_SAVEALL:
1687 case GNU_AK_FLATTEN:
1688 case GNU_AK_SSEREGPARM:
1689 case GNU_AK_EXTERNALLY_VISIBLE:
1690 case GNU_AK_RETURN_TWICE:
1691 case GNU_AK_MAY_ALIAS:
1692 case GNU_AK_MS_STRUCT:
1693 case GNU_AK_GCC_STRUCT:
1696 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1697 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1698 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1699 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1700 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1701 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1702 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1703 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1704 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1705 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1706 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1707 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1708 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1709 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1710 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1711 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1712 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1714 case GNU_AK_ALIGNED:
1715 /* __align__ may be used without an argument */
1716 if (attribute->have_arguments) {
1717 parse_gnu_attribute_const_arg(attribute);
1721 case GNU_AK_FORMAT_ARG:
1722 case GNU_AK_REGPARM:
1723 case GNU_AK_TRAP_EXIT:
1724 if (!attribute->have_arguments) {
1725 /* should have arguments */
1726 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1727 attribute->invalid = true;
1729 parse_gnu_attribute_const_arg(attribute);
1732 case GNU_AK_SECTION:
1733 case GNU_AK_SP_SWITCH:
1734 if (!attribute->have_arguments) {
1735 /* should have arguments */
1736 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1737 attribute->invalid = true;
1739 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1742 if (!attribute->have_arguments) {
1743 /* should have arguments */
1744 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1745 attribute->invalid = true;
1747 parse_gnu_attribute_format_args(attribute);
1749 case GNU_AK_WEAKREF:
1750 /* may have one string argument */
1751 if (attribute->have_arguments)
1752 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1754 case GNU_AK_NONNULL:
1755 if (attribute->have_arguments)
1756 parse_gnu_attribute_const_arg_list(attribute);
1758 case GNU_AK_TLS_MODEL:
1759 if (!attribute->have_arguments) {
1760 /* should have arguments */
1761 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1763 parse_gnu_attribute_tls_model_arg(attribute);
1765 case GNU_AK_VISIBILITY:
1766 if (!attribute->have_arguments) {
1767 /* should have arguments */
1768 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1770 parse_gnu_attribute_visibility_arg(attribute);
1773 if (!attribute->have_arguments) {
1774 /* should have arguments */
1775 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1777 parse_gnu_attribute_model_arg(attribute);
1781 if (!attribute->have_arguments) {
1782 /* should have arguments */
1783 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1785 parse_gnu_attribute_mode_arg(attribute);
1788 case GNU_AK_INTERRUPT:
1789 /* may have one string argument */
1790 if (attribute->have_arguments)
1791 parse_gnu_attribute_interrupt_arg(attribute);
1793 case GNU_AK_SENTINEL:
1794 /* may have one string argument */
1795 if (attribute->have_arguments)
1796 parse_gnu_attribute_const_arg(attribute);
1799 /* already handled */
1803 check_no_argument(attribute, name);
1806 if (attribute != NULL) {
1808 last->next = attribute;
1811 head = last = attribute;
1815 if (token.type != ',')
1829 * Parse GNU attributes.
1831 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1833 decl_modifiers_t modifiers = 0;
1836 switch(token.type) {
1837 case T___attribute__:
1838 modifiers |= parse_gnu_attribute(attributes);
1844 if (token.type != T_STRING_LITERAL) {
1845 parse_error_expected("while parsing assembler attribute",
1846 T_STRING_LITERAL, NULL);
1847 eat_until_matching_token('(');
1850 parse_string_literals();
1855 case T_cdecl: modifiers |= DM_CDECL; break;
1856 case T__fastcall: modifiers |= DM_FASTCALL; break;
1857 case T__stdcall: modifiers |= DM_STDCALL; break;
1860 /* TODO record modifier */
1861 warningf(HERE, "Ignoring declaration modifier %K", &token);
1865 default: return modifiers;
1872 static designator_t *parse_designation(void)
1874 designator_t *result = NULL;
1875 designator_t *last = NULL;
1878 designator_t *designator;
1879 switch(token.type) {
1881 designator = allocate_ast_zero(sizeof(designator[0]));
1882 designator->source_position = token.source_position;
1884 add_anchor_token(']');
1885 designator->array_index = parse_constant_expression();
1886 rem_anchor_token(']');
1890 designator = allocate_ast_zero(sizeof(designator[0]));
1891 designator->source_position = token.source_position;
1893 if (token.type != T_IDENTIFIER) {
1894 parse_error_expected("while parsing designator",
1895 T_IDENTIFIER, NULL);
1898 designator->symbol = token.v.symbol;
1906 assert(designator != NULL);
1908 last->next = designator;
1910 result = designator;
1918 static initializer_t *initializer_from_string(array_type_t *type,
1919 const string_t *const string)
1921 /* TODO: check len vs. size of array type */
1924 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1925 initializer->string.string = *string;
1930 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1931 wide_string_t *const string)
1933 /* TODO: check len vs. size of array type */
1936 initializer_t *const initializer =
1937 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1938 initializer->wide_string.string = *string;
1944 * Build an initializer from a given expression.
1946 static initializer_t *initializer_from_expression(type_t *orig_type,
1947 expression_t *expression)
1949 /* TODO check that expression is a constant expression */
1951 /* § 6.7.8.14/15 char array may be initialized by string literals */
1952 type_t *type = skip_typeref(orig_type);
1953 type_t *expr_type_orig = expression->base.type;
1954 type_t *expr_type = skip_typeref(expr_type_orig);
1955 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1956 array_type_t *const array_type = &type->array;
1957 type_t *const element_type = skip_typeref(array_type->element_type);
1959 if (element_type->kind == TYPE_ATOMIC) {
1960 atomic_type_kind_t akind = element_type->atomic.akind;
1961 switch (expression->kind) {
1962 case EXPR_STRING_LITERAL:
1963 if (akind == ATOMIC_TYPE_CHAR
1964 || akind == ATOMIC_TYPE_SCHAR
1965 || akind == ATOMIC_TYPE_UCHAR) {
1966 return initializer_from_string(array_type,
1967 &expression->string.value);
1970 case EXPR_WIDE_STRING_LITERAL: {
1971 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1972 if (get_unqualified_type(element_type) == bare_wchar_type) {
1973 return initializer_from_wide_string(array_type,
1974 &expression->wide_string.value);
1984 assign_error_t error = semantic_assign(type, expression);
1985 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1987 report_assign_error(error, type, expression, "initializer",
1988 &expression->base.source_position);
1990 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1991 result->value.value = create_implicit_cast(expression, type);
1997 * Checks if a given expression can be used as an constant initializer.
1999 static bool is_initializer_constant(const expression_t *expression)
2001 return is_constant_expression(expression)
2002 || is_address_constant(expression);
2006 * Parses an scalar initializer.
2008 * § 6.7.8.11; eat {} without warning
2010 static initializer_t *parse_scalar_initializer(type_t *type,
2011 bool must_be_constant)
2013 /* there might be extra {} hierarchies */
2015 if (token.type == '{') {
2016 warningf(HERE, "extra curly braces around scalar initializer");
2020 } while (token.type == '{');
2023 expression_t *expression = parse_assignment_expression();
2024 if (must_be_constant && !is_initializer_constant(expression)) {
2025 errorf(&expression->base.source_position,
2026 "Initialisation expression '%E' is not constant\n",
2030 initializer_t *initializer = initializer_from_expression(type, expression);
2032 if (initializer == NULL) {
2033 errorf(&expression->base.source_position,
2034 "expression '%E' (type '%T') doesn't match expected type '%T'",
2035 expression, expression->base.type, type);
2040 bool additional_warning_displayed = false;
2041 while (braces > 0) {
2042 if (token.type == ',') {
2045 if (token.type != '}') {
2046 if (!additional_warning_displayed) {
2047 warningf(HERE, "additional elements in scalar initializer");
2048 additional_warning_displayed = true;
2059 * An entry in the type path.
2061 typedef struct type_path_entry_t type_path_entry_t;
2062 struct type_path_entry_t {
2063 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2065 size_t index; /**< For array types: the current index. */
2066 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2071 * A type path expression a position inside compound or array types.
2073 typedef struct type_path_t type_path_t;
2074 struct type_path_t {
2075 type_path_entry_t *path; /**< An flexible array containing the current path. */
2076 type_t *top_type; /**< type of the element the path points */
2077 size_t max_index; /**< largest index in outermost array */
2081 * Prints a type path for debugging.
2083 static __attribute__((unused)) void debug_print_type_path(
2084 const type_path_t *path)
2086 size_t len = ARR_LEN(path->path);
2088 for(size_t i = 0; i < len; ++i) {
2089 const type_path_entry_t *entry = & path->path[i];
2091 type_t *type = skip_typeref(entry->type);
2092 if (is_type_compound(type)) {
2093 /* in gcc mode structs can have no members */
2094 if (entry->v.compound_entry == NULL) {
2098 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2099 } else if (is_type_array(type)) {
2100 fprintf(stderr, "[%zu]", entry->v.index);
2102 fprintf(stderr, "-INVALID-");
2105 if (path->top_type != NULL) {
2106 fprintf(stderr, " (");
2107 print_type(path->top_type);
2108 fprintf(stderr, ")");
2113 * Return the top type path entry, ie. in a path
2114 * (type).a.b returns the b.
2116 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2118 size_t len = ARR_LEN(path->path);
2120 return &path->path[len-1];
2124 * Enlarge the type path by an (empty) element.
2126 static type_path_entry_t *append_to_type_path(type_path_t *path)
2128 size_t len = ARR_LEN(path->path);
2129 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2131 type_path_entry_t *result = & path->path[len];
2132 memset(result, 0, sizeof(result[0]));
2137 * Descending into a sub-type. Enter the scope of the current
2140 static void descend_into_subtype(type_path_t *path)
2142 type_t *orig_top_type = path->top_type;
2143 type_t *top_type = skip_typeref(orig_top_type);
2145 type_path_entry_t *top = append_to_type_path(path);
2146 top->type = top_type;
2148 if (is_type_compound(top_type)) {
2149 declaration_t *declaration = top_type->compound.declaration;
2150 declaration_t *entry = declaration->scope.declarations;
2151 top->v.compound_entry = entry;
2153 if (entry != NULL) {
2154 path->top_type = entry->type;
2156 path->top_type = NULL;
2158 } else if (is_type_array(top_type)) {
2160 path->top_type = top_type->array.element_type;
2162 assert(!is_type_valid(top_type));
2167 * Pop an entry from the given type path, ie. returning from
2168 * (type).a.b to (type).a
2170 static void ascend_from_subtype(type_path_t *path)
2172 type_path_entry_t *top = get_type_path_top(path);
2174 path->top_type = top->type;
2176 size_t len = ARR_LEN(path->path);
2177 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2181 * Pop entries from the given type path until the given
2182 * path level is reached.
2184 static void ascend_to(type_path_t *path, size_t top_path_level)
2186 size_t len = ARR_LEN(path->path);
2188 while (len > top_path_level) {
2189 ascend_from_subtype(path);
2190 len = ARR_LEN(path->path);
2194 static bool walk_designator(type_path_t *path, const designator_t *designator,
2195 bool used_in_offsetof)
2197 for( ; designator != NULL; designator = designator->next) {
2198 type_path_entry_t *top = get_type_path_top(path);
2199 type_t *orig_type = top->type;
2201 type_t *type = skip_typeref(orig_type);
2203 if (designator->symbol != NULL) {
2204 symbol_t *symbol = designator->symbol;
2205 if (!is_type_compound(type)) {
2206 if (is_type_valid(type)) {
2207 errorf(&designator->source_position,
2208 "'.%Y' designator used for non-compound type '%T'",
2214 declaration_t *declaration = type->compound.declaration;
2215 declaration_t *iter = declaration->scope.declarations;
2216 for( ; iter != NULL; iter = iter->next) {
2217 if (iter->symbol == symbol) {
2222 errorf(&designator->source_position,
2223 "'%T' has no member named '%Y'", orig_type, symbol);
2226 if (used_in_offsetof) {
2227 type_t *real_type = skip_typeref(iter->type);
2228 if (real_type->kind == TYPE_BITFIELD) {
2229 errorf(&designator->source_position,
2230 "offsetof designator '%Y' may not specify bitfield",
2236 top->type = orig_type;
2237 top->v.compound_entry = iter;
2238 orig_type = iter->type;
2240 expression_t *array_index = designator->array_index;
2241 assert(designator->array_index != NULL);
2243 if (!is_type_array(type)) {
2244 if (is_type_valid(type)) {
2245 errorf(&designator->source_position,
2246 "[%E] designator used for non-array type '%T'",
2247 array_index, orig_type);
2251 if (!is_type_valid(array_index->base.type)) {
2255 long index = fold_constant(array_index);
2256 if (!used_in_offsetof) {
2258 errorf(&designator->source_position,
2259 "array index [%E] must be positive", array_index);
2262 if (type->array.size_constant == true) {
2263 long array_size = type->array.size;
2264 if (index >= array_size) {
2265 errorf(&designator->source_position,
2266 "designator [%E] (%d) exceeds array size %d",
2267 array_index, index, array_size);
2273 top->type = orig_type;
2274 top->v.index = (size_t) index;
2275 orig_type = type->array.element_type;
2277 path->top_type = orig_type;
2279 if (designator->next != NULL) {
2280 descend_into_subtype(path);
2289 static void advance_current_object(type_path_t *path, size_t top_path_level)
2291 type_path_entry_t *top = get_type_path_top(path);
2293 type_t *type = skip_typeref(top->type);
2294 if (is_type_union(type)) {
2295 /* in unions only the first element is initialized */
2296 top->v.compound_entry = NULL;
2297 } else if (is_type_struct(type)) {
2298 declaration_t *entry = top->v.compound_entry;
2300 entry = entry->next;
2301 top->v.compound_entry = entry;
2302 if (entry != NULL) {
2303 path->top_type = entry->type;
2307 assert(is_type_array(type));
2311 if (!type->array.size_constant || top->v.index < type->array.size) {
2316 /* we're past the last member of the current sub-aggregate, try if we
2317 * can ascend in the type hierarchy and continue with another subobject */
2318 size_t len = ARR_LEN(path->path);
2320 if (len > top_path_level) {
2321 ascend_from_subtype(path);
2322 advance_current_object(path, top_path_level);
2324 path->top_type = NULL;
2329 * skip until token is found.
2331 static void skip_until(int type)
2333 while (token.type != type) {
2334 if (token.type == T_EOF)
2341 * skip any {...} blocks until a closing bracket is reached.
2343 static void skip_initializers(void)
2345 if (token.type == '{')
2348 while (token.type != '}') {
2349 if (token.type == T_EOF)
2351 if (token.type == '{') {
2359 static initializer_t *create_empty_initializer(void)
2361 static initializer_t empty_initializer
2362 = { .list = { { INITIALIZER_LIST }, 0 } };
2363 return &empty_initializer;
2367 * Parse a part of an initialiser for a struct or union,
2369 static initializer_t *parse_sub_initializer(type_path_t *path,
2370 type_t *outer_type, size_t top_path_level,
2371 parse_initializer_env_t *env)
2373 if (token.type == '}') {
2374 /* empty initializer */
2375 return create_empty_initializer();
2378 type_t *orig_type = path->top_type;
2379 type_t *type = NULL;
2381 if (orig_type == NULL) {
2382 /* We are initializing an empty compound. */
2384 type = skip_typeref(orig_type);
2386 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2387 * initializers in this case. */
2388 if (!is_type_valid(type)) {
2389 skip_initializers();
2390 return create_empty_initializer();
2394 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2397 designator_t *designator = NULL;
2398 if (token.type == '.' || token.type == '[') {
2399 designator = parse_designation();
2400 goto finish_designator;
2401 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2402 /* GNU-style designator ("identifier: value") */
2403 designator = allocate_ast_zero(sizeof(designator[0]));
2404 designator->source_position = token.source_position;
2405 designator->symbol = token.v.symbol;
2410 /* reset path to toplevel, evaluate designator from there */
2411 ascend_to(path, top_path_level);
2412 if (!walk_designator(path, designator, false)) {
2413 /* can't continue after designation error */
2417 initializer_t *designator_initializer
2418 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2419 designator_initializer->designator.designator = designator;
2420 ARR_APP1(initializer_t*, initializers, designator_initializer);
2422 orig_type = path->top_type;
2423 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2428 if (token.type == '{') {
2429 if (type != NULL && is_type_scalar(type)) {
2430 sub = parse_scalar_initializer(type, env->must_be_constant);
2434 if (env->declaration != NULL) {
2435 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2436 env->declaration->symbol);
2438 errorf(HERE, "extra brace group at end of initializer");
2441 descend_into_subtype(path);
2443 add_anchor_token('}');
2444 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2446 rem_anchor_token('}');
2449 ascend_from_subtype(path);
2453 goto error_parse_next;
2457 /* must be an expression */
2458 expression_t *expression = parse_assignment_expression();
2460 if (env->must_be_constant && !is_initializer_constant(expression)) {
2461 errorf(&expression->base.source_position,
2462 "Initialisation expression '%E' is not constant\n",
2467 /* we are already outside, ... */
2468 if (is_type_compound(outer_type) &&
2469 !outer_type->compound.declaration->init.complete) {
2470 goto error_parse_next;
2475 /* handle { "string" } special case */
2476 if ((expression->kind == EXPR_STRING_LITERAL
2477 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2478 && outer_type != NULL) {
2479 sub = initializer_from_expression(outer_type, expression);
2481 if (token.type == ',') {
2484 if (token.type != '}') {
2485 warningf(HERE, "excessive elements in initializer for type '%T'",
2488 /* TODO: eat , ... */
2493 /* descend into subtypes until expression matches type */
2495 orig_type = path->top_type;
2496 type = skip_typeref(orig_type);
2498 sub = initializer_from_expression(orig_type, expression);
2502 if (!is_type_valid(type)) {
2505 if (is_type_scalar(type)) {
2506 errorf(&expression->base.source_position,
2507 "expression '%E' doesn't match expected type '%T'",
2508 expression, orig_type);
2512 descend_into_subtype(path);
2516 /* update largest index of top array */
2517 const type_path_entry_t *first = &path->path[0];
2518 type_t *first_type = first->type;
2519 first_type = skip_typeref(first_type);
2520 if (is_type_array(first_type)) {
2521 size_t index = first->v.index;
2522 if (index > path->max_index)
2523 path->max_index = index;
2527 /* append to initializers list */
2528 ARR_APP1(initializer_t*, initializers, sub);
2531 if (env->declaration != NULL)
2532 warningf(HERE, "excess elements in struct initializer for '%Y'",
2533 env->declaration->symbol);
2535 warningf(HERE, "excess elements in struct initializer");
2539 if (token.type == '}') {
2543 if (token.type == '}') {
2548 /* advance to the next declaration if we are not at the end */
2549 advance_current_object(path, top_path_level);
2550 orig_type = path->top_type;
2551 if (orig_type != NULL)
2552 type = skip_typeref(orig_type);
2558 size_t len = ARR_LEN(initializers);
2559 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2560 initializer_t *result = allocate_ast_zero(size);
2561 result->kind = INITIALIZER_LIST;
2562 result->list.len = len;
2563 memcpy(&result->list.initializers, initializers,
2564 len * sizeof(initializers[0]));
2566 DEL_ARR_F(initializers);
2567 ascend_to(path, top_path_level+1);
2572 skip_initializers();
2573 DEL_ARR_F(initializers);
2574 ascend_to(path, top_path_level+1);
2579 * Parses an initializer. Parsers either a compound literal
2580 * (env->declaration == NULL) or an initializer of a declaration.
2582 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2584 type_t *type = skip_typeref(env->type);
2585 initializer_t *result = NULL;
2588 if (is_type_scalar(type)) {
2589 result = parse_scalar_initializer(type, env->must_be_constant);
2590 } else if (token.type == '{') {
2594 memset(&path, 0, sizeof(path));
2595 path.top_type = env->type;
2596 path.path = NEW_ARR_F(type_path_entry_t, 0);
2598 descend_into_subtype(&path);
2600 add_anchor_token('}');
2601 result = parse_sub_initializer(&path, env->type, 1, env);
2602 rem_anchor_token('}');
2604 max_index = path.max_index;
2605 DEL_ARR_F(path.path);
2609 /* parse_scalar_initializer() also works in this case: we simply
2610 * have an expression without {} around it */
2611 result = parse_scalar_initializer(type, env->must_be_constant);
2614 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2615 * the array type size */
2616 if (is_type_array(type) && type->array.size_expression == NULL
2617 && result != NULL) {
2619 switch (result->kind) {
2620 case INITIALIZER_LIST:
2621 size = max_index + 1;
2624 case INITIALIZER_STRING:
2625 size = result->string.string.size;
2628 case INITIALIZER_WIDE_STRING:
2629 size = result->wide_string.string.size;
2632 case INITIALIZER_DESIGNATOR:
2633 case INITIALIZER_VALUE:
2634 /* can happen for parse errors */
2639 internal_errorf(HERE, "invalid initializer type");
2642 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2643 cnst->base.type = type_size_t;
2644 cnst->conste.v.int_value = size;
2646 type_t *new_type = duplicate_type(type);
2648 new_type->array.size_expression = cnst;
2649 new_type->array.size_constant = true;
2650 new_type->array.size = size;
2651 env->type = new_type;
2659 static declaration_t *append_declaration(declaration_t *declaration);
2661 static declaration_t *parse_compound_type_specifier(bool is_struct)
2663 gnu_attribute_t *attributes = NULL;
2664 decl_modifiers_t modifiers = 0;
2671 symbol_t *symbol = NULL;
2672 declaration_t *declaration = NULL;
2674 if (token.type == T___attribute__) {
2675 modifiers |= parse_attributes(&attributes);
2678 if (token.type == T_IDENTIFIER) {
2679 symbol = token.v.symbol;
2682 namespace_t const namespc =
2683 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2684 declaration = get_declaration(symbol, namespc);
2685 if (declaration != NULL) {
2686 if (declaration->parent_scope != scope &&
2687 (token.type == '{' || token.type == ';')) {
2689 } else if (declaration->init.complete &&
2690 token.type == '{') {
2691 assert(symbol != NULL);
2692 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2693 is_struct ? "struct" : "union", symbol,
2694 &declaration->source_position);
2695 declaration->scope.declarations = NULL;
2698 } else if (token.type != '{') {
2700 parse_error_expected("while parsing struct type specifier",
2701 T_IDENTIFIER, '{', NULL);
2703 parse_error_expected("while parsing union type specifier",
2704 T_IDENTIFIER, '{', NULL);
2710 if (declaration == NULL) {
2711 declaration = allocate_declaration_zero();
2712 declaration->namespc =
2713 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2714 declaration->source_position = token.source_position;
2715 declaration->symbol = symbol;
2716 declaration->parent_scope = scope;
2717 if (symbol != NULL) {
2718 environment_push(declaration);
2720 append_declaration(declaration);
2723 if (token.type == '{') {
2724 declaration->init.complete = true;
2726 parse_compound_type_entries(declaration);
2727 modifiers |= parse_attributes(&attributes);
2730 declaration->modifiers |= modifiers;
2734 static void parse_enum_entries(type_t *const enum_type)
2738 if (token.type == '}') {
2740 errorf(HERE, "empty enum not allowed");
2744 add_anchor_token('}');
2746 if (token.type != T_IDENTIFIER) {
2747 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2749 rem_anchor_token('}');
2753 declaration_t *const entry = allocate_declaration_zero();
2754 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2755 entry->type = enum_type;
2756 entry->symbol = token.v.symbol;
2757 entry->source_position = token.source_position;
2760 if (token.type == '=') {
2762 expression_t *value = parse_constant_expression();
2764 value = create_implicit_cast(value, enum_type);
2765 entry->init.enum_value = value;
2770 record_declaration(entry, false);
2772 if (token.type != ',')
2775 } while (token.type != '}');
2776 rem_anchor_token('}');
2784 static type_t *parse_enum_specifier(void)
2786 gnu_attribute_t *attributes = NULL;
2787 declaration_t *declaration;
2791 if (token.type == T_IDENTIFIER) {
2792 symbol = token.v.symbol;
2795 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2796 } else if (token.type != '{') {
2797 parse_error_expected("while parsing enum type specifier",
2798 T_IDENTIFIER, '{', NULL);
2805 if (declaration == NULL) {
2806 declaration = allocate_declaration_zero();
2807 declaration->namespc = NAMESPACE_ENUM;
2808 declaration->source_position = token.source_position;
2809 declaration->symbol = symbol;
2810 declaration->parent_scope = scope;
2813 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2814 type->enumt.declaration = declaration;
2816 if (token.type == '{') {
2817 if (declaration->init.complete) {
2818 errorf(HERE, "multiple definitions of enum %Y", symbol);
2820 if (symbol != NULL) {
2821 environment_push(declaration);
2823 append_declaration(declaration);
2824 declaration->init.complete = true;
2826 parse_enum_entries(type);
2827 parse_attributes(&attributes);
2834 * if a symbol is a typedef to another type, return true
2836 static bool is_typedef_symbol(symbol_t *symbol)
2838 const declaration_t *const declaration =
2839 get_declaration(symbol, NAMESPACE_NORMAL);
2841 declaration != NULL &&
2842 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2845 static type_t *parse_typeof(void)
2852 add_anchor_token(')');
2854 expression_t *expression = NULL;
2857 switch(token.type) {
2858 case T___extension__:
2859 /* This can be a prefix to a typename or an expression. We simply eat
2863 } while (token.type == T___extension__);
2867 if (is_typedef_symbol(token.v.symbol)) {
2868 type = parse_typename();
2870 expression = parse_expression();
2871 type = expression->base.type;
2876 type = parse_typename();
2880 expression = parse_expression();
2881 type = expression->base.type;
2885 rem_anchor_token(')');
2888 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2889 typeof_type->typeoft.expression = expression;
2890 typeof_type->typeoft.typeof_type = type;
2897 typedef enum specifiers_t {
2898 SPECIFIER_SIGNED = 1 << 0,
2899 SPECIFIER_UNSIGNED = 1 << 1,
2900 SPECIFIER_LONG = 1 << 2,
2901 SPECIFIER_INT = 1 << 3,
2902 SPECIFIER_DOUBLE = 1 << 4,
2903 SPECIFIER_CHAR = 1 << 5,
2904 SPECIFIER_SHORT = 1 << 6,
2905 SPECIFIER_LONG_LONG = 1 << 7,
2906 SPECIFIER_FLOAT = 1 << 8,
2907 SPECIFIER_BOOL = 1 << 9,
2908 SPECIFIER_VOID = 1 << 10,
2909 SPECIFIER_INT8 = 1 << 11,
2910 SPECIFIER_INT16 = 1 << 12,
2911 SPECIFIER_INT32 = 1 << 13,
2912 SPECIFIER_INT64 = 1 << 14,
2913 SPECIFIER_INT128 = 1 << 15,
2914 SPECIFIER_COMPLEX = 1 << 16,
2915 SPECIFIER_IMAGINARY = 1 << 17,
2918 static type_t *create_builtin_type(symbol_t *const symbol,
2919 type_t *const real_type)
2921 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2922 type->builtin.symbol = symbol;
2923 type->builtin.real_type = real_type;
2925 type_t *result = typehash_insert(type);
2926 if (type != result) {
2933 static type_t *get_typedef_type(symbol_t *symbol)
2935 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2936 if (declaration == NULL ||
2937 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2940 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2941 type->typedeft.declaration = declaration;
2947 * check for the allowed MS alignment values.
2949 static bool check_alignment_value(long long intvalue)
2951 if (intvalue < 1 || intvalue > 8192) {
2952 errorf(HERE, "illegal alignment value");
2955 unsigned v = (unsigned)intvalue;
2956 for(unsigned i = 1; i <= 8192; i += i) {
2960 errorf(HERE, "alignment must be power of two");
2964 #define DET_MOD(name, tag) do { \
2965 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2966 *modifiers |= tag; \
2969 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2971 decl_modifiers_t *modifiers = &specifiers->modifiers;
2974 if (token.type == T_restrict) {
2976 DET_MOD(restrict, DM_RESTRICT);
2978 } else if (token.type != T_IDENTIFIER)
2980 symbol_t *symbol = token.v.symbol;
2981 if (symbol == sym_align) {
2984 if (token.type != T_INTEGER)
2986 if (check_alignment_value(token.v.intvalue)) {
2987 if (specifiers->alignment != 0)
2988 warningf(HERE, "align used more than once");
2989 specifiers->alignment = (unsigned char)token.v.intvalue;
2993 } else if (symbol == sym_allocate) {
2996 if (token.type != T_IDENTIFIER)
2998 (void)token.v.symbol;
3000 } else if (symbol == sym_dllimport) {
3002 DET_MOD(dllimport, DM_DLLIMPORT);
3003 } else if (symbol == sym_dllexport) {
3005 DET_MOD(dllexport, DM_DLLEXPORT);
3006 } else if (symbol == sym_thread) {
3008 DET_MOD(thread, DM_THREAD);
3009 } else if (symbol == sym_naked) {
3011 DET_MOD(naked, DM_NAKED);
3012 } else if (symbol == sym_noinline) {
3014 DET_MOD(noinline, DM_NOINLINE);
3015 } else if (symbol == sym_noreturn) {
3017 DET_MOD(noreturn, DM_NORETURN);
3018 } else if (symbol == sym_nothrow) {
3020 DET_MOD(nothrow, DM_NOTHROW);
3021 } else if (symbol == sym_novtable) {
3023 DET_MOD(novtable, DM_NOVTABLE);
3024 } else if (symbol == sym_property) {
3028 bool is_get = false;
3029 if (token.type != T_IDENTIFIER)
3031 if (token.v.symbol == sym_get) {
3033 } else if (token.v.symbol == sym_put) {
3035 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3040 if (token.type != T_IDENTIFIER)
3043 if (specifiers->get_property_sym != NULL) {
3044 errorf(HERE, "get property name already specified");
3046 specifiers->get_property_sym = token.v.symbol;
3049 if (specifiers->put_property_sym != NULL) {
3050 errorf(HERE, "put property name already specified");
3052 specifiers->put_property_sym = token.v.symbol;
3056 if (token.type == ',') {
3063 } else if (symbol == sym_selectany) {
3065 DET_MOD(selectany, DM_SELECTANY);
3066 } else if (symbol == sym_uuid) {
3069 if (token.type != T_STRING_LITERAL)
3073 } else if (symbol == sym_deprecated) {
3075 if (specifiers->deprecated != 0)
3076 warningf(HERE, "deprecated used more than once");
3077 specifiers->deprecated = 1;
3078 if (token.type == '(') {
3080 if (token.type == T_STRING_LITERAL) {
3081 specifiers->deprecated_string = token.v.string.begin;
3084 errorf(HERE, "string literal expected");
3088 } else if (symbol == sym_noalias) {
3090 DET_MOD(noalias, DM_NOALIAS);
3092 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3094 if (token.type == '(')
3098 if (token.type == ',')
3105 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3107 declaration_t *const decl = allocate_declaration_zero();
3108 decl->source_position = *HERE;
3109 decl->declared_storage_class = storage_class;
3110 decl->storage_class =
3111 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3112 storage_class : STORAGE_CLASS_AUTO;
3113 decl->symbol = symbol;
3114 decl->implicit = true;
3115 record_declaration(decl, false);
3120 * Finish the construction of a struct type by calculating
3121 * its size, offsets, alignment.
3123 static void finish_struct_type(compound_type_t *type) {
3124 if (type->declaration == NULL)
3126 declaration_t *struct_decl = type->declaration;
3127 if (! struct_decl->init.complete)
3132 il_alignment_t alignment = 1;
3133 bool need_pad = false;
3135 declaration_t *entry = struct_decl->scope.declarations;
3136 for (; entry != NULL; entry = entry->next) {
3137 if (entry->namespc != NAMESPACE_NORMAL)
3140 type_t *m_type = skip_typeref(entry->type);
3141 if (! is_type_valid(m_type)) {
3142 /* simply ignore errors here */
3145 il_alignment_t m_alignment = m_type->base.alignment;
3146 if (m_alignment > alignment)
3147 alignment = m_alignment;
3149 offset = (size + m_alignment - 1) & -m_alignment;
3153 entry->offset = offset;
3154 size = offset + m_type->base.size;
3156 if (type->base.alignment != 0) {
3157 alignment = type->base.alignment;
3160 offset = (size + alignment - 1) & -alignment;
3164 if (warning.padded && need_pad) {
3165 warningf(&struct_decl->source_position,
3166 "'%#T' needs padding", type, struct_decl->symbol);
3168 if (warning.packed && !need_pad) {
3169 warningf(&struct_decl->source_position,
3170 "superfluous packed attribute on '%#T'",
3171 type, struct_decl->symbol);
3174 type->base.size = offset;
3175 type->base.alignment = alignment;
3179 * Finish the construction of an union type by calculating
3180 * its size and alignment.
3182 static void finish_union_type(compound_type_t *type) {
3183 if (type->declaration == NULL)
3185 declaration_t *union_decl = type->declaration;
3186 if (! union_decl->init.complete)
3190 il_alignment_t alignment = 1;
3192 declaration_t *entry = union_decl->scope.declarations;
3193 for (; entry != NULL; entry = entry->next) {
3194 if (entry->namespc != NAMESPACE_NORMAL)
3197 type_t *m_type = skip_typeref(entry->type);
3198 if (! is_type_valid(m_type))
3202 if (m_type->base.size > size)
3203 size = m_type->base.size;
3204 if (m_type->base.alignment > alignment)
3205 alignment = m_type->base.alignment;
3207 if (type->base.alignment != 0) {
3208 alignment = type->base.alignment;
3210 size = (size + alignment - 1) & -alignment;
3211 type->base.size = size;
3212 type->base.alignment = alignment;
3215 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3217 type_t *type = NULL;
3218 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3219 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3220 unsigned type_specifiers = 0;
3221 bool newtype = false;
3222 bool saw_error = false;
3224 specifiers->source_position = token.source_position;
3227 specifiers->modifiers
3228 |= parse_attributes(&specifiers->gnu_attributes);
3229 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3230 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3232 switch(token.type) {
3235 #define MATCH_STORAGE_CLASS(token, class) \
3237 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3238 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3240 specifiers->declared_storage_class = class; \
3244 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3245 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3246 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3247 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3248 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3253 add_anchor_token(')');
3254 parse_microsoft_extended_decl_modifier(specifiers);
3255 rem_anchor_token(')');
3260 switch (specifiers->declared_storage_class) {
3261 case STORAGE_CLASS_NONE:
3262 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3265 case STORAGE_CLASS_EXTERN:
3266 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3269 case STORAGE_CLASS_STATIC:
3270 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3274 errorf(HERE, "multiple storage classes in declaration specifiers");
3280 /* type qualifiers */
3281 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3283 qualifiers |= qualifier; \
3287 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3288 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3289 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3290 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3291 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3292 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3293 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3294 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3296 case T___extension__:
3301 /* type specifiers */
3302 #define MATCH_SPECIFIER(token, specifier, name) \
3305 if (type_specifiers & specifier) { \
3306 errorf(HERE, "multiple " name " type specifiers given"); \
3308 type_specifiers |= specifier; \
3312 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3313 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3314 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3315 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3316 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3317 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3318 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3319 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3320 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3321 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3322 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3323 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3324 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3325 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3326 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3327 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3329 case T__forceinline:
3330 /* only in microsoft mode */
3331 specifiers->modifiers |= DM_FORCEINLINE;
3336 specifiers->is_inline = true;
3341 if (type_specifiers & SPECIFIER_LONG_LONG) {
3342 errorf(HERE, "multiple type specifiers given");
3343 } else if (type_specifiers & SPECIFIER_LONG) {
3344 type_specifiers |= SPECIFIER_LONG_LONG;
3346 type_specifiers |= SPECIFIER_LONG;
3351 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3353 type->compound.declaration = parse_compound_type_specifier(true);
3354 finish_struct_type(&type->compound);
3358 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3359 type->compound.declaration = parse_compound_type_specifier(false);
3360 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3361 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3363 finish_union_type(&type->compound);
3366 type = parse_enum_specifier();
3369 type = parse_typeof();
3371 case T___builtin_va_list:
3372 type = duplicate_type(type_valist);
3376 case T_IDENTIFIER: {
3377 /* only parse identifier if we haven't found a type yet */
3378 if (type != NULL || type_specifiers != 0) {
3379 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3380 * declaration, so it doesn't generate errors about expecting '(' or
3382 switch (look_ahead(1)->type) {
3389 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3392 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3397 goto finish_specifiers;
3401 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3402 if (typedef_type == NULL) {
3403 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3404 * declaration, so it doesn't generate 'implicit int' followed by more
3405 * errors later on. */
3406 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3411 errorf(HERE, "%K does not name a type", &token);
3413 declaration_t *const decl =
3414 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3416 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3417 type->typedeft.declaration = decl;
3421 if (la1_type == '*')
3422 goto finish_specifiers;
3427 goto finish_specifiers;
3432 type = typedef_type;
3436 /* function specifier */
3438 goto finish_specifiers;
3443 if (type == NULL || (saw_error && type_specifiers != 0)) {
3444 atomic_type_kind_t atomic_type;
3446 /* match valid basic types */
3447 switch(type_specifiers) {
3448 case SPECIFIER_VOID:
3449 atomic_type = ATOMIC_TYPE_VOID;
3451 case SPECIFIER_CHAR:
3452 atomic_type = ATOMIC_TYPE_CHAR;
3454 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3455 atomic_type = ATOMIC_TYPE_SCHAR;
3457 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3458 atomic_type = ATOMIC_TYPE_UCHAR;
3460 case SPECIFIER_SHORT:
3461 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3462 case SPECIFIER_SHORT | SPECIFIER_INT:
3463 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3464 atomic_type = ATOMIC_TYPE_SHORT;
3466 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3467 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3468 atomic_type = ATOMIC_TYPE_USHORT;
3471 case SPECIFIER_SIGNED:
3472 case SPECIFIER_SIGNED | SPECIFIER_INT:
3473 atomic_type = ATOMIC_TYPE_INT;
3475 case SPECIFIER_UNSIGNED:
3476 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3477 atomic_type = ATOMIC_TYPE_UINT;
3479 case SPECIFIER_LONG:
3480 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3481 case SPECIFIER_LONG | SPECIFIER_INT:
3482 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3483 atomic_type = ATOMIC_TYPE_LONG;
3485 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3486 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3487 atomic_type = ATOMIC_TYPE_ULONG;
3490 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3491 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3492 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3493 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3495 atomic_type = ATOMIC_TYPE_LONGLONG;
3496 goto warn_about_long_long;
3498 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3499 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3501 atomic_type = ATOMIC_TYPE_ULONGLONG;
3502 warn_about_long_long:
3503 if (warning.long_long) {
3504 warningf(&specifiers->source_position,
3505 "ISO C90 does not support 'long long'");
3509 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3510 atomic_type = unsigned_int8_type_kind;
3513 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3514 atomic_type = unsigned_int16_type_kind;
3517 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3518 atomic_type = unsigned_int32_type_kind;
3521 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3522 atomic_type = unsigned_int64_type_kind;
3525 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3526 atomic_type = unsigned_int128_type_kind;
3529 case SPECIFIER_INT8:
3530 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3531 atomic_type = int8_type_kind;
3534 case SPECIFIER_INT16:
3535 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3536 atomic_type = int16_type_kind;
3539 case SPECIFIER_INT32:
3540 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3541 atomic_type = int32_type_kind;
3544 case SPECIFIER_INT64:
3545 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3546 atomic_type = int64_type_kind;
3549 case SPECIFIER_INT128:
3550 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3551 atomic_type = int128_type_kind;
3554 case SPECIFIER_FLOAT:
3555 atomic_type = ATOMIC_TYPE_FLOAT;
3557 case SPECIFIER_DOUBLE:
3558 atomic_type = ATOMIC_TYPE_DOUBLE;
3560 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3561 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3563 case SPECIFIER_BOOL:
3564 atomic_type = ATOMIC_TYPE_BOOL;
3566 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3567 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3568 atomic_type = ATOMIC_TYPE_FLOAT;
3570 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3571 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3572 atomic_type = ATOMIC_TYPE_DOUBLE;
3574 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3575 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3576 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3579 /* invalid specifier combination, give an error message */
3580 if (type_specifiers == 0) {
3585 if (warning.implicit_int) {
3586 warningf(HERE, "no type specifiers in declaration, using 'int'");
3588 atomic_type = ATOMIC_TYPE_INT;
3591 errorf(HERE, "no type specifiers given in declaration");
3593 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3594 (type_specifiers & SPECIFIER_UNSIGNED)) {
3595 errorf(HERE, "signed and unsigned specifiers given");
3596 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3597 errorf(HERE, "only integer types can be signed or unsigned");
3599 errorf(HERE, "multiple datatypes in declaration");
3604 if (type_specifiers & SPECIFIER_COMPLEX) {
3605 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3606 type->complex.akind = atomic_type;
3607 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3608 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3609 type->imaginary.akind = atomic_type;
3611 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3612 type->atomic.akind = atomic_type;
3615 } else if (type_specifiers != 0) {
3616 errorf(HERE, "multiple datatypes in declaration");
3619 /* FIXME: check type qualifiers here */
3621 type->base.qualifiers = qualifiers;
3622 type->base.modifiers = modifiers;
3624 type_t *result = typehash_insert(type);
3625 if (newtype && result != type) {
3629 specifiers->type = result;
3633 specifiers->type = type_error_type;
3637 static type_qualifiers_t parse_type_qualifiers(void)
3639 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3642 switch(token.type) {
3643 /* type qualifiers */
3644 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3645 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3646 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3647 /* microsoft extended type modifiers */
3648 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3649 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3650 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3651 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3652 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3660 static declaration_t *parse_identifier_list(void)
3662 declaration_t *declarations = NULL;
3663 declaration_t *last_declaration = NULL;
3665 declaration_t *const declaration = allocate_declaration_zero();
3666 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3667 declaration->source_position = token.source_position;
3668 declaration->symbol = token.v.symbol;
3671 if (last_declaration != NULL) {
3672 last_declaration->next = declaration;
3674 declarations = declaration;
3676 last_declaration = declaration;
3678 if (token.type != ',') {
3682 } while (token.type == T_IDENTIFIER);
3684 return declarations;
3687 static type_t *automatic_type_conversion(type_t *orig_type);
3689 static void semantic_parameter(declaration_t *declaration)
3691 /* TODO: improve error messages */
3692 source_position_t const* const pos = &declaration->source_position;
3694 switch (declaration->declared_storage_class) {
3695 case STORAGE_CLASS_TYPEDEF:
3696 errorf(pos, "typedef not allowed in parameter list");
3699 /* Allowed storage classes */
3700 case STORAGE_CLASS_NONE:
3701 case STORAGE_CLASS_REGISTER:
3705 errorf(pos, "parameter may only have none or register storage class");
3709 type_t *const orig_type = declaration->type;
3710 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3711 * sugar. Turn it into a pointer.
3712 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3713 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3715 type_t *const type = automatic_type_conversion(orig_type);
3716 declaration->type = type;
3718 if (is_type_incomplete(skip_typeref(type))) {
3719 errorf(pos, "parameter '%#T' is of incomplete type",
3720 orig_type, declaration->symbol);
3724 static declaration_t *parse_parameter(void)
3726 declaration_specifiers_t specifiers;
3727 memset(&specifiers, 0, sizeof(specifiers));
3729 parse_declaration_specifiers(&specifiers);
3731 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3736 static declaration_t *parse_parameters(function_type_t *type)
3738 declaration_t *declarations = NULL;
3741 add_anchor_token(')');
3742 int saved_comma_state = save_and_reset_anchor_state(',');
3744 if (token.type == T_IDENTIFIER &&
3745 !is_typedef_symbol(token.v.symbol)) {
3746 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3747 if (la1_type == ',' || la1_type == ')') {
3748 type->kr_style_parameters = true;
3749 declarations = parse_identifier_list();
3750 goto parameters_finished;
3754 if (token.type == ')') {
3755 type->unspecified_parameters = 1;
3756 goto parameters_finished;
3759 declaration_t *declaration;
3760 declaration_t *last_declaration = NULL;
3761 function_parameter_t *parameter;
3762 function_parameter_t *last_parameter = NULL;
3765 switch(token.type) {
3769 goto parameters_finished;
3772 case T___extension__:
3774 declaration = parse_parameter();
3776 /* func(void) is not a parameter */
3777 if (last_parameter == NULL
3778 && token.type == ')'
3779 && declaration->symbol == NULL
3780 && skip_typeref(declaration->type) == type_void) {
3781 goto parameters_finished;
3783 semantic_parameter(declaration);
3785 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3786 memset(parameter, 0, sizeof(parameter[0]));
3787 parameter->type = declaration->type;
3789 if (last_parameter != NULL) {
3790 last_declaration->next = declaration;
3791 last_parameter->next = parameter;
3793 type->parameters = parameter;
3794 declarations = declaration;
3796 last_parameter = parameter;
3797 last_declaration = declaration;
3801 goto parameters_finished;
3803 if (token.type != ',') {
3804 goto parameters_finished;
3810 parameters_finished:
3811 rem_anchor_token(')');
3814 restore_anchor_state(',', saved_comma_state);
3815 return declarations;
3818 restore_anchor_state(',', saved_comma_state);
3822 typedef enum construct_type_kind_t {
3827 } construct_type_kind_t;
3829 typedef struct construct_type_t construct_type_t;
3830 struct construct_type_t {
3831 construct_type_kind_t kind;
3832 construct_type_t *next;
3835 typedef struct parsed_pointer_t parsed_pointer_t;
3836 struct parsed_pointer_t {
3837 construct_type_t construct_type;
3838 type_qualifiers_t type_qualifiers;
3841 typedef struct construct_function_type_t construct_function_type_t;
3842 struct construct_function_type_t {
3843 construct_type_t construct_type;
3844 type_t *function_type;
3847 typedef struct parsed_array_t parsed_array_t;
3848 struct parsed_array_t {
3849 construct_type_t construct_type;
3850 type_qualifiers_t type_qualifiers;
3856 typedef struct construct_base_type_t construct_base_type_t;
3857 struct construct_base_type_t {
3858 construct_type_t construct_type;
3862 static construct_type_t *parse_pointer_declarator(void)
3866 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3867 memset(pointer, 0, sizeof(pointer[0]));
3868 pointer->construct_type.kind = CONSTRUCT_POINTER;
3869 pointer->type_qualifiers = parse_type_qualifiers();
3871 return (construct_type_t*) pointer;
3874 static construct_type_t *parse_array_declarator(void)
3877 add_anchor_token(']');
3879 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3880 memset(array, 0, sizeof(array[0]));
3881 array->construct_type.kind = CONSTRUCT_ARRAY;
3883 if (token.type == T_static) {
3884 array->is_static = true;
3888 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3889 if (type_qualifiers != 0) {
3890 if (token.type == T_static) {
3891 array->is_static = true;
3895 array->type_qualifiers = type_qualifiers;
3897 if (token.type == '*' && look_ahead(1)->type == ']') {
3898 array->is_variable = true;
3900 } else if (token.type != ']') {
3901 array->size = parse_assignment_expression();
3904 rem_anchor_token(']');
3908 return (construct_type_t*) array;
3911 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3914 if (declaration != NULL) {
3915 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3917 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3919 if (mask & (mask-1)) {
3920 const char *first = NULL, *second = NULL;
3922 /* more than one calling convention set */
3923 if (declaration->modifiers & DM_CDECL) {
3924 if (first == NULL) first = "cdecl";
3925 else if (second == NULL) second = "cdecl";
3927 if (declaration->modifiers & DM_STDCALL) {
3928 if (first == NULL) first = "stdcall";
3929 else if (second == NULL) second = "stdcall";
3931 if (declaration->modifiers & DM_FASTCALL) {
3932 if (first == NULL) first = "fastcall";
3933 else if (second == NULL) second = "fastcall";
3935 if (declaration->modifiers & DM_THISCALL) {
3936 if (first == NULL) first = "thiscall";
3937 else if (second == NULL) second = "thiscall";
3939 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3942 if (declaration->modifiers & DM_CDECL)
3943 type->function.calling_convention = CC_CDECL;
3944 else if (declaration->modifiers & DM_STDCALL)
3945 type->function.calling_convention = CC_STDCALL;
3946 else if (declaration->modifiers & DM_FASTCALL)
3947 type->function.calling_convention = CC_FASTCALL;
3948 else if (declaration->modifiers & DM_THISCALL)
3949 type->function.calling_convention = CC_THISCALL;
3951 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3954 declaration_t *parameters = parse_parameters(&type->function);
3955 if (declaration != NULL) {
3956 declaration->scope.declarations = parameters;
3959 construct_function_type_t *construct_function_type =
3960 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3961 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3962 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3963 construct_function_type->function_type = type;
3965 return &construct_function_type->construct_type;
3968 static void fix_declaration_type(declaration_t *declaration)
3970 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3971 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3973 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3974 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3976 if (declaration->type->base.modifiers == type_modifiers)
3979 type_t *copy = duplicate_type(declaration->type);
3980 copy->base.modifiers = type_modifiers;
3982 type_t *result = typehash_insert(copy);
3983 if (result != copy) {
3984 obstack_free(type_obst, copy);
3987 declaration->type = result;
3990 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3991 bool may_be_abstract)
3993 /* construct a single linked list of construct_type_t's which describe
3994 * how to construct the final declarator type */
3995 construct_type_t *first = NULL;
3996 construct_type_t *last = NULL;
3997 gnu_attribute_t *attributes = NULL;
3999 decl_modifiers_t modifiers = parse_attributes(&attributes);
4002 while (token.type == '*') {
4003 construct_type_t *type = parse_pointer_declarator();
4013 /* TODO: find out if this is correct */
4014 modifiers |= parse_attributes(&attributes);
4017 if (declaration != NULL)
4018 declaration->modifiers |= modifiers;
4020 construct_type_t *inner_types = NULL;
4022 switch(token.type) {
4024 if (declaration == NULL) {
4025 errorf(HERE, "no identifier expected in typename");
4027 declaration->symbol = token.v.symbol;
4028 declaration->source_position = token.source_position;
4034 add_anchor_token(')');
4035 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4036 if (inner_types != NULL) {
4037 /* All later declarators only modify the return type, not declaration */
4040 rem_anchor_token(')');
4044 if (may_be_abstract)
4046 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4051 construct_type_t *p = last;
4054 construct_type_t *type;
4055 switch(token.type) {
4057 type = parse_function_declarator(declaration);
4060 type = parse_array_declarator();
4063 goto declarator_finished;
4066 /* insert in the middle of the list (behind p) */
4068 type->next = p->next;
4079 declarator_finished:
4080 /* append inner_types at the end of the list, we don't to set last anymore
4081 * as it's not needed anymore */
4083 assert(first == NULL);
4084 first = inner_types;
4086 last->next = inner_types;
4094 static void parse_declaration_attributes(declaration_t *declaration)
4096 gnu_attribute_t *attributes = NULL;
4097 decl_modifiers_t modifiers = parse_attributes(&attributes);
4099 if (declaration == NULL)
4102 declaration->modifiers |= modifiers;
4103 /* check if we have these stupid mode attributes... */
4104 type_t *old_type = declaration->type;
4105 if (old_type == NULL)
4108 gnu_attribute_t *attribute = attributes;
4109 for ( ; attribute != NULL; attribute = attribute->next) {
4110 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4113 atomic_type_kind_t akind = attribute->u.akind;
4114 if (!is_type_signed(old_type)) {
4116 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4117 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4118 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4119 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4121 panic("invalid akind in mode attribute");
4125 = make_atomic_type(akind, old_type->base.qualifiers);
4129 static type_t *construct_declarator_type(construct_type_t *construct_list,
4132 construct_type_t *iter = construct_list;
4133 for( ; iter != NULL; iter = iter->next) {
4134 switch(iter->kind) {
4135 case CONSTRUCT_INVALID:
4136 internal_errorf(HERE, "invalid type construction found");
4137 case CONSTRUCT_FUNCTION: {
4138 construct_function_type_t *construct_function_type
4139 = (construct_function_type_t*) iter;
4141 type_t *function_type = construct_function_type->function_type;
4143 function_type->function.return_type = type;
4145 type_t *skipped_return_type = skip_typeref(type);
4147 if (is_type_function(skipped_return_type)) {
4148 errorf(HERE, "function returning function is not allowed");
4149 } else if (is_type_array(skipped_return_type)) {
4150 errorf(HERE, "function returning array is not allowed");
4152 if (skipped_return_type->base.qualifiers != 0) {
4154 "type qualifiers in return type of function type are meaningless");
4158 type = function_type;
4162 case CONSTRUCT_POINTER: {
4163 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4164 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4165 pointer_type->pointer.points_to = type;
4166 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4168 type = pointer_type;
4172 case CONSTRUCT_ARRAY: {
4173 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4174 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4176 expression_t *size_expression = parsed_array->size;
4177 if (size_expression != NULL) {
4179 = create_implicit_cast(size_expression, type_size_t);
4182 array_type->base.qualifiers = parsed_array->type_qualifiers;
4183 array_type->array.element_type = type;
4184 array_type->array.is_static = parsed_array->is_static;
4185 array_type->array.is_variable = parsed_array->is_variable;
4186 array_type->array.size_expression = size_expression;
4188 if (size_expression != NULL) {
4189 if (is_constant_expression(size_expression)) {
4190 array_type->array.size_constant = true;
4191 array_type->array.size
4192 = fold_constant(size_expression);
4194 array_type->array.is_vla = true;
4198 type_t *skipped_type = skip_typeref(type);
4200 if (is_type_incomplete(skipped_type)) {
4201 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4202 } else if (is_type_function(skipped_type)) {
4203 errorf(HERE, "array of functions is not allowed");
4210 type_t *hashed_type = typehash_insert(type);
4211 if (hashed_type != type) {
4212 /* the function type was constructed earlier freeing it here will
4213 * destroy other types... */
4214 if (iter->kind != CONSTRUCT_FUNCTION) {
4224 static declaration_t *parse_declarator(
4225 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4227 declaration_t *const declaration = allocate_declaration_zero();
4228 declaration->source_position = specifiers->source_position;
4229 declaration->declared_storage_class = specifiers->declared_storage_class;
4230 declaration->modifiers = specifiers->modifiers;
4231 declaration->deprecated_string = specifiers->deprecated_string;
4232 declaration->get_property_sym = specifiers->get_property_sym;
4233 declaration->put_property_sym = specifiers->put_property_sym;
4234 declaration->is_inline = specifiers->is_inline;
4236 declaration->storage_class = specifiers->declared_storage_class;
4237 if (declaration->storage_class == STORAGE_CLASS_NONE
4238 && scope != global_scope) {
4239 declaration->storage_class = STORAGE_CLASS_AUTO;
4242 if (specifiers->alignment != 0) {
4243 /* TODO: add checks here */
4244 declaration->alignment = specifiers->alignment;
4247 construct_type_t *construct_type
4248 = parse_inner_declarator(declaration, may_be_abstract);
4249 type_t *const type = specifiers->type;
4250 declaration->type = construct_declarator_type(construct_type, type);
4252 parse_declaration_attributes(declaration);
4254 fix_declaration_type(declaration);
4256 if (construct_type != NULL) {
4257 obstack_free(&temp_obst, construct_type);
4263 static type_t *parse_abstract_declarator(type_t *base_type)
4265 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4267 type_t *result = construct_declarator_type(construct_type, base_type);
4268 if (construct_type != NULL) {
4269 obstack_free(&temp_obst, construct_type);
4275 static declaration_t *append_declaration(declaration_t* const declaration)
4277 if (last_declaration != NULL) {
4278 last_declaration->next = declaration;
4280 scope->declarations = declaration;
4282 last_declaration = declaration;
4287 * Check if the declaration of main is suspicious. main should be a
4288 * function with external linkage, returning int, taking either zero
4289 * arguments, two, or three arguments of appropriate types, ie.
4291 * int main([ int argc, char **argv [, char **env ] ]).
4293 * @param decl the declaration to check
4294 * @param type the function type of the declaration
4296 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4298 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4299 warningf(&decl->source_position,
4300 "'main' is normally a non-static function");
4302 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4303 warningf(&decl->source_position,
4304 "return type of 'main' should be 'int', but is '%T'",
4305 func_type->return_type);
4307 const function_parameter_t *parm = func_type->parameters;
4309 type_t *const first_type = parm->type;
4310 if (!types_compatible(skip_typeref(first_type), type_int)) {
4311 warningf(&decl->source_position,
4312 "first argument of 'main' should be 'int', but is '%T'", first_type);
4316 type_t *const second_type = parm->type;
4317 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4318 warningf(&decl->source_position,
4319 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4323 type_t *const third_type = parm->type;
4324 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4325 warningf(&decl->source_position,
4326 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4330 goto warn_arg_count;
4334 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4340 * Check if a symbol is the equal to "main".
4342 static bool is_sym_main(const symbol_t *const sym)
4344 return strcmp(sym->string, "main") == 0;
4347 static declaration_t *record_declaration(
4348 declaration_t *const declaration,
4349 const bool is_definition)
4351 const symbol_t *const symbol = declaration->symbol;
4352 const namespace_t namespc = (namespace_t)declaration->namespc;
4354 assert(symbol != NULL);
4355 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4357 type_t *const orig_type = declaration->type;
4358 type_t *const type = skip_typeref(orig_type);
4359 if (is_type_function(type) &&
4360 type->function.unspecified_parameters &&
4361 warning.strict_prototypes &&
4362 previous_declaration == NULL) {
4363 warningf(&declaration->source_position,
4364 "function declaration '%#T' is not a prototype",
4368 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4369 check_type_of_main(declaration, &type->function);
4372 if (warning.nested_externs &&
4373 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4374 scope != global_scope) {
4375 warningf(&declaration->source_position,
4376 "nested extern declaration of '%#T'", declaration->type, symbol);
4379 assert(declaration != previous_declaration);
4380 if (previous_declaration != NULL
4381 && previous_declaration->parent_scope == scope) {
4382 /* can happen for K&R style declarations */
4383 if (previous_declaration->type == NULL) {
4384 previous_declaration->type = declaration->type;
4387 const type_t *prev_type = skip_typeref(previous_declaration->type);
4388 if (!types_compatible(type, prev_type)) {
4389 errorf(&declaration->source_position,
4390 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4391 orig_type, symbol, previous_declaration->type, symbol,
4392 &previous_declaration->source_position);
4394 unsigned old_storage_class = previous_declaration->storage_class;
4395 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4396 errorf(&declaration->source_position,
4397 "redeclaration of enum entry '%Y' (declared %P)",
4398 symbol, &previous_declaration->source_position);
4399 return previous_declaration;
4402 if (warning.redundant_decls &&
4404 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4405 !(previous_declaration->modifiers & DM_USED) &&
4406 !previous_declaration->used) {
4407 warningf(&previous_declaration->source_position,
4408 "unnecessary static forward declaration for '%#T'",
4409 previous_declaration->type, symbol);
4412 unsigned new_storage_class = declaration->storage_class;
4414 if (is_type_incomplete(prev_type)) {
4415 previous_declaration->type = type;
4419 /* pretend no storage class means extern for function
4420 * declarations (except if the previous declaration is neither
4421 * none nor extern) */
4422 if (is_type_function(type)) {
4423 if (prev_type->function.unspecified_parameters) {
4424 previous_declaration->type = type;
4428 switch (old_storage_class) {
4429 case STORAGE_CLASS_NONE:
4430 old_storage_class = STORAGE_CLASS_EXTERN;
4433 case STORAGE_CLASS_EXTERN:
4434 if (is_definition) {
4435 if (warning.missing_prototypes &&
4436 prev_type->function.unspecified_parameters &&
4437 !is_sym_main(symbol)) {
4438 warningf(&declaration->source_position,
4439 "no previous prototype for '%#T'",
4442 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4443 new_storage_class = STORAGE_CLASS_EXTERN;
4452 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4453 new_storage_class == STORAGE_CLASS_EXTERN) {
4454 warn_redundant_declaration:
4455 if (!is_definition &&
4456 warning.redundant_decls &&
4457 is_type_valid(prev_type) &&
4458 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4459 warningf(&declaration->source_position,
4460 "redundant declaration for '%Y' (declared %P)",
4461 symbol, &previous_declaration->source_position);
4463 } else if (current_function == NULL) {
4464 if (old_storage_class != STORAGE_CLASS_STATIC &&
4465 new_storage_class == STORAGE_CLASS_STATIC) {
4466 errorf(&declaration->source_position,
4467 "static declaration of '%Y' follows non-static declaration (declared %P)",
4468 symbol, &previous_declaration->source_position);
4469 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4470 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4471 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4473 goto warn_redundant_declaration;
4475 } else if (is_type_valid(prev_type)) {
4476 if (old_storage_class == new_storage_class) {
4477 errorf(&declaration->source_position,
4478 "redeclaration of '%Y' (declared %P)",
4479 symbol, &previous_declaration->source_position);
4481 errorf(&declaration->source_position,
4482 "redeclaration of '%Y' with different linkage (declared %P)",
4483 symbol, &previous_declaration->source_position);
4488 previous_declaration->modifiers |= declaration->modifiers;
4489 previous_declaration->is_inline |= declaration->is_inline;
4490 return previous_declaration;
4491 } else if (is_type_function(type)) {
4492 if (is_definition &&
4493 declaration->storage_class != STORAGE_CLASS_STATIC) {
4494 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4495 warningf(&declaration->source_position,
4496 "no previous prototype for '%#T'", orig_type, symbol);
4497 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4498 warningf(&declaration->source_position,
4499 "no previous declaration for '%#T'", orig_type,
4504 if (warning.missing_declarations &&
4505 scope == global_scope && (
4506 declaration->storage_class == STORAGE_CLASS_NONE ||
4507 declaration->storage_class == STORAGE_CLASS_THREAD
4509 warningf(&declaration->source_position,
4510 "no previous declaration for '%#T'", orig_type, symbol);
4514 assert(declaration->parent_scope == NULL);
4515 assert(scope != NULL);
4517 declaration->parent_scope = scope;
4519 environment_push(declaration);
4520 return append_declaration(declaration);
4523 static void parser_error_multiple_definition(declaration_t *declaration,
4524 const source_position_t *source_position)
4526 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4527 declaration->symbol, &declaration->source_position);
4530 static bool is_declaration_specifier(const token_t *token,
4531 bool only_specifiers_qualifiers)
4533 switch(token->type) {
4538 return is_typedef_symbol(token->v.symbol);
4540 case T___extension__:
4542 return !only_specifiers_qualifiers;
4549 static void parse_init_declarator_rest(declaration_t *declaration)
4553 type_t *orig_type = declaration->type;
4554 type_t *type = skip_typeref(orig_type);
4556 if (declaration->init.initializer != NULL) {
4557 parser_error_multiple_definition(declaration, HERE);
4560 bool must_be_constant = false;
4561 if (declaration->storage_class == STORAGE_CLASS_STATIC
4562 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4563 || declaration->parent_scope == global_scope) {
4564 must_be_constant = true;
4567 if (is_type_function(type)) {
4568 errorf(&declaration->source_position,
4569 "function '%#T' is initialized like a variable",
4570 orig_type, declaration->symbol);
4571 orig_type = type_error_type;
4574 parse_initializer_env_t env;
4575 env.type = orig_type;
4576 env.must_be_constant = must_be_constant;
4577 env.declaration = current_init_decl = declaration;
4579 initializer_t *initializer = parse_initializer(&env);
4580 current_init_decl = NULL;
4582 if (!is_type_function(type)) {
4583 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4584 * the array type size */
4585 declaration->type = env.type;
4586 declaration->init.initializer = initializer;
4590 /* parse rest of a declaration without any declarator */
4591 static void parse_anonymous_declaration_rest(
4592 const declaration_specifiers_t *specifiers)
4596 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4597 warningf(&specifiers->source_position,
4598 "useless storage class in empty declaration");
4601 type_t *type = specifiers->type;
4602 switch (type->kind) {
4603 case TYPE_COMPOUND_STRUCT:
4604 case TYPE_COMPOUND_UNION: {
4605 if (type->compound.declaration->symbol == NULL) {
4606 warningf(&specifiers->source_position,
4607 "unnamed struct/union that defines no instances");
4616 warningf(&specifiers->source_position, "empty declaration");
4620 #ifdef RECORD_EMPTY_DECLARATIONS
4621 declaration_t *const declaration = allocate_declaration_zero();
4622 declaration->type = specifiers->type;
4623 declaration->declared_storage_class = specifiers->declared_storage_class;
4624 declaration->source_position = specifiers->source_position;
4625 declaration->modifiers = specifiers->modifiers;
4626 declaration->storage_class = STORAGE_CLASS_NONE;
4628 append_declaration(declaration);
4632 static void parse_declaration_rest(declaration_t *ndeclaration,
4633 const declaration_specifiers_t *specifiers,
4634 parsed_declaration_func finished_declaration)
4636 add_anchor_token(';');
4637 add_anchor_token('=');
4638 add_anchor_token(',');
4640 declaration_t *declaration =
4641 finished_declaration(ndeclaration, token.type == '=');
4643 type_t *orig_type = declaration->type;
4644 type_t *type = skip_typeref(orig_type);
4646 if (type->kind != TYPE_FUNCTION &&
4647 declaration->is_inline &&
4648 is_type_valid(type)) {
4649 warningf(&declaration->source_position,
4650 "variable '%Y' declared 'inline'\n", declaration->symbol);
4653 if (token.type == '=') {
4654 parse_init_declarator_rest(declaration);
4657 if (token.type != ',')
4661 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4666 rem_anchor_token(';');
4667 rem_anchor_token('=');
4668 rem_anchor_token(',');
4671 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4673 symbol_t *symbol = declaration->symbol;
4674 if (symbol == NULL) {
4675 errorf(HERE, "anonymous declaration not valid as function parameter");
4678 namespace_t namespc = (namespace_t) declaration->namespc;
4679 if (namespc != NAMESPACE_NORMAL) {
4680 return record_declaration(declaration, false);
4683 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4684 if (previous_declaration == NULL ||
4685 previous_declaration->parent_scope != scope) {
4686 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4691 if (is_definition) {
4692 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4695 if (previous_declaration->type == NULL) {
4696 previous_declaration->type = declaration->type;
4697 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4698 previous_declaration->storage_class = declaration->storage_class;
4699 previous_declaration->parent_scope = scope;
4700 return previous_declaration;
4702 return record_declaration(declaration, false);
4706 static void parse_declaration(parsed_declaration_func finished_declaration)
4708 declaration_specifiers_t specifiers;
4709 memset(&specifiers, 0, sizeof(specifiers));
4711 add_anchor_token(';');
4712 parse_declaration_specifiers(&specifiers);
4713 rem_anchor_token(';');
4715 if (token.type == ';') {
4716 parse_anonymous_declaration_rest(&specifiers);
4718 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4719 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4723 static type_t *get_default_promoted_type(type_t *orig_type)
4725 type_t *result = orig_type;
4727 type_t *type = skip_typeref(orig_type);
4728 if (is_type_integer(type)) {
4729 result = promote_integer(type);
4730 } else if (type == type_float) {
4731 result = type_double;
4737 static void parse_kr_declaration_list(declaration_t *declaration)
4739 type_t *type = skip_typeref(declaration->type);
4740 if (!is_type_function(type))
4743 if (!type->function.kr_style_parameters)
4746 /* push function parameters */
4747 int top = environment_top();
4748 scope_t *last_scope = scope;
4749 set_scope(&declaration->scope);
4751 declaration_t *parameter = declaration->scope.declarations;
4752 for ( ; parameter != NULL; parameter = parameter->next) {
4753 assert(parameter->parent_scope == NULL);
4754 parameter->parent_scope = scope;
4755 environment_push(parameter);
4758 /* parse declaration list */
4759 while (is_declaration_specifier(&token, false)) {
4760 parse_declaration(finished_kr_declaration);
4763 /* pop function parameters */
4764 assert(scope == &declaration->scope);
4765 set_scope(last_scope);
4766 environment_pop_to(top);
4768 /* update function type */
4769 type_t *new_type = duplicate_type(type);
4771 function_parameter_t *parameters = NULL;
4772 function_parameter_t *last_parameter = NULL;
4774 declaration_t *parameter_declaration = declaration->scope.declarations;
4775 for( ; parameter_declaration != NULL;
4776 parameter_declaration = parameter_declaration->next) {
4777 type_t *parameter_type = parameter_declaration->type;
4778 if (parameter_type == NULL) {
4780 errorf(HERE, "no type specified for function parameter '%Y'",
4781 parameter_declaration->symbol);
4783 if (warning.implicit_int) {
4784 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4785 parameter_declaration->symbol);
4787 parameter_type = type_int;
4788 parameter_declaration->type = parameter_type;
4792 semantic_parameter(parameter_declaration);
4793 parameter_type = parameter_declaration->type;
4796 * we need the default promoted types for the function type
4798 parameter_type = get_default_promoted_type(parameter_type);
4800 function_parameter_t *function_parameter
4801 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4802 memset(function_parameter, 0, sizeof(function_parameter[0]));
4804 function_parameter->type = parameter_type;
4805 if (last_parameter != NULL) {
4806 last_parameter->next = function_parameter;
4808 parameters = function_parameter;
4810 last_parameter = function_parameter;
4813 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4815 new_type->function.parameters = parameters;
4816 new_type->function.unspecified_parameters = true;
4818 type = typehash_insert(new_type);
4819 if (type != new_type) {
4820 obstack_free(type_obst, new_type);
4823 declaration->type = type;
4826 static bool first_err = true;
4829 * When called with first_err set, prints the name of the current function,
4832 static void print_in_function(void)
4836 diagnosticf("%s: In function '%Y':\n",
4837 current_function->source_position.input_name,
4838 current_function->symbol);
4843 * Check if all labels are defined in the current function.
4844 * Check if all labels are used in the current function.
4846 static void check_labels(void)
4848 for (const goto_statement_t *goto_statement = goto_first;
4849 goto_statement != NULL;
4850 goto_statement = goto_statement->next) {
4851 /* skip computed gotos */
4852 if (goto_statement->expression != NULL)
4855 declaration_t *label = goto_statement->label;
4858 if (label->source_position.input_name == NULL) {
4859 print_in_function();
4860 errorf(&goto_statement->base.source_position,
4861 "label '%Y' used but not defined", label->symbol);
4864 goto_first = goto_last = NULL;
4866 if (warning.unused_label) {
4867 for (const label_statement_t *label_statement = label_first;
4868 label_statement != NULL;
4869 label_statement = label_statement->next) {
4870 const declaration_t *label = label_statement->label;
4872 if (! label->used) {
4873 print_in_function();
4874 warningf(&label_statement->base.source_position,
4875 "label '%Y' defined but not used", label->symbol);
4879 label_first = label_last = NULL;
4883 * Check declarations of current_function for unused entities.
4885 static void check_declarations(void)
4887 if (warning.unused_parameter) {
4888 const scope_t *scope = ¤t_function->scope;
4890 if (is_sym_main(current_function->symbol)) {
4891 /* do not issue unused warnings for main */
4894 const declaration_t *parameter = scope->declarations;
4895 for (; parameter != NULL; parameter = parameter->next) {
4896 if (! parameter->used) {
4897 print_in_function();
4898 warningf(¶meter->source_position,
4899 "unused parameter '%Y'", parameter->symbol);
4903 if (warning.unused_variable) {
4907 static int determine_truth(expression_t const* const cond)
4910 !is_constant_expression(cond) ? 0 :
4911 fold_constant(cond) != 0 ? 1 :
4915 static bool noreturn_candidate;
4917 static void check_reachable(statement_t *const stmt)
4919 if (stmt->base.reachable)
4921 if (stmt->kind != STATEMENT_DO_WHILE)
4922 stmt->base.reachable = true;
4924 statement_t *last = stmt;
4926 switch (stmt->kind) {
4927 case STATEMENT_INVALID:
4928 case STATEMENT_EMPTY:
4929 case STATEMENT_DECLARATION:
4931 next = stmt->base.next;
4934 case STATEMENT_COMPOUND:
4935 next = stmt->compound.statements;
4938 case STATEMENT_RETURN:
4939 noreturn_candidate = false;
4942 case STATEMENT_IF: {
4943 if_statement_t const* const ifs = &stmt->ifs;
4944 int const val = determine_truth(ifs->condition);
4947 check_reachable(ifs->true_statement);
4952 if (ifs->false_statement != NULL) {
4953 check_reachable(ifs->false_statement);
4957 next = stmt->base.next;
4961 case STATEMENT_SWITCH: {
4962 switch_statement_t const *const switchs = &stmt->switchs;
4963 expression_t const *const expr = switchs->expression;
4965 if (is_constant_expression(expr)) {
4966 long const val = fold_constant(expr);
4967 case_label_statement_t * defaults = NULL;
4968 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4969 if (i->expression == NULL) {
4974 if (i->first_case <= val && val <= i->last_case) {
4975 check_reachable((statement_t*)i);
4980 if (defaults != NULL) {
4981 check_reachable((statement_t*)defaults);
4985 bool has_default = false;
4986 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4987 if (i->expression == NULL)
4990 check_reachable((statement_t*)i);
4997 next = stmt->base.next;
5001 case STATEMENT_EXPRESSION: {
5002 /* Check for noreturn function call */
5003 expression_t const *const expr = stmt->expression.expression;
5004 if (expr->kind == EXPR_CALL) {
5005 expression_t const *const func = expr->call.function;
5006 if (func->kind == EXPR_REFERENCE) {
5007 declaration_t const *const decl = func->reference.declaration;
5008 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5014 next = stmt->base.next;
5018 case STATEMENT_CONTINUE: {
5019 statement_t *parent = stmt;
5021 parent = parent->base.parent;
5022 if (parent == NULL) /* continue not within loop */
5026 switch (parent->kind) {
5027 case STATEMENT_WHILE: goto continue_while;
5028 case STATEMENT_DO_WHILE: goto continue_do_while;
5029 case STATEMENT_FOR: goto continue_for;
5036 case STATEMENT_BREAK: {
5037 statement_t *parent = stmt;
5039 parent = parent->base.parent;
5040 if (parent == NULL) /* break not within loop/switch */
5043 switch (parent->kind) {
5044 case STATEMENT_SWITCH:
5045 case STATEMENT_WHILE:
5046 case STATEMENT_DO_WHILE:
5049 next = parent->base.next;
5050 goto found_break_parent;
5059 case STATEMENT_GOTO:
5060 if (stmt->gotos.expression) {
5061 statement_t *parent = stmt->base.parent;
5062 if (parent == NULL) /* top level goto */
5066 next = stmt->gotos.label->init.statement;
5067 if (next == NULL) /* missing label */
5072 case STATEMENT_LABEL:
5073 next = stmt->label.statement;
5076 case STATEMENT_CASE_LABEL:
5077 next = stmt->case_label.statement;
5080 case STATEMENT_WHILE: {
5081 while_statement_t const *const whiles = &stmt->whiles;
5082 int const val = determine_truth(whiles->condition);
5085 check_reachable(whiles->body);
5090 next = stmt->base.next;
5094 case STATEMENT_DO_WHILE:
5095 next = stmt->do_while.body;
5098 case STATEMENT_FOR: {
5099 for_statement_t *const fors = &stmt->fors;
5101 if (fors->condition_reachable)
5103 fors->condition_reachable = true;
5105 expression_t const *const cond = fors->condition;
5107 cond == NULL ? 1 : determine_truth(cond);
5110 check_reachable(fors->body);
5115 next = stmt->base.next;
5119 case STATEMENT_MS_TRY: {
5120 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5121 check_reachable(ms_try->try_statement);
5122 next = ms_try->final_statement;
5126 case STATEMENT_LEAVE: {
5127 statement_t *parent = stmt;
5129 parent = parent->base.parent;
5130 if (parent == NULL) /* __leave not within __try */
5133 if (parent->kind == STATEMENT_MS_TRY) {
5135 next = parent->ms_try.final_statement;
5143 while (next == NULL) {
5144 next = last->base.parent;
5146 noreturn_candidate = false;
5148 type_t *const type = current_function->type;
5149 assert(is_type_function(type));
5150 type_t *const ret = skip_typeref(type->function.return_type);
5151 if (warning.return_type &&
5152 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5153 is_type_valid(ret) &&
5154 !is_sym_main(current_function->symbol)) {
5155 warningf(&stmt->base.source_position,
5156 "control reaches end of non-void function");
5161 switch (next->kind) {
5162 case STATEMENT_INVALID:
5163 case STATEMENT_EMPTY:
5164 case STATEMENT_DECLARATION:
5165 case STATEMENT_EXPRESSION:
5167 case STATEMENT_RETURN:
5168 case STATEMENT_CONTINUE:
5169 case STATEMENT_BREAK:
5170 case STATEMENT_GOTO:
5171 case STATEMENT_LEAVE:
5172 panic("invalid control flow in function");
5174 case STATEMENT_COMPOUND:
5176 case STATEMENT_SWITCH:
5177 case STATEMENT_LABEL:
5178 case STATEMENT_CASE_LABEL:
5180 next = next->base.next;
5183 case STATEMENT_WHILE: {
5185 if (next->base.reachable)
5187 next->base.reachable = true;
5189 while_statement_t const *const whiles = &next->whiles;
5190 int const val = determine_truth(whiles->condition);
5193 check_reachable(whiles->body);
5199 next = next->base.next;
5203 case STATEMENT_DO_WHILE: {
5205 if (next->base.reachable)
5207 next->base.reachable = true;
5209 do_while_statement_t const *const dw = &next->do_while;
5210 int const val = determine_truth(dw->condition);
5213 check_reachable(dw->body);
5219 next = next->base.next;
5223 case STATEMENT_FOR: {
5225 for_statement_t *const fors = &next->fors;
5227 fors->step_reachable = true;
5229 if (fors->condition_reachable)
5231 fors->condition_reachable = true;
5233 expression_t const *const cond = fors->condition;
5235 cond == NULL ? 1 : determine_truth(cond);
5238 check_reachable(fors->body);
5244 next = next->base.next;
5248 case STATEMENT_MS_TRY:
5250 next = next->ms_try.final_statement;
5256 next = stmt->base.parent;
5258 warningf(&stmt->base.source_position,
5259 "control reaches end of non-void function");
5263 check_reachable(next);
5266 static void check_unreachable(statement_t const* const stmt)
5268 if (!stmt->base.reachable &&
5269 stmt->kind != STATEMENT_DO_WHILE &&
5270 stmt->kind != STATEMENT_FOR &&
5271 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5272 warningf(&stmt->base.source_position, "statement is unreachable");
5275 switch (stmt->kind) {
5276 case STATEMENT_INVALID:
5277 case STATEMENT_EMPTY:
5278 case STATEMENT_RETURN:
5279 case STATEMENT_DECLARATION:
5280 case STATEMENT_EXPRESSION:
5281 case STATEMENT_CONTINUE:
5282 case STATEMENT_BREAK:
5283 case STATEMENT_GOTO:
5285 case STATEMENT_LEAVE:
5288 case STATEMENT_COMPOUND:
5289 if (stmt->compound.statements)
5290 check_unreachable(stmt->compound.statements);
5294 check_unreachable(stmt->ifs.true_statement);
5295 if (stmt->ifs.false_statement != NULL)
5296 check_unreachable(stmt->ifs.false_statement);
5299 case STATEMENT_SWITCH:
5300 check_unreachable(stmt->switchs.body);
5303 case STATEMENT_LABEL:
5304 check_unreachable(stmt->label.statement);
5307 case STATEMENT_CASE_LABEL:
5308 check_unreachable(stmt->case_label.statement);
5311 case STATEMENT_WHILE:
5312 check_unreachable(stmt->whiles.body);
5315 case STATEMENT_DO_WHILE:
5316 check_unreachable(stmt->do_while.body);
5317 if (!stmt->base.reachable) {
5318 expression_t const *const cond = stmt->do_while.condition;
5319 if (determine_truth(cond) >= 0) {
5320 warningf(&cond->base.source_position,
5321 "condition of do-while-loop is unreachable");
5326 case STATEMENT_FOR: {
5327 for_statement_t const* const fors = &stmt->fors;
5329 // if init and step are unreachable, cond is unreachable, too
5330 if (!stmt->base.reachable && !fors->step_reachable) {
5331 warningf(&stmt->base.source_position, "statement is unreachable");
5333 if (!stmt->base.reachable && fors->initialisation != NULL) {
5334 warningf(&fors->initialisation->base.source_position,
5335 "initialisation of for-statement is unreachable");
5338 if (!fors->condition_reachable && fors->condition != NULL) {
5339 warningf(&fors->condition->base.source_position,
5340 "condition of for-statement is unreachable");
5343 if (!fors->step_reachable && fors->step != NULL) {
5344 warningf(&fors->step->base.source_position,
5345 "step of for-statement is unreachable");
5349 check_unreachable(fors->body);
5353 case STATEMENT_MS_TRY: {
5354 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5355 check_unreachable(ms_try->try_statement);
5356 check_unreachable(ms_try->final_statement);
5360 if (stmt->base.next)
5361 check_unreachable(stmt->base.next);
5364 static void parse_external_declaration(void)
5366 /* function-definitions and declarations both start with declaration
5368 declaration_specifiers_t specifiers;
5369 memset(&specifiers, 0, sizeof(specifiers));
5371 add_anchor_token(';');
5372 parse_declaration_specifiers(&specifiers);
5373 rem_anchor_token(';');
5375 /* must be a declaration */
5376 if (token.type == ';') {
5377 parse_anonymous_declaration_rest(&specifiers);
5381 add_anchor_token(',');
5382 add_anchor_token('=');
5383 add_anchor_token(';');
5385 /* declarator is common to both function-definitions and declarations */
5386 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5388 rem_anchor_token(',');
5389 rem_anchor_token('=');
5390 rem_anchor_token(';');
5392 /* must be a declaration */
5393 switch (token.type) {
5397 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5401 /* must be a function definition */
5402 parse_kr_declaration_list(ndeclaration);
5404 if (token.type != '{') {
5405 parse_error_expected("while parsing function definition", '{', NULL);
5406 eat_until_matching_token(';');
5410 type_t *type = ndeclaration->type;
5412 /* note that we don't skip typerefs: the standard doesn't allow them here
5413 * (so we can't use is_type_function here) */
5414 if (type->kind != TYPE_FUNCTION) {
5415 if (is_type_valid(type)) {
5416 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5417 type, ndeclaration->symbol);
5423 if (warning.aggregate_return &&
5424 is_type_compound(skip_typeref(type->function.return_type))) {
5425 warningf(HERE, "function '%Y' returns an aggregate",
5426 ndeclaration->symbol);
5428 if (warning.traditional && !type->function.unspecified_parameters) {
5429 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5430 ndeclaration->symbol);
5432 if (warning.old_style_definition && type->function.unspecified_parameters) {
5433 warningf(HERE, "old-style function definition '%Y'",
5434 ndeclaration->symbol);
5437 /* § 6.7.5.3 (14) a function definition with () means no
5438 * parameters (and not unspecified parameters) */
5439 if (type->function.unspecified_parameters
5440 && type->function.parameters == NULL
5441 && !type->function.kr_style_parameters) {
5442 type_t *duplicate = duplicate_type(type);
5443 duplicate->function.unspecified_parameters = false;
5445 type = typehash_insert(duplicate);
5446 if (type != duplicate) {
5447 obstack_free(type_obst, duplicate);
5449 ndeclaration->type = type;
5452 declaration_t *const declaration = record_declaration(ndeclaration, true);
5453 if (ndeclaration != declaration) {
5454 declaration->scope = ndeclaration->scope;
5456 type = skip_typeref(declaration->type);
5458 /* push function parameters and switch scope */
5459 int top = environment_top();
5460 scope_t *last_scope = scope;
5461 set_scope(&declaration->scope);
5463 declaration_t *parameter = declaration->scope.declarations;
5464 for( ; parameter != NULL; parameter = parameter->next) {
5465 if (parameter->parent_scope == &ndeclaration->scope) {
5466 parameter->parent_scope = scope;
5468 assert(parameter->parent_scope == NULL
5469 || parameter->parent_scope == scope);
5470 parameter->parent_scope = scope;
5471 if (parameter->symbol == NULL) {
5472 errorf(¶meter->source_position, "parameter name omitted");
5475 environment_push(parameter);
5478 if (declaration->init.statement != NULL) {
5479 parser_error_multiple_definition(declaration, HERE);
5482 /* parse function body */
5483 int label_stack_top = label_top();
5484 declaration_t *old_current_function = current_function;
5485 current_function = declaration;
5486 current_parent = NULL;
5488 statement_t *const body = parse_compound_statement(false);
5489 declaration->init.statement = body;
5492 check_declarations();
5493 if (warning.return_type ||
5494 warning.unreachable_code ||
5495 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5496 noreturn_candidate = true;
5497 check_reachable(body);
5498 if (warning.unreachable_code)
5499 check_unreachable(body);
5500 if (warning.missing_noreturn &&
5501 noreturn_candidate &&
5502 !(declaration->modifiers & DM_NORETURN)) {
5503 warningf(&body->base.source_position,
5504 "function '%#T' is candidate for attribute 'noreturn'",
5505 type, declaration->symbol);
5509 assert(current_parent == NULL);
5510 assert(current_function == declaration);
5511 current_function = old_current_function;
5512 label_pop_to(label_stack_top);
5515 assert(scope == &declaration->scope);
5516 set_scope(last_scope);
5517 environment_pop_to(top);
5520 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5521 source_position_t *source_position,
5522 const symbol_t *symbol)
5524 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5526 type->bitfield.base_type = base_type;
5527 type->bitfield.size_expression = size;
5530 type_t *skipped_type = skip_typeref(base_type);
5531 if (!is_type_integer(skipped_type)) {
5532 errorf(HERE, "bitfield base type '%T' is not an integer type",
5536 bit_size = skipped_type->base.size * 8;
5539 if (is_constant_expression(size)) {
5540 long v = fold_constant(size);
5543 errorf(source_position, "negative width in bit-field '%Y'",
5545 } else if (v == 0) {
5546 errorf(source_position, "zero width for bit-field '%Y'",
5548 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5549 errorf(source_position, "width of '%Y' exceeds its type",
5552 type->bitfield.bit_size = v;
5559 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5562 declaration_t *iter = compound_declaration->scope.declarations;
5563 for( ; iter != NULL; iter = iter->next) {
5564 if (iter->namespc != NAMESPACE_NORMAL)
5567 if (iter->symbol == NULL) {
5568 type_t *type = skip_typeref(iter->type);
5569 if (is_type_compound(type)) {
5570 declaration_t *result
5571 = find_compound_entry(type->compound.declaration, symbol);
5578 if (iter->symbol == symbol) {
5586 static void parse_compound_declarators(declaration_t *struct_declaration,
5587 const declaration_specifiers_t *specifiers)
5589 declaration_t *last_declaration = struct_declaration->scope.declarations;
5590 if (last_declaration != NULL) {
5591 while (last_declaration->next != NULL) {
5592 last_declaration = last_declaration->next;
5597 declaration_t *declaration;
5599 if (token.type == ':') {
5600 source_position_t source_position = *HERE;
5603 type_t *base_type = specifiers->type;
5604 expression_t *size = parse_constant_expression();
5606 type_t *type = make_bitfield_type(base_type, size,
5607 &source_position, sym_anonymous);
5609 declaration = allocate_declaration_zero();
5610 declaration->namespc = NAMESPACE_NORMAL;
5611 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5612 declaration->storage_class = STORAGE_CLASS_NONE;
5613 declaration->source_position = source_position;
5614 declaration->modifiers = specifiers->modifiers;
5615 declaration->type = type;
5617 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5619 type_t *orig_type = declaration->type;
5620 type_t *type = skip_typeref(orig_type);
5622 if (token.type == ':') {
5623 source_position_t source_position = *HERE;
5625 expression_t *size = parse_constant_expression();
5627 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5628 &source_position, declaration->symbol);
5629 declaration->type = bitfield_type;
5631 /* TODO we ignore arrays for now... what is missing is a check
5632 * that they're at the end of the struct */
5633 if (is_type_incomplete(type) && !is_type_array(type)) {
5635 "compound member '%Y' has incomplete type '%T'",
5636 declaration->symbol, orig_type);
5637 } else if (is_type_function(type)) {
5638 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5639 declaration->symbol, orig_type);
5644 /* make sure we don't define a symbol multiple times */
5645 symbol_t *symbol = declaration->symbol;
5646 if (symbol != NULL) {
5647 declaration_t *prev_decl
5648 = find_compound_entry(struct_declaration, symbol);
5650 if (prev_decl != NULL) {
5651 assert(prev_decl->symbol == symbol);
5652 errorf(&declaration->source_position,
5653 "multiple declarations of symbol '%Y' (declared %P)",
5654 symbol, &prev_decl->source_position);
5658 /* append declaration */
5659 if (last_declaration != NULL) {
5660 last_declaration->next = declaration;
5662 struct_declaration->scope.declarations = declaration;
5664 last_declaration = declaration;
5666 if (token.type != ',')
5676 static void parse_compound_type_entries(declaration_t *compound_declaration)
5679 add_anchor_token('}');
5681 while (token.type != '}' && token.type != T_EOF) {
5682 declaration_specifiers_t specifiers;
5683 memset(&specifiers, 0, sizeof(specifiers));
5684 parse_declaration_specifiers(&specifiers);
5686 parse_compound_declarators(compound_declaration, &specifiers);
5688 rem_anchor_token('}');
5690 if (token.type == T_EOF) {
5691 errorf(HERE, "EOF while parsing struct");
5696 static type_t *parse_typename(void)
5698 declaration_specifiers_t specifiers;
5699 memset(&specifiers, 0, sizeof(specifiers));
5700 parse_declaration_specifiers(&specifiers);
5701 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5702 /* TODO: improve error message, user does probably not know what a
5703 * storage class is...
5705 errorf(HERE, "typename may not have a storage class");
5708 type_t *result = parse_abstract_declarator(specifiers.type);
5716 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5717 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5718 expression_t *left);
5720 typedef struct expression_parser_function_t expression_parser_function_t;
5721 struct expression_parser_function_t {
5722 unsigned precedence;
5723 parse_expression_function parser;
5724 unsigned infix_precedence;
5725 parse_expression_infix_function infix_parser;
5728 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5731 * Prints an error message if an expression was expected but not read
5733 static expression_t *expected_expression_error(void)
5735 /* skip the error message if the error token was read */
5736 if (token.type != T_ERROR) {
5737 errorf(HERE, "expected expression, got token '%K'", &token);
5741 return create_invalid_expression();
5745 * Parse a string constant.
5747 static expression_t *parse_string_const(void)
5750 if (token.type == T_STRING_LITERAL) {
5751 string_t res = token.v.string;
5753 while (token.type == T_STRING_LITERAL) {
5754 res = concat_strings(&res, &token.v.string);
5757 if (token.type != T_WIDE_STRING_LITERAL) {
5758 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5759 /* note: that we use type_char_ptr here, which is already the
5760 * automatic converted type. revert_automatic_type_conversion
5761 * will construct the array type */
5762 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5763 cnst->string.value = res;
5767 wres = concat_string_wide_string(&res, &token.v.wide_string);
5769 wres = token.v.wide_string;
5774 switch (token.type) {
5775 case T_WIDE_STRING_LITERAL:
5776 wres = concat_wide_strings(&wres, &token.v.wide_string);
5779 case T_STRING_LITERAL:
5780 wres = concat_wide_string_string(&wres, &token.v.string);
5784 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5785 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5786 cnst->wide_string.value = wres;
5795 * Parse an integer constant.
5797 static expression_t *parse_int_const(void)
5799 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5800 cnst->base.source_position = *HERE;
5801 cnst->base.type = token.datatype;
5802 cnst->conste.v.int_value = token.v.intvalue;
5810 * Parse a character constant.
5812 static expression_t *parse_character_constant(void)
5814 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5816 cnst->base.source_position = *HERE;
5817 cnst->base.type = token.datatype;
5818 cnst->conste.v.character = token.v.string;
5820 if (cnst->conste.v.character.size != 1) {
5821 if (warning.multichar && (c_mode & _GNUC)) {
5823 warningf(HERE, "multi-character character constant");
5825 errorf(HERE, "more than 1 characters in character constant");
5834 * Parse a wide character constant.
5836 static expression_t *parse_wide_character_constant(void)
5838 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5840 cnst->base.source_position = *HERE;
5841 cnst->base.type = token.datatype;
5842 cnst->conste.v.wide_character = token.v.wide_string;
5844 if (cnst->conste.v.wide_character.size != 1) {
5845 if (warning.multichar && (c_mode & _GNUC)) {
5847 warningf(HERE, "multi-character character constant");
5849 errorf(HERE, "more than 1 characters in character constant");
5858 * Parse a float constant.
5860 static expression_t *parse_float_const(void)
5862 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5863 cnst->base.type = token.datatype;
5864 cnst->conste.v.float_value = token.v.floatvalue;
5871 static declaration_t *create_implicit_function(symbol_t *symbol,
5872 const source_position_t *source_position)
5874 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5875 ntype->function.return_type = type_int;
5876 ntype->function.unspecified_parameters = true;
5878 type_t *type = typehash_insert(ntype);
5879 if (type != ntype) {
5883 declaration_t *const declaration = allocate_declaration_zero();
5884 declaration->storage_class = STORAGE_CLASS_EXTERN;
5885 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5886 declaration->type = type;
5887 declaration->symbol = symbol;
5888 declaration->source_position = *source_position;
5889 declaration->implicit = true;
5891 bool strict_prototypes_old = warning.strict_prototypes;
5892 warning.strict_prototypes = false;
5893 record_declaration(declaration, false);
5894 warning.strict_prototypes = strict_prototypes_old;
5900 * Creates a return_type (func)(argument_type) function type if not
5903 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5904 type_t *argument_type2)
5906 function_parameter_t *parameter2
5907 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5908 memset(parameter2, 0, sizeof(parameter2[0]));
5909 parameter2->type = argument_type2;
5911 function_parameter_t *parameter1
5912 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5913 memset(parameter1, 0, sizeof(parameter1[0]));
5914 parameter1->type = argument_type1;
5915 parameter1->next = parameter2;
5917 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5918 type->function.return_type = return_type;
5919 type->function.parameters = parameter1;
5921 type_t *result = typehash_insert(type);
5922 if (result != type) {
5930 * Creates a return_type (func)(argument_type) function type if not
5933 * @param return_type the return type
5934 * @param argument_type the argument type
5936 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5938 function_parameter_t *parameter
5939 = obstack_alloc(type_obst, sizeof(parameter[0]));
5940 memset(parameter, 0, sizeof(parameter[0]));
5941 parameter->type = argument_type;
5943 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5944 type->function.return_type = return_type;
5945 type->function.parameters = parameter;
5947 type_t *result = typehash_insert(type);
5948 if (result != type) {
5955 static type_t *make_function_0_type(type_t *return_type)
5957 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5958 type->function.return_type = return_type;
5959 type->function.parameters = NULL;
5961 type_t *result = typehash_insert(type);
5962 if (result != type) {
5970 * Creates a function type for some function like builtins.
5972 * @param symbol the symbol describing the builtin
5974 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5976 switch(symbol->ID) {
5977 case T___builtin_alloca:
5978 return make_function_1_type(type_void_ptr, type_size_t);
5979 case T___builtin_huge_val:
5980 return make_function_0_type(type_double);
5981 case T___builtin_nan:
5982 return make_function_1_type(type_double, type_char_ptr);
5983 case T___builtin_nanf:
5984 return make_function_1_type(type_float, type_char_ptr);
5985 case T___builtin_nand:
5986 return make_function_1_type(type_long_double, type_char_ptr);
5987 case T___builtin_va_end:
5988 return make_function_1_type(type_void, type_valist);
5989 case T___builtin_expect:
5990 return make_function_2_type(type_long, type_long, type_long);
5992 internal_errorf(HERE, "not implemented builtin symbol found");
5997 * Performs automatic type cast as described in § 6.3.2.1.
5999 * @param orig_type the original type
6001 static type_t *automatic_type_conversion(type_t *orig_type)
6003 type_t *type = skip_typeref(orig_type);
6004 if (is_type_array(type)) {
6005 array_type_t *array_type = &type->array;
6006 type_t *element_type = array_type->element_type;
6007 unsigned qualifiers = array_type->base.qualifiers;
6009 return make_pointer_type(element_type, qualifiers);
6012 if (is_type_function(type)) {
6013 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6020 * reverts the automatic casts of array to pointer types and function
6021 * to function-pointer types as defined § 6.3.2.1
6023 type_t *revert_automatic_type_conversion(const expression_t *expression)
6025 switch (expression->kind) {
6026 case EXPR_REFERENCE: return expression->reference.declaration->type;
6029 return get_qualified_type(expression->select.compound_entry->type,
6030 expression->base.type->base.qualifiers);
6032 case EXPR_UNARY_DEREFERENCE: {
6033 const expression_t *const value = expression->unary.value;
6034 type_t *const type = skip_typeref(value->base.type);
6035 assert(is_type_pointer(type));
6036 return type->pointer.points_to;
6039 case EXPR_BUILTIN_SYMBOL:
6040 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6042 case EXPR_ARRAY_ACCESS: {
6043 const expression_t *array_ref = expression->array_access.array_ref;
6044 type_t *type_left = skip_typeref(array_ref->base.type);
6045 if (!is_type_valid(type_left))
6047 assert(is_type_pointer(type_left));
6048 return type_left->pointer.points_to;
6051 case EXPR_STRING_LITERAL: {
6052 size_t size = expression->string.value.size;
6053 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6056 case EXPR_WIDE_STRING_LITERAL: {
6057 size_t size = expression->wide_string.value.size;
6058 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6061 case EXPR_COMPOUND_LITERAL:
6062 return expression->compound_literal.type;
6067 return expression->base.type;
6070 static expression_t *parse_reference(void)
6072 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6074 reference_expression_t *ref = &expression->reference;
6075 symbol_t *const symbol = token.v.symbol;
6077 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6079 if (declaration == NULL) {
6080 if (!strict_mode && look_ahead(1)->type == '(') {
6081 /* an implicitly declared function */
6082 if (warning.implicit_function_declaration) {
6083 warningf(HERE, "implicit declaration of function '%Y'",
6087 declaration = create_implicit_function(symbol, HERE);
6089 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6090 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6094 type_t *type = declaration->type;
6096 /* we always do the auto-type conversions; the & and sizeof parser contains
6097 * code to revert this! */
6098 type = automatic_type_conversion(type);
6100 ref->declaration = declaration;
6101 ref->base.type = type;
6103 /* this declaration is used */
6104 declaration->used = true;
6106 /* check for deprecated functions */
6107 if (warning.deprecated_declarations &&
6108 declaration->modifiers & DM_DEPRECATED) {
6109 char const *const prefix = is_type_function(declaration->type) ?
6110 "function" : "variable";
6112 if (declaration->deprecated_string != NULL) {
6113 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6114 prefix, declaration->symbol, &declaration->source_position,
6115 declaration->deprecated_string);
6117 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6118 declaration->symbol, &declaration->source_position);
6121 if (warning.init_self && declaration == current_init_decl) {
6122 current_init_decl = NULL;
6123 warningf(HERE, "variable '%#T' is initialized by itself",
6124 declaration->type, declaration->symbol);
6131 static bool semantic_cast(expression_t *cast)
6133 expression_t *expression = cast->unary.value;
6134 type_t *orig_dest_type = cast->base.type;
6135 type_t *orig_type_right = expression->base.type;
6136 type_t const *dst_type = skip_typeref(orig_dest_type);
6137 type_t const *src_type = skip_typeref(orig_type_right);
6138 source_position_t const *pos = &cast->base.source_position;
6140 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6141 if (dst_type == type_void)
6144 /* only integer and pointer can be casted to pointer */
6145 if (is_type_pointer(dst_type) &&
6146 !is_type_pointer(src_type) &&
6147 !is_type_integer(src_type) &&
6148 is_type_valid(src_type)) {
6149 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6153 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6154 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6158 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6159 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6163 if (warning.cast_qual &&
6164 is_type_pointer(src_type) &&
6165 is_type_pointer(dst_type)) {
6166 type_t *src = skip_typeref(src_type->pointer.points_to);
6167 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6168 unsigned missing_qualifiers =
6169 src->base.qualifiers & ~dst->base.qualifiers;
6170 if (missing_qualifiers != 0) {
6172 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6173 missing_qualifiers, orig_type_right);
6179 static expression_t *parse_compound_literal(type_t *type)
6181 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6183 parse_initializer_env_t env;
6185 env.declaration = NULL;
6186 env.must_be_constant = false;
6187 initializer_t *initializer = parse_initializer(&env);
6190 expression->compound_literal.initializer = initializer;
6191 expression->compound_literal.type = type;
6192 expression->base.type = automatic_type_conversion(type);
6198 * Parse a cast expression.
6200 static expression_t *parse_cast(void)
6202 add_anchor_token(')');
6204 source_position_t source_position = token.source_position;
6206 type_t *type = parse_typename();
6208 rem_anchor_token(')');
6211 if (token.type == '{') {
6212 return parse_compound_literal(type);
6215 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6216 cast->base.source_position = source_position;
6218 expression_t *value = parse_sub_expression(20);
6219 cast->base.type = type;
6220 cast->unary.value = value;
6222 if (! semantic_cast(cast)) {
6223 /* TODO: record the error in the AST. else it is impossible to detect it */
6228 return create_invalid_expression();
6232 * Parse a statement expression.
6234 static expression_t *parse_statement_expression(void)
6236 add_anchor_token(')');
6238 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6240 statement_t *statement = parse_compound_statement(true);
6241 expression->statement.statement = statement;
6242 expression->base.source_position = statement->base.source_position;
6244 /* find last statement and use its type */
6245 type_t *type = type_void;
6246 const statement_t *stmt = statement->compound.statements;
6248 while (stmt->base.next != NULL)
6249 stmt = stmt->base.next;
6251 if (stmt->kind == STATEMENT_EXPRESSION) {
6252 type = stmt->expression.expression->base.type;
6255 warningf(&expression->base.source_position, "empty statement expression ({})");
6257 expression->base.type = type;
6259 rem_anchor_token(')');
6267 * Parse a parenthesized expression.
6269 static expression_t *parse_parenthesized_expression(void)
6273 switch(token.type) {
6275 /* gcc extension: a statement expression */
6276 return parse_statement_expression();
6280 return parse_cast();
6282 if (is_typedef_symbol(token.v.symbol)) {
6283 return parse_cast();
6287 add_anchor_token(')');
6288 expression_t *result = parse_expression();
6289 rem_anchor_token(')');
6296 static expression_t *parse_function_keyword(void)
6301 if (current_function == NULL) {
6302 errorf(HERE, "'__func__' used outside of a function");
6305 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6306 expression->base.type = type_char_ptr;
6307 expression->funcname.kind = FUNCNAME_FUNCTION;
6312 static expression_t *parse_pretty_function_keyword(void)
6314 eat(T___PRETTY_FUNCTION__);
6316 if (current_function == NULL) {
6317 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6320 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6321 expression->base.type = type_char_ptr;
6322 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6327 static expression_t *parse_funcsig_keyword(void)
6331 if (current_function == NULL) {
6332 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6335 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6336 expression->base.type = type_char_ptr;
6337 expression->funcname.kind = FUNCNAME_FUNCSIG;
6342 static expression_t *parse_funcdname_keyword(void)
6344 eat(T___FUNCDNAME__);
6346 if (current_function == NULL) {
6347 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6350 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6351 expression->base.type = type_char_ptr;
6352 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6357 static designator_t *parse_designator(void)
6359 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6360 result->source_position = *HERE;
6362 if (token.type != T_IDENTIFIER) {
6363 parse_error_expected("while parsing member designator",
6364 T_IDENTIFIER, NULL);
6367 result->symbol = token.v.symbol;
6370 designator_t *last_designator = result;
6372 if (token.type == '.') {
6374 if (token.type != T_IDENTIFIER) {
6375 parse_error_expected("while parsing member designator",
6376 T_IDENTIFIER, NULL);
6379 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6380 designator->source_position = *HERE;
6381 designator->symbol = token.v.symbol;
6384 last_designator->next = designator;
6385 last_designator = designator;
6388 if (token.type == '[') {
6390 add_anchor_token(']');
6391 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6392 designator->source_position = *HERE;
6393 designator->array_index = parse_expression();
6394 rem_anchor_token(']');
6396 if (designator->array_index == NULL) {
6400 last_designator->next = designator;
6401 last_designator = designator;
6413 * Parse the __builtin_offsetof() expression.
6415 static expression_t *parse_offsetof(void)
6417 eat(T___builtin_offsetof);
6419 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6420 expression->base.type = type_size_t;
6423 add_anchor_token(',');
6424 type_t *type = parse_typename();
6425 rem_anchor_token(',');
6427 add_anchor_token(')');
6428 designator_t *designator = parse_designator();
6429 rem_anchor_token(')');
6432 expression->offsetofe.type = type;
6433 expression->offsetofe.designator = designator;
6436 memset(&path, 0, sizeof(path));
6437 path.top_type = type;
6438 path.path = NEW_ARR_F(type_path_entry_t, 0);
6440 descend_into_subtype(&path);
6442 if (!walk_designator(&path, designator, true)) {
6443 return create_invalid_expression();
6446 DEL_ARR_F(path.path);
6450 return create_invalid_expression();
6454 * Parses a _builtin_va_start() expression.
6456 static expression_t *parse_va_start(void)
6458 eat(T___builtin_va_start);
6460 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6463 add_anchor_token(',');
6464 expression->va_starte.ap = parse_assignment_expression();
6465 rem_anchor_token(',');
6467 expression_t *const expr = parse_assignment_expression();
6468 if (expr->kind == EXPR_REFERENCE) {
6469 declaration_t *const decl = expr->reference.declaration;
6470 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6471 errorf(&expr->base.source_position,
6472 "second argument of 'va_start' must be last parameter of the current function");
6474 expression->va_starte.parameter = decl;
6480 return create_invalid_expression();
6484 * Parses a _builtin_va_arg() expression.
6486 static expression_t *parse_va_arg(void)
6488 eat(T___builtin_va_arg);
6490 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6493 expression->va_arge.ap = parse_assignment_expression();
6495 expression->base.type = parse_typename();
6500 return create_invalid_expression();
6503 static expression_t *parse_builtin_symbol(void)
6505 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6507 symbol_t *symbol = token.v.symbol;
6509 expression->builtin_symbol.symbol = symbol;
6512 type_t *type = get_builtin_symbol_type(symbol);
6513 type = automatic_type_conversion(type);
6515 expression->base.type = type;
6520 * Parses a __builtin_constant() expression.
6522 static expression_t *parse_builtin_constant(void)
6524 eat(T___builtin_constant_p);
6526 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6529 add_anchor_token(')');
6530 expression->builtin_constant.value = parse_assignment_expression();
6531 rem_anchor_token(')');
6533 expression->base.type = type_int;
6537 return create_invalid_expression();
6541 * Parses a __builtin_prefetch() expression.
6543 static expression_t *parse_builtin_prefetch(void)
6545 eat(T___builtin_prefetch);
6547 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6550 add_anchor_token(')');
6551 expression->builtin_prefetch.adr = parse_assignment_expression();
6552 if (token.type == ',') {
6554 expression->builtin_prefetch.rw = parse_assignment_expression();
6556 if (token.type == ',') {
6558 expression->builtin_prefetch.locality = parse_assignment_expression();
6560 rem_anchor_token(')');
6562 expression->base.type = type_void;
6566 return create_invalid_expression();
6570 * Parses a __builtin_is_*() compare expression.
6572 static expression_t *parse_compare_builtin(void)
6574 expression_t *expression;
6576 switch(token.type) {
6577 case T___builtin_isgreater:
6578 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6580 case T___builtin_isgreaterequal:
6581 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6583 case T___builtin_isless:
6584 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6586 case T___builtin_islessequal:
6587 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6589 case T___builtin_islessgreater:
6590 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6592 case T___builtin_isunordered:
6593 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6596 internal_errorf(HERE, "invalid compare builtin found");
6599 expression->base.source_position = *HERE;
6603 expression->binary.left = parse_assignment_expression();
6605 expression->binary.right = parse_assignment_expression();
6608 type_t *const orig_type_left = expression->binary.left->base.type;
6609 type_t *const orig_type_right = expression->binary.right->base.type;
6611 type_t *const type_left = skip_typeref(orig_type_left);
6612 type_t *const type_right = skip_typeref(orig_type_right);
6613 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6614 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6615 type_error_incompatible("invalid operands in comparison",
6616 &expression->base.source_position, orig_type_left, orig_type_right);
6619 semantic_comparison(&expression->binary);
6624 return create_invalid_expression();
6629 * Parses a __builtin_expect() expression.
6631 static expression_t *parse_builtin_expect(void)
6633 eat(T___builtin_expect);
6635 expression_t *expression
6636 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6639 expression->binary.left = parse_assignment_expression();
6641 expression->binary.right = parse_constant_expression();
6644 expression->base.type = expression->binary.left->base.type;
6648 return create_invalid_expression();
6653 * Parses a MS assume() expression.
6655 static expression_t *parse_assume(void)
6659 expression_t *expression
6660 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6663 add_anchor_token(')');
6664 expression->unary.value = parse_assignment_expression();
6665 rem_anchor_token(')');
6668 expression->base.type = type_void;
6671 return create_invalid_expression();
6675 * Return the declaration for a given label symbol or create a new one.
6677 * @param symbol the symbol of the label
6679 static declaration_t *get_label(symbol_t *symbol)
6681 declaration_t *candidate;
6682 assert(current_function != NULL);
6684 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6685 /* if we found a local label, we already created the declaration */
6686 if (candidate != NULL) {
6687 assert(candidate->parent_scope == scope);
6691 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6692 /* if we found a label in the same function, then we already created the
6694 if (candidate != NULL
6695 && candidate->parent_scope == ¤t_function->scope) {
6699 /* otherwise we need to create a new one */
6700 declaration_t *const declaration = allocate_declaration_zero();
6701 declaration->namespc = NAMESPACE_LABEL;
6702 declaration->symbol = symbol;
6704 label_push(declaration);
6710 * Parses a GNU && label address expression.
6712 static expression_t *parse_label_address(void)
6714 source_position_t source_position = token.source_position;
6716 if (token.type != T_IDENTIFIER) {
6717 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6720 symbol_t *symbol = token.v.symbol;
6723 declaration_t *label = get_label(symbol);
6726 label->address_taken = true;
6728 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6729 expression->base.source_position = source_position;
6731 /* label address is threaten as a void pointer */
6732 expression->base.type = type_void_ptr;
6733 expression->label_address.declaration = label;
6736 return create_invalid_expression();
6740 * Parse a microsoft __noop expression.
6742 static expression_t *parse_noop_expression(void)
6744 source_position_t source_position = *HERE;
6747 if (token.type == '(') {
6748 /* parse arguments */
6750 add_anchor_token(')');
6751 add_anchor_token(',');
6753 if (token.type != ')') {
6755 (void)parse_assignment_expression();
6756 if (token.type != ',')
6762 rem_anchor_token(',');
6763 rem_anchor_token(')');
6766 /* the result is a (int)0 */
6767 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6768 cnst->base.source_position = source_position;
6769 cnst->base.type = type_int;
6770 cnst->conste.v.int_value = 0;
6771 cnst->conste.is_ms_noop = true;
6776 return create_invalid_expression();
6780 * Parses a primary expression.
6782 static expression_t *parse_primary_expression(void)
6784 switch (token.type) {
6785 case T_INTEGER: return parse_int_const();
6786 case T_CHARACTER_CONSTANT: return parse_character_constant();
6787 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6788 case T_FLOATINGPOINT: return parse_float_const();
6789 case T_STRING_LITERAL:
6790 case T_WIDE_STRING_LITERAL: return parse_string_const();
6791 case T_IDENTIFIER: return parse_reference();
6792 case T___FUNCTION__:
6793 case T___func__: return parse_function_keyword();
6794 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6795 case T___FUNCSIG__: return parse_funcsig_keyword();
6796 case T___FUNCDNAME__: return parse_funcdname_keyword();
6797 case T___builtin_offsetof: return parse_offsetof();
6798 case T___builtin_va_start: return parse_va_start();
6799 case T___builtin_va_arg: return parse_va_arg();
6800 case T___builtin_expect:
6801 case T___builtin_alloca:
6802 case T___builtin_nan:
6803 case T___builtin_nand:
6804 case T___builtin_nanf:
6805 case T___builtin_huge_val:
6806 case T___builtin_va_end: return parse_builtin_symbol();
6807 case T___builtin_isgreater:
6808 case T___builtin_isgreaterequal:
6809 case T___builtin_isless:
6810 case T___builtin_islessequal:
6811 case T___builtin_islessgreater:
6812 case T___builtin_isunordered: return parse_compare_builtin();
6813 case T___builtin_constant_p: return parse_builtin_constant();
6814 case T___builtin_prefetch: return parse_builtin_prefetch();
6815 case T__assume: return parse_assume();
6818 return parse_label_address();
6821 case '(': return parse_parenthesized_expression();
6822 case T___noop: return parse_noop_expression();
6825 errorf(HERE, "unexpected token %K, expected an expression", &token);
6826 return create_invalid_expression();
6830 * Check if the expression has the character type and issue a warning then.
6832 static void check_for_char_index_type(const expression_t *expression)
6834 type_t *const type = expression->base.type;
6835 const type_t *const base_type = skip_typeref(type);
6837 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6838 warning.char_subscripts) {
6839 warningf(&expression->base.source_position,
6840 "array subscript has type '%T'", type);
6844 static expression_t *parse_array_expression(unsigned precedence,
6850 add_anchor_token(']');
6852 expression_t *inside = parse_expression();
6854 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6856 array_access_expression_t *array_access = &expression->array_access;
6858 type_t *const orig_type_left = left->base.type;
6859 type_t *const orig_type_inside = inside->base.type;
6861 type_t *const type_left = skip_typeref(orig_type_left);
6862 type_t *const type_inside = skip_typeref(orig_type_inside);
6864 type_t *return_type;
6865 if (is_type_pointer(type_left)) {
6866 return_type = type_left->pointer.points_to;
6867 array_access->array_ref = left;
6868 array_access->index = inside;
6869 check_for_char_index_type(inside);
6870 } else if (is_type_pointer(type_inside)) {
6871 return_type = type_inside->pointer.points_to;
6872 array_access->array_ref = inside;
6873 array_access->index = left;
6874 array_access->flipped = true;
6875 check_for_char_index_type(left);
6877 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6879 "array access on object with non-pointer types '%T', '%T'",
6880 orig_type_left, orig_type_inside);
6882 return_type = type_error_type;
6883 array_access->array_ref = left;
6884 array_access->index = inside;
6887 expression->base.type = automatic_type_conversion(return_type);
6889 rem_anchor_token(']');
6890 if (token.type == ']') {
6893 parse_error_expected("Problem while parsing array access", ']', NULL);
6898 static expression_t *parse_typeprop(expression_kind_t const kind,
6899 source_position_t const pos,
6900 unsigned const precedence)
6902 expression_t *tp_expression = allocate_expression_zero(kind);
6903 tp_expression->base.type = type_size_t;
6904 tp_expression->base.source_position = pos;
6906 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6908 /* we only refer to a type property, not the value, so do not warn
6909 * when using current_init_decl */
6910 declaration_t *old = current_init_decl;
6911 current_init_decl = NULL;
6912 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6914 add_anchor_token(')');
6915 type_t* const orig_type = parse_typename();
6916 tp_expression->typeprop.type = orig_type;
6918 type_t const* const type = skip_typeref(orig_type);
6919 char const* const wrong_type =
6920 is_type_incomplete(type) ? "incomplete" :
6921 type->kind == TYPE_FUNCTION ? "function designator" :
6922 type->kind == TYPE_BITFIELD ? "bitfield" :
6924 if (wrong_type != NULL) {
6925 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6926 what, wrong_type, type);
6929 rem_anchor_token(')');
6932 expression_t *expression = parse_sub_expression(precedence);
6934 type_t* const orig_type = revert_automatic_type_conversion(expression);
6935 expression->base.type = orig_type;
6937 type_t const* const type = skip_typeref(orig_type);
6938 char const* const wrong_type =
6939 is_type_incomplete(type) ? "incomplete" :
6940 type->kind == TYPE_FUNCTION ? "function designator" :
6941 type->kind == TYPE_BITFIELD ? "bitfield" :
6943 if (wrong_type != NULL) {
6944 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6947 tp_expression->typeprop.type = expression->base.type;
6948 tp_expression->typeprop.tp_expression = expression;
6952 current_init_decl = old;
6953 return tp_expression;
6956 static expression_t *parse_sizeof(unsigned precedence)
6958 source_position_t pos = *HERE;
6960 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6963 static expression_t *parse_alignof(unsigned precedence)
6965 source_position_t pos = *HERE;
6967 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6970 static expression_t *parse_select_expression(unsigned precedence,
6971 expression_t *compound)
6974 assert(token.type == '.' || token.type == T_MINUSGREATER);
6976 bool is_pointer = (token.type == T_MINUSGREATER);
6979 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6980 select->select.compound = compound;
6982 if (token.type != T_IDENTIFIER) {
6983 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6986 symbol_t *symbol = token.v.symbol;
6989 type_t *const orig_type = compound->base.type;
6990 type_t *const type = skip_typeref(orig_type);
6993 bool saw_error = false;
6994 if (is_type_pointer(type)) {
6997 "request for member '%Y' in something not a struct or union, but '%T'",
7001 type_left = skip_typeref(type->pointer.points_to);
7003 if (is_pointer && is_type_valid(type)) {
7004 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7010 declaration_t *entry;
7011 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7012 type_left->kind == TYPE_COMPOUND_UNION) {
7013 declaration_t *const declaration = type_left->compound.declaration;
7015 if (!declaration->init.complete) {
7016 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7018 goto create_error_entry;
7021 entry = find_compound_entry(declaration, symbol);
7022 if (entry == NULL) {
7023 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7024 goto create_error_entry;
7027 if (is_type_valid(type_left) && !saw_error) {
7029 "request for member '%Y' in something not a struct or union, but '%T'",
7033 entry = allocate_declaration_zero();
7034 entry->symbol = symbol;
7037 select->select.compound_entry = entry;
7039 type_t *const res_type =
7040 get_qualified_type(entry->type, type_left->base.qualifiers);
7042 /* we always do the auto-type conversions; the & and sizeof parser contains
7043 * code to revert this! */
7044 select->base.type = automatic_type_conversion(res_type);
7046 type_t *skipped = skip_typeref(res_type);
7047 if (skipped->kind == TYPE_BITFIELD) {
7048 select->base.type = skipped->bitfield.base_type;
7054 static void check_call_argument(const function_parameter_t *parameter,
7055 call_argument_t *argument, unsigned pos)
7057 type_t *expected_type = parameter->type;
7058 type_t *expected_type_skip = skip_typeref(expected_type);
7059 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7060 expression_t *arg_expr = argument->expression;
7061 type_t *arg_type = skip_typeref(arg_expr->base.type);
7063 /* handle transparent union gnu extension */
7064 if (is_type_union(expected_type_skip)
7065 && (expected_type_skip->base.modifiers
7066 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7067 declaration_t *union_decl = expected_type_skip->compound.declaration;
7069 declaration_t *declaration = union_decl->scope.declarations;
7070 type_t *best_type = NULL;
7071 for ( ; declaration != NULL; declaration = declaration->next) {
7072 type_t *decl_type = declaration->type;
7073 error = semantic_assign(decl_type, arg_expr);
7074 if (error == ASSIGN_ERROR_INCOMPATIBLE
7075 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7078 if (error == ASSIGN_SUCCESS) {
7079 best_type = decl_type;
7080 } else if (best_type == NULL) {
7081 best_type = decl_type;
7085 if (best_type != NULL) {
7086 expected_type = best_type;
7090 error = semantic_assign(expected_type, arg_expr);
7091 argument->expression = create_implicit_cast(argument->expression,
7094 if (error != ASSIGN_SUCCESS) {
7095 /* report exact scope in error messages (like "in argument 3") */
7097 snprintf(buf, sizeof(buf), "call argument %u", pos);
7098 report_assign_error(error, expected_type, arg_expr, buf,
7099 &arg_expr->base.source_position);
7100 } else if (warning.traditional || warning.conversion) {
7101 type_t *const promoted_type = get_default_promoted_type(arg_type);
7102 if (!types_compatible(expected_type_skip, promoted_type) &&
7103 !types_compatible(expected_type_skip, type_void_ptr) &&
7104 !types_compatible(type_void_ptr, promoted_type)) {
7105 /* Deliberately show the skipped types in this warning */
7106 warningf(&arg_expr->base.source_position,
7107 "passing call argument %u as '%T' rather than '%T' due to prototype",
7108 pos, expected_type_skip, promoted_type);
7114 * Parse a call expression, ie. expression '( ... )'.
7116 * @param expression the function address
7118 static expression_t *parse_call_expression(unsigned precedence,
7119 expression_t *expression)
7122 expression_t *result = allocate_expression_zero(EXPR_CALL);
7123 result->base.source_position = expression->base.source_position;
7125 call_expression_t *call = &result->call;
7126 call->function = expression;
7128 type_t *const orig_type = expression->base.type;
7129 type_t *const type = skip_typeref(orig_type);
7131 function_type_t *function_type = NULL;
7132 if (is_type_pointer(type)) {
7133 type_t *const to_type = skip_typeref(type->pointer.points_to);
7135 if (is_type_function(to_type)) {
7136 function_type = &to_type->function;
7137 call->base.type = function_type->return_type;
7141 if (function_type == NULL && is_type_valid(type)) {
7142 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7145 /* parse arguments */
7147 add_anchor_token(')');
7148 add_anchor_token(',');
7150 if (token.type != ')') {
7151 call_argument_t *last_argument = NULL;
7154 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7156 argument->expression = parse_assignment_expression();
7157 if (last_argument == NULL) {
7158 call->arguments = argument;
7160 last_argument->next = argument;
7162 last_argument = argument;
7164 if (token.type != ',')
7169 rem_anchor_token(',');
7170 rem_anchor_token(')');
7173 if (function_type == NULL)
7176 function_parameter_t *parameter = function_type->parameters;
7177 call_argument_t *argument = call->arguments;
7178 if (!function_type->unspecified_parameters) {
7179 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7180 parameter = parameter->next, argument = argument->next) {
7181 check_call_argument(parameter, argument, ++pos);
7184 if (parameter != NULL) {
7185 errorf(HERE, "too few arguments to function '%E'", expression);
7186 } else if (argument != NULL && !function_type->variadic) {
7187 errorf(HERE, "too many arguments to function '%E'", expression);
7191 /* do default promotion */
7192 for( ; argument != NULL; argument = argument->next) {
7193 type_t *type = argument->expression->base.type;
7195 type = get_default_promoted_type(type);
7197 argument->expression
7198 = create_implicit_cast(argument->expression, type);
7201 check_format(&result->call);
7203 if (warning.aggregate_return &&
7204 is_type_compound(skip_typeref(function_type->return_type))) {
7205 warningf(&result->base.source_position,
7206 "function call has aggregate value");
7213 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7215 static bool same_compound_type(const type_t *type1, const type_t *type2)
7218 is_type_compound(type1) &&
7219 type1->kind == type2->kind &&
7220 type1->compound.declaration == type2->compound.declaration;
7224 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7226 * @param expression the conditional expression
7228 static expression_t *parse_conditional_expression(unsigned precedence,
7229 expression_t *expression)
7231 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7233 conditional_expression_t *conditional = &result->conditional;
7234 conditional->base.source_position = *HERE;
7235 conditional->condition = expression;
7238 add_anchor_token(':');
7241 type_t *const condition_type_orig = expression->base.type;
7242 type_t *const condition_type = skip_typeref(condition_type_orig);
7243 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7244 type_error("expected a scalar type in conditional condition",
7245 &expression->base.source_position, condition_type_orig);
7248 expression_t *true_expression = expression;
7249 bool gnu_cond = false;
7250 if ((c_mode & _GNUC) && token.type == ':') {
7253 true_expression = parse_expression();
7254 rem_anchor_token(':');
7256 expression_t *false_expression = parse_sub_expression(precedence);
7258 type_t *const orig_true_type = true_expression->base.type;
7259 type_t *const orig_false_type = false_expression->base.type;
7260 type_t *const true_type = skip_typeref(orig_true_type);
7261 type_t *const false_type = skip_typeref(orig_false_type);
7264 type_t *result_type;
7265 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7266 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7267 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7268 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7269 warningf(&conditional->base.source_position,
7270 "ISO C forbids conditional expression with only one void side");
7272 result_type = type_void;
7273 } else if (is_type_arithmetic(true_type)
7274 && is_type_arithmetic(false_type)) {
7275 result_type = semantic_arithmetic(true_type, false_type);
7277 true_expression = create_implicit_cast(true_expression, result_type);
7278 false_expression = create_implicit_cast(false_expression, result_type);
7280 conditional->true_expression = true_expression;
7281 conditional->false_expression = false_expression;
7282 conditional->base.type = result_type;
7283 } else if (same_compound_type(true_type, false_type)) {
7284 /* just take 1 of the 2 types */
7285 result_type = true_type;
7286 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7287 type_t *pointer_type;
7289 expression_t *other_expression;
7290 if (is_type_pointer(true_type) &&
7291 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7292 pointer_type = true_type;
7293 other_type = false_type;
7294 other_expression = false_expression;
7296 pointer_type = false_type;
7297 other_type = true_type;
7298 other_expression = true_expression;
7301 if (is_null_pointer_constant(other_expression)) {
7302 result_type = pointer_type;
7303 } else if (is_type_pointer(other_type)) {
7304 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7305 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7308 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7309 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7311 } else if (types_compatible(get_unqualified_type(to1),
7312 get_unqualified_type(to2))) {
7315 warningf(&conditional->base.source_position,
7316 "pointer types '%T' and '%T' in conditional expression are incompatible",
7317 true_type, false_type);
7321 type_t *const type =
7322 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7323 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7324 } else if (is_type_integer(other_type)) {
7325 warningf(&conditional->base.source_position,
7326 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7327 result_type = pointer_type;
7329 type_error_incompatible("while parsing conditional",
7330 &expression->base.source_position, true_type, false_type);
7331 result_type = type_error_type;
7334 /* TODO: one pointer to void*, other some pointer */
7336 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7337 type_error_incompatible("while parsing conditional",
7338 &conditional->base.source_position, true_type,
7341 result_type = type_error_type;
7344 conditional->true_expression
7345 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7346 conditional->false_expression
7347 = create_implicit_cast(false_expression, result_type);
7348 conditional->base.type = result_type;
7351 return create_invalid_expression();
7355 * Parse an extension expression.
7357 static expression_t *parse_extension(unsigned precedence)
7359 eat(T___extension__);
7361 /* TODO enable extensions */
7362 expression_t *expression = parse_sub_expression(precedence);
7363 /* TODO disable extensions */
7368 * Parse a __builtin_classify_type() expression.
7370 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7372 eat(T___builtin_classify_type);
7374 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7375 result->base.type = type_int;
7378 add_anchor_token(')');
7379 expression_t *expression = parse_sub_expression(precedence);
7380 rem_anchor_token(')');
7382 result->classify_type.type_expression = expression;
7386 return create_invalid_expression();
7389 static bool check_pointer_arithmetic(const source_position_t *source_position,
7390 type_t *pointer_type,
7391 type_t *orig_pointer_type)
7393 type_t *points_to = pointer_type->pointer.points_to;
7394 points_to = skip_typeref(points_to);
7396 if (is_type_incomplete(points_to)) {
7397 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7398 errorf(source_position,
7399 "arithmetic with pointer to incomplete type '%T' not allowed",
7402 } else if (warning.pointer_arith) {
7403 warningf(source_position,
7404 "pointer of type '%T' used in arithmetic",
7407 } else if (is_type_function(points_to)) {
7408 if (!(c_mode && _GNUC)) {
7409 errorf(source_position,
7410 "arithmetic with pointer to function type '%T' not allowed",
7413 } else if (warning.pointer_arith) {
7414 warningf(source_position,
7415 "pointer to a function '%T' used in arithmetic",
7422 static bool is_lvalue(const expression_t *expression)
7424 switch (expression->kind) {
7425 case EXPR_REFERENCE:
7426 case EXPR_ARRAY_ACCESS:
7428 case EXPR_UNARY_DEREFERENCE:
7436 static void semantic_incdec(unary_expression_t *expression)
7438 type_t *const orig_type = expression->value->base.type;
7439 type_t *const type = skip_typeref(orig_type);
7440 if (is_type_pointer(type)) {
7441 if (!check_pointer_arithmetic(&expression->base.source_position,
7445 } else if (!is_type_real(type) && is_type_valid(type)) {
7446 /* TODO: improve error message */
7447 errorf(&expression->base.source_position,
7448 "operation needs an arithmetic or pointer type");
7451 if (!is_lvalue(expression->value)) {
7452 /* TODO: improve error message */
7453 errorf(&expression->base.source_position, "lvalue required as operand");
7455 expression->base.type = orig_type;
7458 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7460 type_t *const orig_type = expression->value->base.type;
7461 type_t *const type = skip_typeref(orig_type);
7462 if (!is_type_arithmetic(type)) {
7463 if (is_type_valid(type)) {
7464 /* TODO: improve error message */
7465 errorf(&expression->base.source_position,
7466 "operation needs an arithmetic type");
7471 expression->base.type = orig_type;
7474 static void semantic_unexpr_plus(unary_expression_t *expression)
7476 semantic_unexpr_arithmetic(expression);
7477 if (warning.traditional)
7478 warningf(&expression->base.source_position,
7479 "traditional C rejects the unary plus operator");
7482 static void semantic_not(unary_expression_t *expression)
7484 type_t *const orig_type = expression->value->base.type;
7485 type_t *const type = skip_typeref(orig_type);
7486 if (!is_type_scalar(type) && is_type_valid(type)) {
7487 errorf(&expression->base.source_position,
7488 "operand of ! must be of scalar type");
7491 expression->base.type = type_int;
7494 static void semantic_unexpr_integer(unary_expression_t *expression)
7496 type_t *const orig_type = expression->value->base.type;
7497 type_t *const type = skip_typeref(orig_type);
7498 if (!is_type_integer(type)) {
7499 if (is_type_valid(type)) {
7500 errorf(&expression->base.source_position,
7501 "operand of ~ must be of integer type");
7506 expression->base.type = orig_type;
7509 static void semantic_dereference(unary_expression_t *expression)
7511 type_t *const orig_type = expression->value->base.type;
7512 type_t *const type = skip_typeref(orig_type);
7513 if (!is_type_pointer(type)) {
7514 if (is_type_valid(type)) {
7515 errorf(&expression->base.source_position,
7516 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7521 type_t *result_type = type->pointer.points_to;
7522 result_type = automatic_type_conversion(result_type);
7523 expression->base.type = result_type;
7527 * Record that an address is taken (expression represents an lvalue).
7529 * @param expression the expression
7530 * @param may_be_register if true, the expression might be an register
7532 static void set_address_taken(expression_t *expression, bool may_be_register)
7534 if (expression->kind != EXPR_REFERENCE)
7537 declaration_t *const declaration = expression->reference.declaration;
7538 /* happens for parse errors */
7539 if (declaration == NULL)
7542 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7543 errorf(&expression->base.source_position,
7544 "address of register variable '%Y' requested",
7545 declaration->symbol);
7547 declaration->address_taken = 1;
7552 * Check the semantic of the address taken expression.
7554 static void semantic_take_addr(unary_expression_t *expression)
7556 expression_t *value = expression->value;
7557 value->base.type = revert_automatic_type_conversion(value);
7559 type_t *orig_type = value->base.type;
7560 if (!is_type_valid(orig_type))
7563 set_address_taken(value, false);
7565 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7568 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7569 static expression_t *parse_##unexpression_type(unsigned precedence) \
7571 expression_t *unary_expression \
7572 = allocate_expression_zero(unexpression_type); \
7573 unary_expression->base.source_position = *HERE; \
7575 unary_expression->unary.value = parse_sub_expression(precedence); \
7577 sfunc(&unary_expression->unary); \
7579 return unary_expression; \
7582 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7583 semantic_unexpr_arithmetic)
7584 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7585 semantic_unexpr_plus)
7586 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7588 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7589 semantic_dereference)
7590 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7592 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7593 semantic_unexpr_integer)
7594 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7596 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7599 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7601 static expression_t *parse_##unexpression_type(unsigned precedence, \
7602 expression_t *left) \
7604 (void) precedence; \
7606 expression_t *unary_expression \
7607 = allocate_expression_zero(unexpression_type); \
7608 unary_expression->base.source_position = *HERE; \
7610 unary_expression->unary.value = left; \
7612 sfunc(&unary_expression->unary); \
7614 return unary_expression; \
7617 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7618 EXPR_UNARY_POSTFIX_INCREMENT,
7620 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7621 EXPR_UNARY_POSTFIX_DECREMENT,
7624 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7626 /* TODO: handle complex + imaginary types */
7628 type_left = get_unqualified_type(type_left);
7629 type_right = get_unqualified_type(type_right);
7631 /* § 6.3.1.8 Usual arithmetic conversions */
7632 if (type_left == type_long_double || type_right == type_long_double) {
7633 return type_long_double;
7634 } else if (type_left == type_double || type_right == type_double) {
7636 } else if (type_left == type_float || type_right == type_float) {
7640 type_left = promote_integer(type_left);
7641 type_right = promote_integer(type_right);
7643 if (type_left == type_right)
7646 bool const signed_left = is_type_signed(type_left);
7647 bool const signed_right = is_type_signed(type_right);
7648 int const rank_left = get_rank(type_left);
7649 int const rank_right = get_rank(type_right);
7651 if (signed_left == signed_right)
7652 return rank_left >= rank_right ? type_left : type_right;
7661 u_rank = rank_right;
7662 u_type = type_right;
7664 s_rank = rank_right;
7665 s_type = type_right;
7670 if (u_rank >= s_rank)
7673 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7675 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7676 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7680 case ATOMIC_TYPE_INT: return type_unsigned_int;
7681 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7682 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7684 default: panic("invalid atomic type");
7689 * Check the semantic restrictions for a binary expression.
7691 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7693 expression_t *const left = expression->left;
7694 expression_t *const right = expression->right;
7695 type_t *const orig_type_left = left->base.type;
7696 type_t *const orig_type_right = right->base.type;
7697 type_t *const type_left = skip_typeref(orig_type_left);
7698 type_t *const type_right = skip_typeref(orig_type_right);
7700 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7701 /* TODO: improve error message */
7702 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7703 errorf(&expression->base.source_position,
7704 "operation needs arithmetic types");
7709 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7710 expression->left = create_implicit_cast(left, arithmetic_type);
7711 expression->right = create_implicit_cast(right, arithmetic_type);
7712 expression->base.type = arithmetic_type;
7715 static void warn_div_by_zero(binary_expression_t const *const expression)
7717 if (!warning.div_by_zero ||
7718 !is_type_integer(expression->base.type))
7721 expression_t const *const right = expression->right;
7722 /* The type of the right operand can be different for /= */
7723 if (is_type_integer(right->base.type) &&
7724 is_constant_expression(right) &&
7725 fold_constant(right) == 0) {
7726 warningf(&expression->base.source_position, "division by zero");
7731 * Check the semantic restrictions for a div/mod expression.
7733 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7734 semantic_binexpr_arithmetic(expression);
7735 warn_div_by_zero(expression);
7738 static void semantic_shift_op(binary_expression_t *expression)
7740 expression_t *const left = expression->left;
7741 expression_t *const right = expression->right;
7742 type_t *const orig_type_left = left->base.type;
7743 type_t *const orig_type_right = right->base.type;
7744 type_t * type_left = skip_typeref(orig_type_left);
7745 type_t * type_right = skip_typeref(orig_type_right);
7747 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7748 /* TODO: improve error message */
7749 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7750 errorf(&expression->base.source_position,
7751 "operands of shift operation must have integer types");
7756 type_left = promote_integer(type_left);
7757 type_right = promote_integer(type_right);
7759 expression->left = create_implicit_cast(left, type_left);
7760 expression->right = create_implicit_cast(right, type_right);
7761 expression->base.type = type_left;
7764 static void semantic_add(binary_expression_t *expression)
7766 expression_t *const left = expression->left;
7767 expression_t *const right = expression->right;
7768 type_t *const orig_type_left = left->base.type;
7769 type_t *const orig_type_right = right->base.type;
7770 type_t *const type_left = skip_typeref(orig_type_left);
7771 type_t *const type_right = skip_typeref(orig_type_right);
7774 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7775 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7776 expression->left = create_implicit_cast(left, arithmetic_type);
7777 expression->right = create_implicit_cast(right, arithmetic_type);
7778 expression->base.type = arithmetic_type;
7780 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7781 check_pointer_arithmetic(&expression->base.source_position,
7782 type_left, orig_type_left);
7783 expression->base.type = type_left;
7784 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7785 check_pointer_arithmetic(&expression->base.source_position,
7786 type_right, orig_type_right);
7787 expression->base.type = type_right;
7788 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7789 errorf(&expression->base.source_position,
7790 "invalid operands to binary + ('%T', '%T')",
7791 orig_type_left, orig_type_right);
7795 static void semantic_sub(binary_expression_t *expression)
7797 expression_t *const left = expression->left;
7798 expression_t *const right = expression->right;
7799 type_t *const orig_type_left = left->base.type;
7800 type_t *const orig_type_right = right->base.type;
7801 type_t *const type_left = skip_typeref(orig_type_left);
7802 type_t *const type_right = skip_typeref(orig_type_right);
7803 source_position_t const *const pos = &expression->base.source_position;
7806 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7807 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7808 expression->left = create_implicit_cast(left, arithmetic_type);
7809 expression->right = create_implicit_cast(right, arithmetic_type);
7810 expression->base.type = arithmetic_type;
7812 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7813 check_pointer_arithmetic(&expression->base.source_position,
7814 type_left, orig_type_left);
7815 expression->base.type = type_left;
7816 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7817 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7818 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7819 if (!types_compatible(unqual_left, unqual_right)) {
7821 "subtracting pointers to incompatible types '%T' and '%T'",
7822 orig_type_left, orig_type_right);
7823 } else if (!is_type_object(unqual_left)) {
7824 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7825 warningf(pos, "subtracting pointers to void");
7827 errorf(pos, "subtracting pointers to non-object types '%T'",
7831 expression->base.type = type_ptrdiff_t;
7832 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7833 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7834 orig_type_left, orig_type_right);
7839 * Check the semantics of comparison expressions.
7841 * @param expression The expression to check.
7843 static void semantic_comparison(binary_expression_t *expression)
7845 expression_t *left = expression->left;
7846 expression_t *right = expression->right;
7847 type_t *orig_type_left = left->base.type;
7848 type_t *orig_type_right = right->base.type;
7850 type_t *type_left = skip_typeref(orig_type_left);
7851 type_t *type_right = skip_typeref(orig_type_right);
7853 /* TODO non-arithmetic types */
7854 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7855 /* test for signed vs unsigned compares */
7856 if (warning.sign_compare &&
7857 (expression->base.kind != EXPR_BINARY_EQUAL &&
7858 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7859 (is_type_signed(type_left) != is_type_signed(type_right))) {
7861 /* check if 1 of the operands is a constant, in this case we just
7862 * check wether we can safely represent the resulting constant in
7863 * the type of the other operand. */
7864 expression_t *const_expr = NULL;
7865 expression_t *other_expr = NULL;
7867 if (is_constant_expression(left)) {
7870 } else if (is_constant_expression(right)) {
7875 if (const_expr != NULL) {
7876 type_t *other_type = skip_typeref(other_expr->base.type);
7877 long val = fold_constant(const_expr);
7878 /* TODO: check if val can be represented by other_type */
7882 warningf(&expression->base.source_position,
7883 "comparison between signed and unsigned");
7885 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7886 expression->left = create_implicit_cast(left, arithmetic_type);
7887 expression->right = create_implicit_cast(right, arithmetic_type);
7888 expression->base.type = arithmetic_type;
7889 if (warning.float_equal &&
7890 (expression->base.kind == EXPR_BINARY_EQUAL ||
7891 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7892 is_type_float(arithmetic_type)) {
7893 warningf(&expression->base.source_position,
7894 "comparing floating point with == or != is unsafe");
7896 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7897 /* TODO check compatibility */
7898 } else if (is_type_pointer(type_left)) {
7899 expression->right = create_implicit_cast(right, type_left);
7900 } else if (is_type_pointer(type_right)) {
7901 expression->left = create_implicit_cast(left, type_right);
7902 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7903 type_error_incompatible("invalid operands in comparison",
7904 &expression->base.source_position,
7905 type_left, type_right);
7907 expression->base.type = type_int;
7911 * Checks if a compound type has constant fields.
7913 static bool has_const_fields(const compound_type_t *type)
7915 const scope_t *scope = &type->declaration->scope;
7916 const declaration_t *declaration = scope->declarations;
7918 for (; declaration != NULL; declaration = declaration->next) {
7919 if (declaration->namespc != NAMESPACE_NORMAL)
7922 const type_t *decl_type = skip_typeref(declaration->type);
7923 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7930 static bool is_valid_assignment_lhs(expression_t const* const left)
7932 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7933 type_t *const type_left = skip_typeref(orig_type_left);
7935 if (!is_lvalue(left)) {
7936 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7941 if (is_type_array(type_left)) {
7942 errorf(HERE, "cannot assign to arrays ('%E')", left);
7945 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7946 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7950 if (is_type_incomplete(type_left)) {
7951 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7952 left, orig_type_left);
7955 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7956 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7957 left, orig_type_left);
7964 static void semantic_arithmetic_assign(binary_expression_t *expression)
7966 expression_t *left = expression->left;
7967 expression_t *right = expression->right;
7968 type_t *orig_type_left = left->base.type;
7969 type_t *orig_type_right = right->base.type;
7971 if (!is_valid_assignment_lhs(left))
7974 type_t *type_left = skip_typeref(orig_type_left);
7975 type_t *type_right = skip_typeref(orig_type_right);
7977 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7978 /* TODO: improve error message */
7979 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7980 errorf(&expression->base.source_position,
7981 "operation needs arithmetic types");
7986 /* combined instructions are tricky. We can't create an implicit cast on
7987 * the left side, because we need the uncasted form for the store.
7988 * The ast2firm pass has to know that left_type must be right_type
7989 * for the arithmetic operation and create a cast by itself */
7990 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7991 expression->right = create_implicit_cast(right, arithmetic_type);
7992 expression->base.type = type_left;
7995 static void semantic_divmod_assign(binary_expression_t *expression)
7997 semantic_arithmetic_assign(expression);
7998 warn_div_by_zero(expression);
8001 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8003 expression_t *const left = expression->left;
8004 expression_t *const right = expression->right;
8005 type_t *const orig_type_left = left->base.type;
8006 type_t *const orig_type_right = right->base.type;
8007 type_t *const type_left = skip_typeref(orig_type_left);
8008 type_t *const type_right = skip_typeref(orig_type_right);
8010 if (!is_valid_assignment_lhs(left))
8013 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8014 /* combined instructions are tricky. We can't create an implicit cast on
8015 * the left side, because we need the uncasted form for the store.
8016 * The ast2firm pass has to know that left_type must be right_type
8017 * for the arithmetic operation and create a cast by itself */
8018 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8019 expression->right = create_implicit_cast(right, arithmetic_type);
8020 expression->base.type = type_left;
8021 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8022 check_pointer_arithmetic(&expression->base.source_position,
8023 type_left, orig_type_left);
8024 expression->base.type = type_left;
8025 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8026 errorf(&expression->base.source_position,
8027 "incompatible types '%T' and '%T' in assignment",
8028 orig_type_left, orig_type_right);
8033 * Check the semantic restrictions of a logical expression.
8035 static void semantic_logical_op(binary_expression_t *expression)
8037 expression_t *const left = expression->left;
8038 expression_t *const right = expression->right;
8039 type_t *const orig_type_left = left->base.type;
8040 type_t *const orig_type_right = right->base.type;
8041 type_t *const type_left = skip_typeref(orig_type_left);
8042 type_t *const type_right = skip_typeref(orig_type_right);
8044 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8045 /* TODO: improve error message */
8046 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8047 errorf(&expression->base.source_position,
8048 "operation needs scalar types");
8053 expression->base.type = type_int;
8057 * Check the semantic restrictions of a binary assign expression.
8059 static void semantic_binexpr_assign(binary_expression_t *expression)
8061 expression_t *left = expression->left;
8062 type_t *orig_type_left = left->base.type;
8064 if (!is_valid_assignment_lhs(left))
8067 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8068 report_assign_error(error, orig_type_left, expression->right,
8069 "assignment", &left->base.source_position);
8070 expression->right = create_implicit_cast(expression->right, orig_type_left);
8071 expression->base.type = orig_type_left;
8075 * Determine if the outermost operation (or parts thereof) of the given
8076 * expression has no effect in order to generate a warning about this fact.
8077 * Therefore in some cases this only examines some of the operands of the
8078 * expression (see comments in the function and examples below).
8080 * f() + 23; // warning, because + has no effect
8081 * x || f(); // no warning, because x controls execution of f()
8082 * x ? y : f(); // warning, because y has no effect
8083 * (void)x; // no warning to be able to suppress the warning
8084 * This function can NOT be used for an "expression has definitely no effect"-
8086 static bool expression_has_effect(const expression_t *const expr)
8088 switch (expr->kind) {
8089 case EXPR_UNKNOWN: break;
8090 case EXPR_INVALID: return true; /* do NOT warn */
8091 case EXPR_REFERENCE: return false;
8092 /* suppress the warning for microsoft __noop operations */
8093 case EXPR_CONST: return expr->conste.is_ms_noop;
8094 case EXPR_CHARACTER_CONSTANT: return false;
8095 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8096 case EXPR_STRING_LITERAL: return false;
8097 case EXPR_WIDE_STRING_LITERAL: return false;
8098 case EXPR_LABEL_ADDRESS: return false;
8101 const call_expression_t *const call = &expr->call;
8102 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8105 switch (call->function->builtin_symbol.symbol->ID) {
8106 case T___builtin_va_end: return true;
8107 default: return false;
8111 /* Generate the warning if either the left or right hand side of a
8112 * conditional expression has no effect */
8113 case EXPR_CONDITIONAL: {
8114 const conditional_expression_t *const cond = &expr->conditional;
8116 expression_has_effect(cond->true_expression) &&
8117 expression_has_effect(cond->false_expression);
8120 case EXPR_SELECT: return false;
8121 case EXPR_ARRAY_ACCESS: return false;
8122 case EXPR_SIZEOF: return false;
8123 case EXPR_CLASSIFY_TYPE: return false;
8124 case EXPR_ALIGNOF: return false;
8126 case EXPR_FUNCNAME: return false;
8127 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8128 case EXPR_BUILTIN_CONSTANT_P: return false;
8129 case EXPR_BUILTIN_PREFETCH: return true;
8130 case EXPR_OFFSETOF: return false;
8131 case EXPR_VA_START: return true;
8132 case EXPR_VA_ARG: return true;
8133 case EXPR_STATEMENT: return true; // TODO
8134 case EXPR_COMPOUND_LITERAL: return false;
8136 case EXPR_UNARY_NEGATE: return false;
8137 case EXPR_UNARY_PLUS: return false;
8138 case EXPR_UNARY_BITWISE_NEGATE: return false;
8139 case EXPR_UNARY_NOT: return false;
8140 case EXPR_UNARY_DEREFERENCE: return false;
8141 case EXPR_UNARY_TAKE_ADDRESS: return false;
8142 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8143 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8144 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8145 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8147 /* Treat void casts as if they have an effect in order to being able to
8148 * suppress the warning */
8149 case EXPR_UNARY_CAST: {
8150 type_t *const type = skip_typeref(expr->base.type);
8151 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8154 case EXPR_UNARY_CAST_IMPLICIT: return true;
8155 case EXPR_UNARY_ASSUME: return true;
8157 case EXPR_BINARY_ADD: return false;
8158 case EXPR_BINARY_SUB: return false;
8159 case EXPR_BINARY_MUL: return false;
8160 case EXPR_BINARY_DIV: return false;
8161 case EXPR_BINARY_MOD: return false;
8162 case EXPR_BINARY_EQUAL: return false;
8163 case EXPR_BINARY_NOTEQUAL: return false;
8164 case EXPR_BINARY_LESS: return false;
8165 case EXPR_BINARY_LESSEQUAL: return false;
8166 case EXPR_BINARY_GREATER: return false;
8167 case EXPR_BINARY_GREATEREQUAL: return false;
8168 case EXPR_BINARY_BITWISE_AND: return false;
8169 case EXPR_BINARY_BITWISE_OR: return false;
8170 case EXPR_BINARY_BITWISE_XOR: return false;
8171 case EXPR_BINARY_SHIFTLEFT: return false;
8172 case EXPR_BINARY_SHIFTRIGHT: return false;
8173 case EXPR_BINARY_ASSIGN: return true;
8174 case EXPR_BINARY_MUL_ASSIGN: return true;
8175 case EXPR_BINARY_DIV_ASSIGN: return true;
8176 case EXPR_BINARY_MOD_ASSIGN: return true;
8177 case EXPR_BINARY_ADD_ASSIGN: return true;
8178 case EXPR_BINARY_SUB_ASSIGN: return true;
8179 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8180 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8181 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8182 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8183 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8185 /* Only examine the right hand side of && and ||, because the left hand
8186 * side already has the effect of controlling the execution of the right
8188 case EXPR_BINARY_LOGICAL_AND:
8189 case EXPR_BINARY_LOGICAL_OR:
8190 /* Only examine the right hand side of a comma expression, because the left
8191 * hand side has a separate warning */
8192 case EXPR_BINARY_COMMA:
8193 return expression_has_effect(expr->binary.right);
8195 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8196 case EXPR_BINARY_ISGREATER: return false;
8197 case EXPR_BINARY_ISGREATEREQUAL: return false;
8198 case EXPR_BINARY_ISLESS: return false;
8199 case EXPR_BINARY_ISLESSEQUAL: return false;
8200 case EXPR_BINARY_ISLESSGREATER: return false;
8201 case EXPR_BINARY_ISUNORDERED: return false;
8204 internal_errorf(HERE, "unexpected expression");
8207 static void semantic_comma(binary_expression_t *expression)
8209 if (warning.unused_value) {
8210 const expression_t *const left = expression->left;
8211 if (!expression_has_effect(left)) {
8212 warningf(&left->base.source_position,
8213 "left-hand operand of comma expression has no effect");
8216 expression->base.type = expression->right->base.type;
8219 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8220 static expression_t *parse_##binexpression_type(unsigned precedence, \
8221 expression_t *left) \
8223 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8224 binexpr->base.source_position = *HERE; \
8225 binexpr->binary.left = left; \
8228 expression_t *right = parse_sub_expression(precedence + lr); \
8230 binexpr->binary.right = right; \
8231 sfunc(&binexpr->binary); \
8236 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8237 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8238 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8239 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8240 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8241 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8242 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8243 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8244 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8246 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8247 semantic_comparison, 1)
8248 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8249 semantic_comparison, 1)
8250 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8251 semantic_comparison, 1)
8252 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8253 semantic_comparison, 1)
8255 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8256 semantic_binexpr_arithmetic, 1)
8257 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8258 semantic_binexpr_arithmetic, 1)
8259 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8260 semantic_binexpr_arithmetic, 1)
8261 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8262 semantic_logical_op, 1)
8263 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8264 semantic_logical_op, 1)
8265 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8266 semantic_shift_op, 1)
8267 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8268 semantic_shift_op, 1)
8269 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8270 semantic_arithmetic_addsubb_assign, 0)
8271 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8272 semantic_arithmetic_addsubb_assign, 0)
8273 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8274 semantic_arithmetic_assign, 0)
8275 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8276 semantic_divmod_assign, 0)
8277 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8278 semantic_divmod_assign, 0)
8279 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8280 semantic_arithmetic_assign, 0)
8281 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8282 semantic_arithmetic_assign, 0)
8283 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8284 semantic_arithmetic_assign, 0)
8285 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8286 semantic_arithmetic_assign, 0)
8287 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8288 semantic_arithmetic_assign, 0)
8290 static expression_t *parse_sub_expression(unsigned precedence)
8292 if (token.type < 0) {
8293 return expected_expression_error();
8296 expression_parser_function_t *parser
8297 = &expression_parsers[token.type];
8298 source_position_t source_position = token.source_position;
8301 if (parser->parser != NULL) {
8302 left = parser->parser(parser->precedence);
8304 left = parse_primary_expression();
8306 assert(left != NULL);
8307 left->base.source_position = source_position;
8310 if (token.type < 0) {
8311 return expected_expression_error();
8314 parser = &expression_parsers[token.type];
8315 if (parser->infix_parser == NULL)
8317 if (parser->infix_precedence < precedence)
8320 left = parser->infix_parser(parser->infix_precedence, left);
8322 assert(left != NULL);
8323 assert(left->kind != EXPR_UNKNOWN);
8324 left->base.source_position = source_position;
8331 * Parse an expression.
8333 static expression_t *parse_expression(void)
8335 return parse_sub_expression(1);
8339 * Register a parser for a prefix-like operator with given precedence.
8341 * @param parser the parser function
8342 * @param token_type the token type of the prefix token
8343 * @param precedence the precedence of the operator
8345 static void register_expression_parser(parse_expression_function parser,
8346 int token_type, unsigned precedence)
8348 expression_parser_function_t *entry = &expression_parsers[token_type];
8350 if (entry->parser != NULL) {
8351 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8352 panic("trying to register multiple expression parsers for a token");
8354 entry->parser = parser;
8355 entry->precedence = precedence;
8359 * Register a parser for an infix operator with given precedence.
8361 * @param parser the parser function
8362 * @param token_type the token type of the infix operator
8363 * @param precedence the precedence of the operator
8365 static void register_infix_parser(parse_expression_infix_function parser,
8366 int token_type, unsigned precedence)
8368 expression_parser_function_t *entry = &expression_parsers[token_type];
8370 if (entry->infix_parser != NULL) {
8371 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8372 panic("trying to register multiple infix expression parsers for a "
8375 entry->infix_parser = parser;
8376 entry->infix_precedence = precedence;
8380 * Initialize the expression parsers.
8382 static void init_expression_parsers(void)
8384 memset(&expression_parsers, 0, sizeof(expression_parsers));
8386 register_infix_parser(parse_array_expression, '[', 30);
8387 register_infix_parser(parse_call_expression, '(', 30);
8388 register_infix_parser(parse_select_expression, '.', 30);
8389 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8390 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8392 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8395 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8396 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8397 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8398 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8399 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8400 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8401 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8402 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8403 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8404 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8405 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8406 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8407 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8408 T_EXCLAMATIONMARKEQUAL, 13);
8409 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8410 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8411 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8412 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8413 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8414 register_infix_parser(parse_conditional_expression, '?', 7);
8415 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8416 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8417 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8418 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8419 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8420 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8421 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8422 T_LESSLESSEQUAL, 2);
8423 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8424 T_GREATERGREATEREQUAL, 2);
8425 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8427 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8429 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8432 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8434 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8435 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8436 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8437 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8438 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8439 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8440 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8442 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8444 register_expression_parser(parse_sizeof, T_sizeof, 25);
8445 register_expression_parser(parse_alignof, T___alignof__, 25);
8446 register_expression_parser(parse_extension, T___extension__, 25);
8447 register_expression_parser(parse_builtin_classify_type,
8448 T___builtin_classify_type, 25);
8452 * Parse a asm statement arguments specification.
8454 static asm_argument_t *parse_asm_arguments(bool is_out)
8456 asm_argument_t *result = NULL;
8457 asm_argument_t *last = NULL;
8459 while (token.type == T_STRING_LITERAL || token.type == '[') {
8460 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8461 memset(argument, 0, sizeof(argument[0]));
8463 if (token.type == '[') {
8465 if (token.type != T_IDENTIFIER) {
8466 parse_error_expected("while parsing asm argument",
8467 T_IDENTIFIER, NULL);
8470 argument->symbol = token.v.symbol;
8475 argument->constraints = parse_string_literals();
8477 add_anchor_token(')');
8478 expression_t *expression = parse_expression();
8479 rem_anchor_token(')');
8481 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8482 * change size or type representation (e.g. int -> long is ok, but
8483 * int -> float is not) */
8484 if (expression->kind == EXPR_UNARY_CAST) {
8485 type_t *const type = expression->base.type;
8486 type_kind_t const kind = type->kind;
8487 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8490 if (kind == TYPE_ATOMIC) {
8491 atomic_type_kind_t const akind = type->atomic.akind;
8492 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8493 size = get_atomic_type_size(akind);
8495 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8496 size = get_atomic_type_size(get_intptr_kind());
8500 expression_t *const value = expression->unary.value;
8501 type_t *const value_type = value->base.type;
8502 type_kind_t const value_kind = value_type->kind;
8504 unsigned value_flags;
8505 unsigned value_size;
8506 if (value_kind == TYPE_ATOMIC) {
8507 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8508 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8509 value_size = get_atomic_type_size(value_akind);
8510 } else if (value_kind == TYPE_POINTER) {
8511 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8512 value_size = get_atomic_type_size(get_intptr_kind());
8517 if (value_flags != flags || value_size != size)
8521 } while (expression->kind == EXPR_UNARY_CAST);
8525 if (!is_lvalue(expression)) {
8526 errorf(&expression->base.source_position,
8527 "asm output argument is not an lvalue");
8530 argument->expression = expression;
8533 set_address_taken(expression, true);
8536 last->next = argument;
8542 if (token.type != ',')
8553 * Parse a asm statement clobber specification.
8555 static asm_clobber_t *parse_asm_clobbers(void)
8557 asm_clobber_t *result = NULL;
8558 asm_clobber_t *last = NULL;
8560 while(token.type == T_STRING_LITERAL) {
8561 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8562 clobber->clobber = parse_string_literals();
8565 last->next = clobber;
8571 if (token.type != ',')
8580 * Parse an asm statement.
8582 static statement_t *parse_asm_statement(void)
8586 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8587 statement->base.source_position = token.source_position;
8589 asm_statement_t *asm_statement = &statement->asms;
8591 if (token.type == T_volatile) {
8593 asm_statement->is_volatile = true;
8597 add_anchor_token(')');
8598 add_anchor_token(':');
8599 asm_statement->asm_text = parse_string_literals();
8601 if (token.type != ':') {
8602 rem_anchor_token(':');
8607 asm_statement->outputs = parse_asm_arguments(true);
8608 if (token.type != ':') {
8609 rem_anchor_token(':');
8614 asm_statement->inputs = parse_asm_arguments(false);
8615 if (token.type != ':') {
8616 rem_anchor_token(':');
8619 rem_anchor_token(':');
8622 asm_statement->clobbers = parse_asm_clobbers();
8625 rem_anchor_token(')');
8629 if (asm_statement->outputs == NULL) {
8630 /* GCC: An 'asm' instruction without any output operands will be treated
8631 * identically to a volatile 'asm' instruction. */
8632 asm_statement->is_volatile = true;
8637 return create_invalid_statement();
8641 * Parse a case statement.
8643 static statement_t *parse_case_statement(void)
8647 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8648 source_position_t *const pos = &statement->base.source_position;
8650 *pos = token.source_position;
8651 expression_t *const expression = parse_expression();
8652 statement->case_label.expression = expression;
8653 if (!is_constant_expression(expression)) {
8654 /* This check does not prevent the error message in all cases of an
8655 * prior error while parsing the expression. At least it catches the
8656 * common case of a mistyped enum entry. */
8657 if (is_type_valid(expression->base.type)) {
8658 errorf(pos, "case label does not reduce to an integer constant");
8660 statement->case_label.is_bad = true;
8662 long const val = fold_constant(expression);
8663 statement->case_label.first_case = val;
8664 statement->case_label.last_case = val;
8667 if (c_mode & _GNUC) {
8668 if (token.type == T_DOTDOTDOT) {
8670 expression_t *const end_range = parse_expression();
8671 statement->case_label.end_range = end_range;
8672 if (!is_constant_expression(end_range)) {
8673 /* This check does not prevent the error message in all cases of an
8674 * prior error while parsing the expression. At least it catches the
8675 * common case of a mistyped enum entry. */
8676 if (is_type_valid(end_range->base.type)) {
8677 errorf(pos, "case range does not reduce to an integer constant");
8679 statement->case_label.is_bad = true;
8681 long const val = fold_constant(end_range);
8682 statement->case_label.last_case = val;
8684 if (val < statement->case_label.first_case) {
8685 statement->case_label.is_empty_range = true;
8686 warningf(pos, "empty range specified");
8692 PUSH_PARENT(statement);
8696 if (current_switch != NULL) {
8697 if (! statement->case_label.is_bad) {
8698 /* Check for duplicate case values */
8699 case_label_statement_t *c = &statement->case_label;
8700 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8701 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8704 if (c->last_case < l->first_case || c->first_case > l->last_case)
8707 errorf(pos, "duplicate case value (previously used %P)",
8708 &l->base.source_position);
8712 /* link all cases into the switch statement */
8713 if (current_switch->last_case == NULL) {
8714 current_switch->first_case = &statement->case_label;
8716 current_switch->last_case->next = &statement->case_label;
8718 current_switch->last_case = &statement->case_label;
8720 errorf(pos, "case label not within a switch statement");
8723 statement_t *const inner_stmt = parse_statement();
8724 statement->case_label.statement = inner_stmt;
8725 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8726 errorf(&inner_stmt->base.source_position, "declaration after case label");
8733 return create_invalid_statement();
8737 * Parse a default statement.
8739 static statement_t *parse_default_statement(void)
8743 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8744 statement->base.source_position = token.source_position;
8746 PUSH_PARENT(statement);
8749 if (current_switch != NULL) {
8750 const case_label_statement_t *def_label = current_switch->default_label;
8751 if (def_label != NULL) {
8752 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8753 &def_label->base.source_position);
8755 current_switch->default_label = &statement->case_label;
8757 /* link all cases into the switch statement */
8758 if (current_switch->last_case == NULL) {
8759 current_switch->first_case = &statement->case_label;
8761 current_switch->last_case->next = &statement->case_label;
8763 current_switch->last_case = &statement->case_label;
8766 errorf(&statement->base.source_position,
8767 "'default' label not within a switch statement");
8770 statement_t *const inner_stmt = parse_statement();
8771 statement->case_label.statement = inner_stmt;
8772 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8773 errorf(&inner_stmt->base.source_position, "declaration after default label");
8780 return create_invalid_statement();
8784 * Parse a label statement.
8786 static statement_t *parse_label_statement(void)
8788 assert(token.type == T_IDENTIFIER);
8789 symbol_t *symbol = token.v.symbol;
8792 declaration_t *label = get_label(symbol);
8794 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8795 statement->base.source_position = token.source_position;
8796 statement->label.label = label;
8798 PUSH_PARENT(statement);
8800 /* if statement is already set then the label is defined twice,
8801 * otherwise it was just mentioned in a goto/local label declaration so far */
8802 if (label->init.statement != NULL) {
8803 errorf(HERE, "duplicate label '%Y' (declared %P)",
8804 symbol, &label->source_position);
8806 label->source_position = token.source_position;
8807 label->init.statement = statement;
8812 if (token.type == '}') {
8813 /* TODO only warn? */
8815 warningf(HERE, "label at end of compound statement");
8816 statement->label.statement = create_empty_statement();
8818 errorf(HERE, "label at end of compound statement");
8819 statement->label.statement = create_invalid_statement();
8821 } else if (token.type == ';') {
8822 /* Eat an empty statement here, to avoid the warning about an empty
8823 * statement after a label. label:; is commonly used to have a label
8824 * before a closing brace. */
8825 statement->label.statement = create_empty_statement();
8828 statement_t *const inner_stmt = parse_statement();
8829 statement->label.statement = inner_stmt;
8830 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8831 errorf(&inner_stmt->base.source_position, "declaration after label");
8835 /* remember the labels in a list for later checking */
8836 if (label_last == NULL) {
8837 label_first = &statement->label;
8839 label_last->next = &statement->label;
8841 label_last = &statement->label;
8848 * Parse an if statement.
8850 static statement_t *parse_if(void)
8854 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8855 statement->base.source_position = token.source_position;
8857 PUSH_PARENT(statement);
8860 add_anchor_token(')');
8861 statement->ifs.condition = parse_expression();
8862 rem_anchor_token(')');
8865 add_anchor_token(T_else);
8866 statement->ifs.true_statement = parse_statement();
8867 rem_anchor_token(T_else);
8869 if (token.type == T_else) {
8871 statement->ifs.false_statement = parse_statement();
8878 return create_invalid_statement();
8882 * Check that all enums are handled in a switch.
8884 * @param statement the switch statement to check
8886 static void check_enum_cases(const switch_statement_t *statement) {
8887 const type_t *type = skip_typeref(statement->expression->base.type);
8888 if (! is_type_enum(type))
8890 const enum_type_t *enumt = &type->enumt;
8892 /* if we have a default, no warnings */
8893 if (statement->default_label != NULL)
8896 /* FIXME: calculation of value should be done while parsing */
8897 const declaration_t *declaration;
8898 long last_value = -1;
8899 for (declaration = enumt->declaration->next;
8900 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8901 declaration = declaration->next) {
8902 const expression_t *expression = declaration->init.enum_value;
8903 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8905 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8906 if (l->expression == NULL)
8908 if (l->first_case <= value && value <= l->last_case) {
8914 warningf(&statement->base.source_position,
8915 "enumeration value '%Y' not handled in switch", declaration->symbol);
8922 * Parse a switch statement.
8924 static statement_t *parse_switch(void)
8928 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8929 statement->base.source_position = token.source_position;
8931 PUSH_PARENT(statement);
8934 add_anchor_token(')');
8935 expression_t *const expr = parse_expression();
8936 type_t * type = skip_typeref(expr->base.type);
8937 if (is_type_integer(type)) {
8938 type = promote_integer(type);
8939 if (warning.traditional) {
8940 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8941 warningf(&expr->base.source_position,
8942 "'%T' switch expression not converted to '%T' in ISO C",
8946 } else if (is_type_valid(type)) {
8947 errorf(&expr->base.source_position,
8948 "switch quantity is not an integer, but '%T'", type);
8949 type = type_error_type;
8951 statement->switchs.expression = create_implicit_cast(expr, type);
8953 rem_anchor_token(')');
8955 switch_statement_t *rem = current_switch;
8956 current_switch = &statement->switchs;
8957 statement->switchs.body = parse_statement();
8958 current_switch = rem;
8960 if (warning.switch_default &&
8961 statement->switchs.default_label == NULL) {
8962 warningf(&statement->base.source_position, "switch has no default case");
8964 if (warning.switch_enum)
8965 check_enum_cases(&statement->switchs);
8971 return create_invalid_statement();
8974 static statement_t *parse_loop_body(statement_t *const loop)
8976 statement_t *const rem = current_loop;
8977 current_loop = loop;
8979 statement_t *const body = parse_statement();
8986 * Parse a while statement.
8988 static statement_t *parse_while(void)
8992 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8993 statement->base.source_position = token.source_position;
8995 PUSH_PARENT(statement);
8998 add_anchor_token(')');
8999 statement->whiles.condition = parse_expression();
9000 rem_anchor_token(')');
9003 statement->whiles.body = parse_loop_body(statement);
9009 return create_invalid_statement();
9013 * Parse a do statement.
9015 static statement_t *parse_do(void)
9019 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9020 statement->base.source_position = token.source_position;
9022 PUSH_PARENT(statement)
9024 add_anchor_token(T_while);
9025 statement->do_while.body = parse_loop_body(statement);
9026 rem_anchor_token(T_while);
9030 add_anchor_token(')');
9031 statement->do_while.condition = parse_expression();
9032 rem_anchor_token(')');
9040 return create_invalid_statement();
9044 * Parse a for statement.
9046 static statement_t *parse_for(void)
9050 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9051 statement->base.source_position = token.source_position;
9053 PUSH_PARENT(statement);
9055 int top = environment_top();
9056 scope_t *last_scope = scope;
9057 set_scope(&statement->fors.scope);
9060 add_anchor_token(')');
9062 if (token.type != ';') {
9063 if (is_declaration_specifier(&token, false)) {
9064 parse_declaration(record_declaration);
9066 add_anchor_token(';');
9067 expression_t *const init = parse_expression();
9068 statement->fors.initialisation = init;
9069 if (warning.unused_value && !expression_has_effect(init)) {
9070 warningf(&init->base.source_position,
9071 "initialisation of 'for'-statement has no effect");
9073 rem_anchor_token(';');
9080 if (token.type != ';') {
9081 add_anchor_token(';');
9082 statement->fors.condition = parse_expression();
9083 rem_anchor_token(';');
9086 if (token.type != ')') {
9087 expression_t *const step = parse_expression();
9088 statement->fors.step = step;
9089 if (warning.unused_value && !expression_has_effect(step)) {
9090 warningf(&step->base.source_position,
9091 "step of 'for'-statement has no effect");
9094 rem_anchor_token(')');
9096 statement->fors.body = parse_loop_body(statement);
9098 assert(scope == &statement->fors.scope);
9099 set_scope(last_scope);
9100 environment_pop_to(top);
9107 rem_anchor_token(')');
9108 assert(scope == &statement->fors.scope);
9109 set_scope(last_scope);
9110 environment_pop_to(top);
9112 return create_invalid_statement();
9116 * Parse a goto statement.
9118 static statement_t *parse_goto(void)
9120 source_position_t source_position = token.source_position;
9123 statement_t *statement;
9124 if (c_mode & _GNUC && token.type == '*') {
9126 expression_t *expression = parse_expression();
9128 /* Argh: although documentation say the expression must be of type void *,
9129 * gcc excepts anything that can be casted into void * without error */
9130 type_t *type = expression->base.type;
9132 if (type != type_error_type) {
9133 if (!is_type_pointer(type) && !is_type_integer(type)) {
9134 errorf(&source_position, "cannot convert to a pointer type");
9135 } else if (type != type_void_ptr) {
9136 warningf(&source_position,
9137 "type of computed goto expression should be 'void*' not '%T'", type);
9139 expression = create_implicit_cast(expression, type_void_ptr);
9142 statement = allocate_statement_zero(STATEMENT_GOTO);
9143 statement->base.source_position = source_position;
9144 statement->gotos.expression = expression;
9146 if (token.type != T_IDENTIFIER) {
9148 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9150 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9154 symbol_t *symbol = token.v.symbol;
9157 statement = allocate_statement_zero(STATEMENT_GOTO);
9158 statement->base.source_position = source_position;
9159 statement->gotos.label = get_label(symbol);
9162 /* remember the goto's in a list for later checking */
9163 if (goto_last == NULL) {
9164 goto_first = &statement->gotos;
9166 goto_last->next = &statement->gotos;
9168 goto_last = &statement->gotos;
9174 return create_invalid_statement();
9178 * Parse a continue statement.
9180 static statement_t *parse_continue(void)
9182 if (current_loop == NULL) {
9183 errorf(HERE, "continue statement not within loop");
9186 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9187 statement->base.source_position = token.source_position;
9197 * Parse a break statement.
9199 static statement_t *parse_break(void)
9201 if (current_switch == NULL && current_loop == NULL) {
9202 errorf(HERE, "break statement not within loop or switch");
9205 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9206 statement->base.source_position = token.source_position;
9216 * Parse a __leave statement.
9218 static statement_t *parse_leave_statement(void)
9220 if (current_try == NULL) {
9221 errorf(HERE, "__leave statement not within __try");
9224 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9225 statement->base.source_position = token.source_position;
9235 * Check if a given declaration represents a local variable.
9237 static bool is_local_var_declaration(const declaration_t *declaration)
9239 switch ((storage_class_tag_t) declaration->storage_class) {
9240 case STORAGE_CLASS_AUTO:
9241 case STORAGE_CLASS_REGISTER: {
9242 const type_t *type = skip_typeref(declaration->type);
9243 if (is_type_function(type)) {
9255 * Check if a given declaration represents a variable.
9257 static bool is_var_declaration(const declaration_t *declaration)
9259 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9262 const type_t *type = skip_typeref(declaration->type);
9263 return !is_type_function(type);
9267 * Check if a given expression represents a local variable.
9269 static bool is_local_variable(const expression_t *expression)
9271 if (expression->base.kind != EXPR_REFERENCE) {
9274 const declaration_t *declaration = expression->reference.declaration;
9275 return is_local_var_declaration(declaration);
9279 * Check if a given expression represents a local variable and
9280 * return its declaration then, else return NULL.
9282 declaration_t *expr_is_variable(const expression_t *expression)
9284 if (expression->base.kind != EXPR_REFERENCE) {
9287 declaration_t *declaration = expression->reference.declaration;
9288 if (is_var_declaration(declaration))
9294 * Parse a return statement.
9296 static statement_t *parse_return(void)
9298 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9299 statement->base.source_position = token.source_position;
9303 expression_t *return_value = NULL;
9304 if (token.type != ';') {
9305 return_value = parse_expression();
9308 const type_t *const func_type = current_function->type;
9309 assert(is_type_function(func_type));
9310 type_t *const return_type = skip_typeref(func_type->function.return_type);
9312 if (return_value != NULL) {
9313 type_t *return_value_type = skip_typeref(return_value->base.type);
9315 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9316 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9317 warningf(&statement->base.source_position,
9318 "'return' with a value, in function returning void");
9319 return_value = NULL;
9321 assign_error_t error = semantic_assign(return_type, return_value);
9322 report_assign_error(error, return_type, return_value, "'return'",
9323 &statement->base.source_position);
9324 return_value = create_implicit_cast(return_value, return_type);
9326 /* check for returning address of a local var */
9327 if (return_value != NULL &&
9328 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9329 const expression_t *expression = return_value->unary.value;
9330 if (is_local_variable(expression)) {
9331 warningf(&statement->base.source_position,
9332 "function returns address of local variable");
9336 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9337 warningf(&statement->base.source_position,
9338 "'return' without value, in function returning non-void");
9341 statement->returns.value = return_value;
9350 * Parse a declaration statement.
9352 static statement_t *parse_declaration_statement(void)
9354 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9356 statement->base.source_position = token.source_position;
9358 declaration_t *before = last_declaration;
9360 parse_external_declaration();
9362 parse_declaration(record_declaration);
9364 if (before == NULL) {
9365 statement->declaration.declarations_begin = scope->declarations;
9367 statement->declaration.declarations_begin = before->next;
9369 statement->declaration.declarations_end = last_declaration;
9375 * Parse an expression statement, ie. expr ';'.
9377 static statement_t *parse_expression_statement(void)
9379 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9381 statement->base.source_position = token.source_position;
9382 expression_t *const expr = parse_expression();
9383 statement->expression.expression = expr;
9392 * Parse a microsoft __try { } __finally { } or
9393 * __try{ } __except() { }
9395 static statement_t *parse_ms_try_statment(void)
9397 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9398 statement->base.source_position = token.source_position;
9401 PUSH_PARENT(statement);
9403 ms_try_statement_t *rem = current_try;
9404 current_try = &statement->ms_try;
9405 statement->ms_try.try_statement = parse_compound_statement(false);
9410 if (token.type == T___except) {
9413 add_anchor_token(')');
9414 expression_t *const expr = parse_expression();
9415 type_t * type = skip_typeref(expr->base.type);
9416 if (is_type_integer(type)) {
9417 type = promote_integer(type);
9418 } else if (is_type_valid(type)) {
9419 errorf(&expr->base.source_position,
9420 "__expect expression is not an integer, but '%T'", type);
9421 type = type_error_type;
9423 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9424 rem_anchor_token(')');
9426 statement->ms_try.final_statement = parse_compound_statement(false);
9427 } else if (token.type == T__finally) {
9429 statement->ms_try.final_statement = parse_compound_statement(false);
9431 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9432 return create_invalid_statement();
9436 return create_invalid_statement();
9439 static statement_t *parse_empty_statement(void)
9441 if (warning.empty_statement) {
9442 warningf(HERE, "statement is empty");
9444 statement_t *const statement = create_empty_statement();
9449 static statement_t *parse_local_label_declaration(void) {
9450 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9451 statement->base.source_position = token.source_position;
9455 declaration_t *begin = NULL, *end = NULL;
9458 if (token.type != T_IDENTIFIER) {
9459 parse_error_expected("while parsing local label declaration",
9460 T_IDENTIFIER, NULL);
9463 symbol_t *symbol = token.v.symbol;
9464 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9465 if (declaration != NULL) {
9466 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9467 symbol, &declaration->source_position);
9469 declaration = allocate_declaration_zero();
9470 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9471 declaration->source_position = token.source_position;
9472 declaration->symbol = symbol;
9473 declaration->parent_scope = scope;
9474 declaration->init.statement = NULL;
9477 end->next = declaration;
9480 begin = declaration;
9482 local_label_push(declaration);
9486 if (token.type != ',')
9492 statement->declaration.declarations_begin = begin;
9493 statement->declaration.declarations_end = end;
9498 * Parse a statement.
9499 * There's also parse_statement() which additionally checks for
9500 * "statement has no effect" warnings
9502 static statement_t *intern_parse_statement(void)
9504 statement_t *statement = NULL;
9506 /* declaration or statement */
9507 add_anchor_token(';');
9508 switch (token.type) {
9509 case T_IDENTIFIER: {
9510 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9511 if (la1_type == ':') {
9512 statement = parse_label_statement();
9513 } else if (is_typedef_symbol(token.v.symbol)) {
9514 statement = parse_declaration_statement();
9515 } else switch (la1_type) {
9517 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9518 goto expression_statment;
9523 statement = parse_declaration_statement();
9527 expression_statment:
9528 statement = parse_expression_statement();
9534 case T___extension__:
9535 /* This can be a prefix to a declaration or an expression statement.
9536 * We simply eat it now and parse the rest with tail recursion. */
9539 } while (token.type == T___extension__);
9540 statement = parse_statement();
9544 statement = parse_declaration_statement();
9548 statement = parse_local_label_declaration();
9551 case ';': statement = parse_empty_statement(); break;
9552 case '{': statement = parse_compound_statement(false); break;
9553 case T___leave: statement = parse_leave_statement(); break;
9554 case T___try: statement = parse_ms_try_statment(); break;
9555 case T_asm: statement = parse_asm_statement(); break;
9556 case T_break: statement = parse_break(); break;
9557 case T_case: statement = parse_case_statement(); break;
9558 case T_continue: statement = parse_continue(); break;
9559 case T_default: statement = parse_default_statement(); break;
9560 case T_do: statement = parse_do(); break;
9561 case T_for: statement = parse_for(); break;
9562 case T_goto: statement = parse_goto(); break;
9563 case T_if: statement = parse_if (); break;
9564 case T_return: statement = parse_return(); break;
9565 case T_switch: statement = parse_switch(); break;
9566 case T_while: statement = parse_while(); break;
9576 case T_CHARACTER_CONSTANT:
9577 case T_FLOATINGPOINT:
9581 case T_STRING_LITERAL:
9582 case T_WIDE_CHARACTER_CONSTANT:
9583 case T_WIDE_STRING_LITERAL:
9584 case T___FUNCDNAME__:
9586 case T___FUNCTION__:
9587 case T___PRETTY_FUNCTION__:
9588 case T___builtin_alloca:
9589 case T___builtin_classify_type:
9590 case T___builtin_constant_p:
9591 case T___builtin_expect:
9592 case T___builtin_huge_val:
9593 case T___builtin_isgreater:
9594 case T___builtin_isgreaterequal:
9595 case T___builtin_isless:
9596 case T___builtin_islessequal:
9597 case T___builtin_islessgreater:
9598 case T___builtin_isunordered:
9599 case T___builtin_nan:
9600 case T___builtin_nand:
9601 case T___builtin_nanf:
9602 case T___builtin_offsetof:
9603 case T___builtin_prefetch:
9604 case T___builtin_va_arg:
9605 case T___builtin_va_end:
9606 case T___builtin_va_start:
9610 statement = parse_expression_statement();
9614 errorf(HERE, "unexpected token %K while parsing statement", &token);
9615 statement = create_invalid_statement();
9620 rem_anchor_token(';');
9622 assert(statement != NULL
9623 && statement->base.source_position.input_name != NULL);
9629 * parse a statement and emits "statement has no effect" warning if needed
9630 * (This is really a wrapper around intern_parse_statement with check for 1
9631 * single warning. It is needed, because for statement expressions we have
9632 * to avoid the warning on the last statement)
9634 static statement_t *parse_statement(void)
9636 statement_t *statement = intern_parse_statement();
9638 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9639 expression_t *expression = statement->expression.expression;
9640 if (!expression_has_effect(expression)) {
9641 warningf(&expression->base.source_position,
9642 "statement has no effect");
9650 * Parse a compound statement.
9652 static statement_t *parse_compound_statement(bool inside_expression_statement)
9654 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9655 statement->base.source_position = token.source_position;
9657 PUSH_PARENT(statement);
9660 add_anchor_token('}');
9662 int top = environment_top();
9663 int top_local = local_label_top();
9664 scope_t *last_scope = scope;
9665 set_scope(&statement->compound.scope);
9667 statement_t **anchor = &statement->compound.statements;
9668 bool only_decls_so_far = true;
9669 while (token.type != '}' && token.type != T_EOF) {
9670 statement_t *sub_statement = intern_parse_statement();
9671 if (is_invalid_statement(sub_statement)) {
9672 /* an error occurred. if we are at an anchor, return */
9678 if (warning.declaration_after_statement) {
9679 if (sub_statement->kind != STATEMENT_DECLARATION) {
9680 only_decls_so_far = false;
9681 } else if (!only_decls_so_far) {
9682 warningf(&sub_statement->base.source_position,
9683 "ISO C90 forbids mixed declarations and code");
9687 *anchor = sub_statement;
9689 while (sub_statement->base.next != NULL)
9690 sub_statement = sub_statement->base.next;
9692 anchor = &sub_statement->base.next;
9695 if (token.type == '}') {
9698 errorf(&statement->base.source_position,
9699 "end of file while looking for closing '}'");
9702 /* look over all statements again to produce no effect warnings */
9703 if (warning.unused_value) {
9704 statement_t *sub_statement = statement->compound.statements;
9705 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9706 if (sub_statement->kind != STATEMENT_EXPRESSION)
9708 /* don't emit a warning for the last expression in an expression
9709 * statement as it has always an effect */
9710 if (inside_expression_statement && sub_statement->base.next == NULL)
9713 expression_t *expression = sub_statement->expression.expression;
9714 if (!expression_has_effect(expression)) {
9715 warningf(&expression->base.source_position,
9716 "statement has no effect");
9722 rem_anchor_token('}');
9723 assert(scope == &statement->compound.scope);
9724 set_scope(last_scope);
9725 environment_pop_to(top);
9726 local_label_pop_to(top_local);
9733 * Initialize builtin types.
9735 static void initialize_builtin_types(void)
9737 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9738 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9739 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9740 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9741 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9742 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9743 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9744 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9746 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9747 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9748 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9749 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9751 /* const version of wchar_t */
9752 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9753 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9754 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9756 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9760 * Check for unused global static functions and variables
9762 static void check_unused_globals(void)
9764 if (!warning.unused_function && !warning.unused_variable)
9767 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9769 decl->modifiers & DM_UNUSED ||
9770 decl->modifiers & DM_USED ||
9771 decl->storage_class != STORAGE_CLASS_STATIC)
9774 type_t *const type = decl->type;
9776 if (is_type_function(skip_typeref(type))) {
9777 if (!warning.unused_function || decl->is_inline)
9780 s = (decl->init.statement != NULL ? "defined" : "declared");
9782 if (!warning.unused_variable)
9788 warningf(&decl->source_position, "'%#T' %s but not used",
9789 type, decl->symbol, s);
9793 static void parse_global_asm(void)
9798 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9799 statement->base.source_position = token.source_position;
9800 statement->asms.asm_text = parse_string_literals();
9801 statement->base.next = unit->global_asm;
9802 unit->global_asm = statement;
9811 * Parse a translation unit.
9813 static void parse_translation_unit(void)
9817 bool anchor_leak = false;
9818 for (token_type_t i = 0; i != T_LAST_TOKEN; ++i) {
9819 unsigned char count = token_anchor_set[i];
9821 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9829 switch (token.type) {
9832 case T___extension__:
9833 parse_external_declaration();
9844 /* TODO error in strict mode */
9845 warningf(HERE, "stray ';' outside of function");
9850 errorf(HERE, "stray %K outside of function", &token);
9851 if (token.type == '(' || token.type == '{' || token.type == '[')
9852 eat_until_matching_token(token.type);
9862 * @return the translation unit or NULL if errors occurred.
9864 void start_parsing(void)
9866 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9867 label_stack = NEW_ARR_F(stack_entry_t, 0);
9868 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
9869 diagnostic_count = 0;
9873 type_set_output(stderr);
9874 ast_set_output(stderr);
9876 assert(unit == NULL);
9877 unit = allocate_ast_zero(sizeof(unit[0]));
9879 assert(global_scope == NULL);
9880 global_scope = &unit->scope;
9882 assert(scope == NULL);
9883 set_scope(&unit->scope);
9885 initialize_builtin_types();
9888 translation_unit_t *finish_parsing(void)
9890 assert(scope == &unit->scope);
9892 last_declaration = NULL;
9894 assert(global_scope == &unit->scope);
9895 check_unused_globals();
9896 global_scope = NULL;
9898 DEL_ARR_F(environment_stack);
9899 DEL_ARR_F(label_stack);
9900 DEL_ARR_F(local_label_stack);
9902 translation_unit_t *result = unit;
9909 lookahead_bufpos = 0;
9910 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9913 parse_translation_unit();
9917 * Initialize the parser.
9919 void init_parser(void)
9921 sym_anonymous = symbol_table_insert("<anonymous>");
9924 /* add predefined symbols for extended-decl-modifier */
9925 sym_align = symbol_table_insert("align");
9926 sym_allocate = symbol_table_insert("allocate");
9927 sym_dllimport = symbol_table_insert("dllimport");
9928 sym_dllexport = symbol_table_insert("dllexport");
9929 sym_naked = symbol_table_insert("naked");
9930 sym_noinline = symbol_table_insert("noinline");
9931 sym_noreturn = symbol_table_insert("noreturn");
9932 sym_nothrow = symbol_table_insert("nothrow");
9933 sym_novtable = symbol_table_insert("novtable");
9934 sym_property = symbol_table_insert("property");
9935 sym_get = symbol_table_insert("get");
9936 sym_put = symbol_table_insert("put");
9937 sym_selectany = symbol_table_insert("selectany");
9938 sym_thread = symbol_table_insert("thread");
9939 sym_uuid = symbol_table_insert("uuid");
9940 sym_deprecated = symbol_table_insert("deprecated");
9941 sym_restrict = symbol_table_insert("restrict");
9942 sym_noalias = symbol_table_insert("noalias");
9944 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9946 init_expression_parsers();
9947 obstack_init(&temp_obst);
9949 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9950 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9954 * Terminate the parser.
9956 void exit_parser(void)
9958 obstack_free(&temp_obst, NULL);