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 /* symbols for Microsoft extended-decl-modifier */
138 static const symbol_t *sym_align = NULL;
139 static const symbol_t *sym_allocate = NULL;
140 static const symbol_t *sym_dllimport = NULL;
141 static const symbol_t *sym_dllexport = NULL;
142 static const symbol_t *sym_naked = NULL;
143 static const symbol_t *sym_noinline = NULL;
144 static const symbol_t *sym_noreturn = NULL;
145 static const symbol_t *sym_nothrow = NULL;
146 static const symbol_t *sym_novtable = NULL;
147 static const symbol_t *sym_property = NULL;
148 static const symbol_t *sym_get = NULL;
149 static const symbol_t *sym_put = NULL;
150 static const symbol_t *sym_selectany = NULL;
151 static const symbol_t *sym_thread = NULL;
152 static const symbol_t *sym_uuid = NULL;
153 static const symbol_t *sym_deprecated = NULL;
154 static const symbol_t *sym_restrict = NULL;
155 static const symbol_t *sym_noalias = NULL;
157 /** The token anchor set */
158 static unsigned char token_anchor_set[T_LAST_TOKEN];
160 /** The current source position. */
161 #define HERE (&token.source_position)
163 static type_t *type_valist;
165 static statement_t *parse_compound_statement(bool inside_expression_statement);
166 static statement_t *parse_statement(void);
168 static expression_t *parse_sub_expression(unsigned precedence);
169 static expression_t *parse_expression(void);
170 static type_t *parse_typename(void);
172 static void parse_compound_type_entries(declaration_t *compound_declaration);
173 static declaration_t *parse_declarator(
174 const declaration_specifiers_t *specifiers, bool may_be_abstract);
175 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
187 #define TYPE_QUALIFIERS \
192 case T__forceinline: \
193 case T___attribute__:
195 #ifdef PROVIDE_COMPLEX
196 #define COMPLEX_SPECIFIERS \
198 #define IMAGINARY_SPECIFIERS \
201 #define COMPLEX_SPECIFIERS
202 #define IMAGINARY_SPECIFIERS
205 #define TYPE_SPECIFIERS \
220 case T___builtin_va_list: \
225 #define DECLARATION_START \
230 #define TYPENAME_START \
235 * Allocate an AST node with given size and
236 * initialize all fields with zero.
238 static void *allocate_ast_zero(size_t size)
240 void *res = allocate_ast(size);
241 memset(res, 0, size);
245 static declaration_t *allocate_declaration_zero(void)
247 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
248 declaration->type = type_error_type;
249 declaration->alignment = 0;
254 * Returns the size of a statement node.
256 * @param kind the statement kind
258 static size_t get_statement_struct_size(statement_kind_t kind)
260 static const size_t sizes[] = {
261 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
262 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
263 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
264 [STATEMENT_RETURN] = sizeof(return_statement_t),
265 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
266 [STATEMENT_IF] = sizeof(if_statement_t),
267 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
268 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
269 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
270 [STATEMENT_BREAK] = sizeof(statement_base_t),
271 [STATEMENT_GOTO] = sizeof(goto_statement_t),
272 [STATEMENT_LABEL] = sizeof(label_statement_t),
273 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
274 [STATEMENT_WHILE] = sizeof(while_statement_t),
275 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
276 [STATEMENT_FOR] = sizeof(for_statement_t),
277 [STATEMENT_ASM] = sizeof(asm_statement_t),
278 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
279 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
281 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
282 assert(sizes[kind] != 0);
287 * Returns the size of an expression node.
289 * @param kind the expression kind
291 static size_t get_expression_struct_size(expression_kind_t kind)
293 static const size_t sizes[] = {
294 [EXPR_INVALID] = sizeof(expression_base_t),
295 [EXPR_REFERENCE] = sizeof(reference_expression_t),
296 [EXPR_CONST] = sizeof(const_expression_t),
297 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
298 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
299 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
300 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
301 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
302 [EXPR_CALL] = sizeof(call_expression_t),
303 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
304 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
305 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
306 [EXPR_SELECT] = sizeof(select_expression_t),
307 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
308 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
309 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
310 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
311 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
312 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
313 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
314 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
315 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
316 [EXPR_VA_START] = sizeof(va_start_expression_t),
317 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
318 [EXPR_STATEMENT] = sizeof(statement_expression_t),
319 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
321 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
322 return sizes[EXPR_UNARY_FIRST];
324 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
325 return sizes[EXPR_BINARY_FIRST];
327 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
328 assert(sizes[kind] != 0);
333 * Allocate a statement node of given kind and initialize all
336 static statement_t *allocate_statement_zero(statement_kind_t kind)
338 size_t size = get_statement_struct_size(kind);
339 statement_t *res = allocate_ast_zero(size);
341 res->base.kind = kind;
342 res->base.parent = current_parent;
347 * Allocate an expression node of given kind and initialize all
350 static expression_t *allocate_expression_zero(expression_kind_t kind)
352 size_t size = get_expression_struct_size(kind);
353 expression_t *res = allocate_ast_zero(size);
355 res->base.kind = kind;
356 res->base.type = type_error_type;
361 * Creates a new invalid expression.
363 static expression_t *create_invalid_expression(void)
365 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
366 expression->base.source_position = token.source_position;
371 * Creates a new invalid statement.
373 static statement_t *create_invalid_statement(void)
375 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
376 statement->base.source_position = token.source_position;
381 * Allocate a new empty statement.
383 static statement_t *create_empty_statement(void)
385 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
386 statement->base.source_position = token.source_position;
391 * Returns the size of a type node.
393 * @param kind the type kind
395 static size_t get_type_struct_size(type_kind_t kind)
397 static const size_t sizes[] = {
398 [TYPE_ATOMIC] = sizeof(atomic_type_t),
399 [TYPE_COMPLEX] = sizeof(complex_type_t),
400 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
401 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
402 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
403 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
404 [TYPE_ENUM] = sizeof(enum_type_t),
405 [TYPE_FUNCTION] = sizeof(function_type_t),
406 [TYPE_POINTER] = sizeof(pointer_type_t),
407 [TYPE_ARRAY] = sizeof(array_type_t),
408 [TYPE_BUILTIN] = sizeof(builtin_type_t),
409 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
410 [TYPE_TYPEOF] = sizeof(typeof_type_t),
412 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
413 assert(kind <= TYPE_TYPEOF);
414 assert(sizes[kind] != 0);
419 * Allocate a type node of given kind and initialize all
422 * @param kind type kind to allocate
423 * @param source_position the source position of the type definition
425 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
427 size_t size = get_type_struct_size(kind);
428 type_t *res = obstack_alloc(type_obst, size);
429 memset(res, 0, size);
431 res->base.kind = kind;
432 res->base.source_position = *source_position;
437 * Returns the size of an initializer node.
439 * @param kind the initializer kind
441 static size_t get_initializer_size(initializer_kind_t kind)
443 static const size_t sizes[] = {
444 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
445 [INITIALIZER_STRING] = sizeof(initializer_string_t),
446 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
447 [INITIALIZER_LIST] = sizeof(initializer_list_t),
448 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
450 assert(kind < sizeof(sizes) / sizeof(*sizes));
451 assert(sizes[kind] != 0);
456 * Allocate an initializer node of given kind and initialize all
459 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
461 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
468 * Free a type from the type obstack.
470 static void free_type(void *type)
472 obstack_free(type_obst, type);
476 * Returns the index of the top element of the environment stack.
478 static size_t environment_top(void)
480 return ARR_LEN(environment_stack);
484 * Returns the index of the top element of the global label stack.
486 static size_t label_top(void)
488 return ARR_LEN(label_stack);
492 * Returns the index of the top element of the local label stack.
494 static size_t local_label_top(void)
496 return ARR_LEN(local_label_stack);
500 * Return the next token.
502 static inline void next_token(void)
504 token = lookahead_buffer[lookahead_bufpos];
505 lookahead_buffer[lookahead_bufpos] = lexer_token;
508 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
511 print_token(stderr, &token);
512 fprintf(stderr, "\n");
517 * Return the next token with a given lookahead.
519 static inline const token_t *look_ahead(int num)
521 assert(num > 0 && num <= MAX_LOOKAHEAD);
522 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
523 return &lookahead_buffer[pos];
527 * Adds a token to the token anchor set (a multi-set).
529 static void add_anchor_token(int token_type)
531 assert(0 <= token_type && token_type < T_LAST_TOKEN);
532 ++token_anchor_set[token_type];
535 static int save_and_reset_anchor_state(int token_type)
537 assert(0 <= token_type && token_type < T_LAST_TOKEN);
538 int count = token_anchor_set[token_type];
539 token_anchor_set[token_type] = 0;
543 static void restore_anchor_state(int token_type, int count)
545 assert(0 <= token_type && token_type < T_LAST_TOKEN);
546 token_anchor_set[token_type] = count;
550 * Remove a token from the token anchor set (a multi-set).
552 static void rem_anchor_token(int token_type)
554 assert(0 <= token_type && token_type < T_LAST_TOKEN);
555 --token_anchor_set[token_type];
558 static bool at_anchor(void)
562 return token_anchor_set[token.type];
566 * Eat tokens until a matching token is found.
568 static void eat_until_matching_token(int type)
572 case '(': end_token = ')'; break;
573 case '{': end_token = '}'; break;
574 case '[': end_token = ']'; break;
575 default: end_token = type; break;
578 unsigned parenthesis_count = 0;
579 unsigned brace_count = 0;
580 unsigned bracket_count = 0;
581 while (token.type != end_token ||
582 parenthesis_count != 0 ||
584 bracket_count != 0) {
585 switch (token.type) {
587 case '(': ++parenthesis_count; break;
588 case '{': ++brace_count; break;
589 case '[': ++bracket_count; break;
592 if (parenthesis_count > 0)
602 if (bracket_count > 0)
605 if (token.type == end_token &&
606 parenthesis_count == 0 &&
620 * Eat input tokens until an anchor is found.
622 static void eat_until_anchor(void)
624 if (token.type == T_EOF)
626 while (token_anchor_set[token.type] == 0) {
627 if (token.type == '(' || token.type == '{' || token.type == '[')
628 eat_until_matching_token(token.type);
629 if (token.type == T_EOF)
635 static void eat_block(void)
637 eat_until_matching_token('{');
638 if (token.type == '}')
643 * eat all token until a ';' is reached or a stop token is found.
645 static void eat_statement(void)
647 eat_until_matching_token(';');
648 if (token.type == ';')
652 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
655 * Report a parse error because an expected token was not found.
658 #if defined __GNUC__ && __GNUC__ >= 4
659 __attribute__((sentinel))
661 void parse_error_expected(const char *message, ...)
663 if (message != NULL) {
664 errorf(HERE, "%s", message);
667 va_start(ap, message);
668 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
673 * Report a type error.
675 static void type_error(const char *msg, const source_position_t *source_position,
678 errorf(source_position, "%s, but found type '%T'", msg, type);
682 * Report an incompatible type.
684 static void type_error_incompatible(const char *msg,
685 const source_position_t *source_position, type_t *type1, type_t *type2)
687 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
692 * Expect the the current token is the expected token.
693 * If not, generate an error, eat the current statement,
694 * and goto the end_error label.
696 #define expect(expected) \
698 if (UNLIKELY(token.type != (expected))) { \
699 parse_error_expected(NULL, (expected), NULL); \
700 add_anchor_token(expected); \
701 eat_until_anchor(); \
702 if (token.type == expected) \
704 rem_anchor_token(expected); \
710 static void set_scope(scope_t *new_scope)
713 scope->last_declaration = last_declaration;
717 last_declaration = new_scope->last_declaration;
721 * Search a symbol in a given namespace and returns its declaration or
722 * NULL if this symbol was not found.
724 static declaration_t *get_declaration(const symbol_t *const symbol,
725 const namespace_t namespc)
727 declaration_t *declaration = symbol->declaration;
728 for( ; declaration != NULL; declaration = declaration->symbol_next) {
729 if (declaration->namespc == namespc)
737 * pushs an environment_entry on the environment stack and links the
738 * corresponding symbol to the new entry
740 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
742 symbol_t *symbol = declaration->symbol;
743 namespace_t namespc = (namespace_t) declaration->namespc;
745 /* replace/add declaration into declaration list of the symbol */
746 declaration_t *iter = symbol->declaration;
748 symbol->declaration = declaration;
750 declaration_t *iter_last = NULL;
751 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
752 /* replace an entry? */
753 if (iter->namespc == namespc) {
754 if (iter_last == NULL) {
755 symbol->declaration = declaration;
757 iter_last->symbol_next = declaration;
759 declaration->symbol_next = iter->symbol_next;
764 assert(iter_last->symbol_next == NULL);
765 iter_last->symbol_next = declaration;
769 /* remember old declaration */
771 entry.symbol = symbol;
772 entry.old_declaration = iter;
773 entry.namespc = (unsigned short) namespc;
774 ARR_APP1(stack_entry_t, *stack_ptr, entry);
778 * Push a declaration on the environment stack.
780 * @param declaration the declaration
782 static void environment_push(declaration_t *declaration)
784 assert(declaration->source_position.input_name != NULL);
785 assert(declaration->parent_scope != NULL);
786 stack_push(&environment_stack, declaration);
790 * Push a declaration on the global label stack.
792 * @param declaration the declaration
794 static void label_push(declaration_t *declaration)
796 declaration->parent_scope = ¤t_function->scope;
797 stack_push(&label_stack, declaration);
801 * Push a declaration of the local label stack.
803 * @param declaration the declaration
805 static void local_label_push(declaration_t *declaration)
807 assert(declaration->parent_scope != NULL);
808 stack_push(&local_label_stack, declaration);
812 * pops symbols from the environment stack until @p new_top is the top element
814 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
816 stack_entry_t *stack = *stack_ptr;
817 size_t top = ARR_LEN(stack);
820 assert(new_top <= top);
824 for(i = top; i > new_top; --i) {
825 stack_entry_t *entry = &stack[i - 1];
827 declaration_t *old_declaration = entry->old_declaration;
828 symbol_t *symbol = entry->symbol;
829 namespace_t namespc = (namespace_t)entry->namespc;
831 /* replace/remove declaration */
832 declaration_t *declaration = symbol->declaration;
833 assert(declaration != NULL);
834 if (declaration->namespc == namespc) {
835 if (old_declaration == NULL) {
836 symbol->declaration = declaration->symbol_next;
838 symbol->declaration = old_declaration;
841 declaration_t *iter_last = declaration;
842 declaration_t *iter = declaration->symbol_next;
843 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
844 /* replace an entry? */
845 if (iter->namespc == namespc) {
846 assert(iter_last != NULL);
847 iter_last->symbol_next = old_declaration;
848 if (old_declaration != NULL) {
849 old_declaration->symbol_next = iter->symbol_next;
854 assert(iter != NULL);
858 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
862 * Pop all entries from the environment stack until the new_top
865 * @param new_top the new stack top
867 static void environment_pop_to(size_t new_top)
869 stack_pop_to(&environment_stack, new_top);
873 * Pop all entries from the global label stack until the new_top
876 * @param new_top the new stack top
878 static void label_pop_to(size_t new_top)
880 stack_pop_to(&label_stack, new_top);
884 * Pop all entries from the local label stack until the new_top
887 * @param new_top the new stack top
889 static void local_label_pop_to(size_t new_top)
891 stack_pop_to(&local_label_stack, new_top);
895 static int get_akind_rank(atomic_type_kind_t akind)
900 static int get_rank(const type_t *type)
902 assert(!is_typeref(type));
903 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
904 * and esp. footnote 108). However we can't fold constants (yet), so we
905 * can't decide whether unsigned int is possible, while int always works.
906 * (unsigned int would be preferable when possible... for stuff like
907 * struct { enum { ... } bla : 4; } ) */
908 if (type->kind == TYPE_ENUM)
909 return get_akind_rank(ATOMIC_TYPE_INT);
911 assert(type->kind == TYPE_ATOMIC);
912 return get_akind_rank(type->atomic.akind);
915 static type_t *promote_integer(type_t *type)
917 if (type->kind == TYPE_BITFIELD)
918 type = type->bitfield.base_type;
920 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
927 * Create a cast expression.
929 * @param expression the expression to cast
930 * @param dest_type the destination type
932 static expression_t *create_cast_expression(expression_t *expression,
935 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
937 cast->unary.value = expression;
938 cast->base.type = dest_type;
944 * Check if a given expression represents the 0 pointer constant.
946 static bool is_null_pointer_constant(const expression_t *expression)
948 /* skip void* cast */
949 if (expression->kind == EXPR_UNARY_CAST
950 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
951 expression = expression->unary.value;
954 /* TODO: not correct yet, should be any constant integer expression
955 * which evaluates to 0 */
956 if (expression->kind != EXPR_CONST)
959 type_t *const type = skip_typeref(expression->base.type);
960 if (!is_type_integer(type))
963 return expression->conste.v.int_value == 0;
967 * Create an implicit cast expression.
969 * @param expression the expression to cast
970 * @param dest_type the destination type
972 static expression_t *create_implicit_cast(expression_t *expression,
975 type_t *const source_type = expression->base.type;
977 if (source_type == dest_type)
980 return create_cast_expression(expression, dest_type);
983 typedef enum assign_error_t {
985 ASSIGN_ERROR_INCOMPATIBLE,
986 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
987 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
988 ASSIGN_WARNING_POINTER_FROM_INT,
989 ASSIGN_WARNING_INT_FROM_POINTER
992 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
993 const expression_t *const right,
995 const source_position_t *source_position)
997 type_t *const orig_type_right = right->base.type;
998 type_t *const type_left = skip_typeref(orig_type_left);
999 type_t *const type_right = skip_typeref(orig_type_right);
1002 case ASSIGN_SUCCESS:
1004 case ASSIGN_ERROR_INCOMPATIBLE:
1005 errorf(source_position,
1006 "destination type '%T' in %s is incompatible with type '%T'",
1007 orig_type_left, context, orig_type_right);
1010 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1011 type_t *points_to_left
1012 = skip_typeref(type_left->pointer.points_to);
1013 type_t *points_to_right
1014 = skip_typeref(type_right->pointer.points_to);
1016 /* the left type has all qualifiers from the right type */
1017 unsigned missing_qualifiers
1018 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1019 warningf(source_position,
1020 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1021 orig_type_left, context, orig_type_right, missing_qualifiers);
1025 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1026 warningf(source_position,
1027 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1028 orig_type_left, context, right, orig_type_right);
1031 case ASSIGN_WARNING_POINTER_FROM_INT:
1032 warningf(source_position,
1033 "%s makes integer '%T' from pointer '%T' without a cast",
1034 context, orig_type_left, orig_type_right);
1037 case ASSIGN_WARNING_INT_FROM_POINTER:
1038 warningf(source_position,
1039 "%s makes integer '%T' from pointer '%T' without a cast",
1040 context, orig_type_left, orig_type_right);
1044 panic("invalid error value");
1048 /** Implements the rules from § 6.5.16.1 */
1049 static assign_error_t semantic_assign(type_t *orig_type_left,
1050 const expression_t *const right)
1052 type_t *const orig_type_right = right->base.type;
1053 type_t *const type_left = skip_typeref(orig_type_left);
1054 type_t *const type_right = skip_typeref(orig_type_right);
1056 if (is_type_pointer(type_left)) {
1057 if (is_null_pointer_constant(right)) {
1058 return ASSIGN_SUCCESS;
1059 } else if (is_type_pointer(type_right)) {
1060 type_t *points_to_left
1061 = skip_typeref(type_left->pointer.points_to);
1062 type_t *points_to_right
1063 = skip_typeref(type_right->pointer.points_to);
1064 assign_error_t res = ASSIGN_SUCCESS;
1066 /* the left type has all qualifiers from the right type */
1067 unsigned missing_qualifiers
1068 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1069 if (missing_qualifiers != 0) {
1070 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1073 points_to_left = get_unqualified_type(points_to_left);
1074 points_to_right = get_unqualified_type(points_to_right);
1076 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1077 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1081 if (!types_compatible(points_to_left, points_to_right)) {
1082 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1086 } else if (is_type_integer(type_right)) {
1087 return ASSIGN_WARNING_POINTER_FROM_INT;
1089 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1090 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1091 && is_type_pointer(type_right))) {
1092 return ASSIGN_SUCCESS;
1093 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1094 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1095 type_t *const unqual_type_left = get_unqualified_type(type_left);
1096 type_t *const unqual_type_right = get_unqualified_type(type_right);
1097 if (types_compatible(unqual_type_left, unqual_type_right)) {
1098 return ASSIGN_SUCCESS;
1100 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1101 return ASSIGN_WARNING_INT_FROM_POINTER;
1104 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1105 return ASSIGN_SUCCESS;
1107 return ASSIGN_ERROR_INCOMPATIBLE;
1110 static expression_t *parse_constant_expression(void)
1112 /* start parsing at precedence 7 (conditional expression) */
1113 expression_t *result = parse_sub_expression(7);
1115 if (!is_constant_expression(result)) {
1116 errorf(&result->base.source_position,
1117 "expression '%E' is not constant\n", result);
1123 static expression_t *parse_assignment_expression(void)
1125 /* start parsing at precedence 2 (assignment expression) */
1126 return parse_sub_expression(2);
1129 static type_t *make_global_typedef(const char *name, type_t *type)
1131 symbol_t *const symbol = symbol_table_insert(name);
1133 declaration_t *const declaration = allocate_declaration_zero();
1134 declaration->namespc = NAMESPACE_NORMAL;
1135 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1136 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1137 declaration->type = type;
1138 declaration->symbol = symbol;
1139 declaration->source_position = builtin_source_position;
1140 declaration->implicit = true;
1142 record_declaration(declaration, false);
1144 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1145 typedef_type->typedeft.declaration = declaration;
1147 return typedef_type;
1150 static string_t parse_string_literals(void)
1152 assert(token.type == T_STRING_LITERAL);
1153 string_t result = token.v.string;
1157 while (token.type == T_STRING_LITERAL) {
1158 result = concat_strings(&result, &token.v.string);
1165 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1166 [GNU_AK_CONST] = "const",
1167 [GNU_AK_VOLATILE] = "volatile",
1168 [GNU_AK_CDECL] = "cdecl",
1169 [GNU_AK_STDCALL] = "stdcall",
1170 [GNU_AK_FASTCALL] = "fastcall",
1171 [GNU_AK_DEPRECATED] = "deprecated",
1172 [GNU_AK_NOINLINE] = "noinline",
1173 [GNU_AK_NORETURN] = "noreturn",
1174 [GNU_AK_NAKED] = "naked",
1175 [GNU_AK_PURE] = "pure",
1176 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1177 [GNU_AK_MALLOC] = "malloc",
1178 [GNU_AK_WEAK] = "weak",
1179 [GNU_AK_CONSTRUCTOR] = "constructor",
1180 [GNU_AK_DESTRUCTOR] = "destructor",
1181 [GNU_AK_NOTHROW] = "nothrow",
1182 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1183 [GNU_AK_COMMON] = "common",
1184 [GNU_AK_NOCOMMON] = "nocommon",
1185 [GNU_AK_PACKED] = "packed",
1186 [GNU_AK_SHARED] = "shared",
1187 [GNU_AK_NOTSHARED] = "notshared",
1188 [GNU_AK_USED] = "used",
1189 [GNU_AK_UNUSED] = "unused",
1190 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1191 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1192 [GNU_AK_LONGCALL] = "longcall",
1193 [GNU_AK_SHORTCALL] = "shortcall",
1194 [GNU_AK_LONG_CALL] = "long_call",
1195 [GNU_AK_SHORT_CALL] = "short_call",
1196 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1197 [GNU_AK_INTERRUPT] = "interrupt",
1198 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1199 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1200 [GNU_AK_NESTING] = "nesting",
1201 [GNU_AK_NEAR] = "near",
1202 [GNU_AK_FAR] = "far",
1203 [GNU_AK_SIGNAL] = "signal",
1204 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1205 [GNU_AK_TINY_DATA] = "tiny_data",
1206 [GNU_AK_SAVEALL] = "saveall",
1207 [GNU_AK_FLATTEN] = "flatten",
1208 [GNU_AK_SSEREGPARM] = "sseregparm",
1209 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1210 [GNU_AK_RETURN_TWICE] = "return_twice",
1211 [GNU_AK_MAY_ALIAS] = "may_alias",
1212 [GNU_AK_MS_STRUCT] = "ms_struct",
1213 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1214 [GNU_AK_DLLIMPORT] = "dllimport",
1215 [GNU_AK_DLLEXPORT] = "dllexport",
1216 [GNU_AK_ALIGNED] = "aligned",
1217 [GNU_AK_ALIAS] = "alias",
1218 [GNU_AK_SECTION] = "section",
1219 [GNU_AK_FORMAT] = "format",
1220 [GNU_AK_FORMAT_ARG] = "format_arg",
1221 [GNU_AK_WEAKREF] = "weakref",
1222 [GNU_AK_NONNULL] = "nonnull",
1223 [GNU_AK_TLS_MODEL] = "tls_model",
1224 [GNU_AK_VISIBILITY] = "visibility",
1225 [GNU_AK_REGPARM] = "regparm",
1226 [GNU_AK_MODE] = "mode",
1227 [GNU_AK_MODEL] = "model",
1228 [GNU_AK_TRAP_EXIT] = "trap_exit",
1229 [GNU_AK_SP_SWITCH] = "sp_switch",
1230 [GNU_AK_SENTINEL] = "sentinel"
1234 * compare two string, ignoring double underscores on the second.
1236 static int strcmp_underscore(const char *s1, const char *s2)
1238 if (s2[0] == '_' && s2[1] == '_') {
1239 size_t len2 = strlen(s2);
1240 size_t len1 = strlen(s1);
1241 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1242 return strncmp(s1, s2+2, len2-4);
1246 return strcmp(s1, s2);
1250 * Allocate a new gnu temporal attribute.
1252 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1254 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1255 attribute->kind = kind;
1256 attribute->next = NULL;
1257 attribute->invalid = false;
1258 attribute->have_arguments = false;
1264 * parse one constant expression argument.
1266 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1268 expression_t *expression;
1269 add_anchor_token(')');
1270 expression = parse_constant_expression();
1271 rem_anchor_token(')');
1273 attribute->u.argument = fold_constant(expression);
1276 attribute->invalid = true;
1280 * parse a list of constant expressions arguments.
1282 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1284 argument_list_t **list = &attribute->u.arguments;
1285 argument_list_t *entry;
1286 expression_t *expression;
1287 add_anchor_token(')');
1288 add_anchor_token(',');
1290 expression = parse_constant_expression();
1291 entry = obstack_alloc(&temp_obst, sizeof(entry));
1292 entry->argument = fold_constant(expression);
1295 list = &entry->next;
1296 if (token.type != ',')
1300 rem_anchor_token(',');
1301 rem_anchor_token(')');
1305 attribute->invalid = true;
1309 * parse one string literal argument.
1311 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1314 add_anchor_token('(');
1315 if (token.type != T_STRING_LITERAL) {
1316 parse_error_expected("while parsing attribute directive",
1317 T_STRING_LITERAL, NULL);
1320 *string = parse_string_literals();
1321 rem_anchor_token('(');
1325 attribute->invalid = true;
1329 * parse one tls model.
1331 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1333 static const char *const tls_models[] = {
1339 string_t string = { NULL, 0 };
1340 parse_gnu_attribute_string_arg(attribute, &string);
1341 if (string.begin != NULL) {
1342 for(size_t i = 0; i < 4; ++i) {
1343 if (strcmp(tls_models[i], string.begin) == 0) {
1344 attribute->u.value = i;
1348 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1350 attribute->invalid = true;
1354 * parse one tls model.
1356 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1358 static const char *const visibilities[] = {
1364 string_t string = { NULL, 0 };
1365 parse_gnu_attribute_string_arg(attribute, &string);
1366 if (string.begin != NULL) {
1367 for(size_t i = 0; i < 4; ++i) {
1368 if (strcmp(visibilities[i], string.begin) == 0) {
1369 attribute->u.value = i;
1373 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1375 attribute->invalid = true;
1379 * parse one (code) model.
1381 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1383 static const char *const visibilities[] = {
1388 string_t string = { NULL, 0 };
1389 parse_gnu_attribute_string_arg(attribute, &string);
1390 if (string.begin != NULL) {
1391 for(int i = 0; i < 3; ++i) {
1392 if (strcmp(visibilities[i], string.begin) == 0) {
1393 attribute->u.value = i;
1397 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1399 attribute->invalid = true;
1402 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1404 /* TODO: find out what is allowed here... */
1406 /* at least: byte, word, pointer, list of machine modes
1407 * __XXX___ is interpreted as XXX */
1408 add_anchor_token(')');
1410 if (token.type != T_IDENTIFIER) {
1411 expect(T_IDENTIFIER);
1414 /* This isn't really correct, the backend should provide a list of machine
1415 * specific modes (according to gcc philosophy that is...) */
1416 const char *symbol_str = token.v.symbol->string;
1417 if (strcmp_underscore("QI", symbol_str) == 0 ||
1418 strcmp_underscore("byte", symbol_str) == 0) {
1419 attribute->u.akind = ATOMIC_TYPE_CHAR;
1420 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1421 attribute->u.akind = ATOMIC_TYPE_SHORT;
1422 } else if (strcmp_underscore("SI", symbol_str) == 0
1423 || strcmp_underscore("word", symbol_str) == 0
1424 || strcmp_underscore("pointer", symbol_str) == 0) {
1425 attribute->u.akind = ATOMIC_TYPE_INT;
1426 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1427 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1429 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1430 attribute->invalid = true;
1434 rem_anchor_token(')');
1438 attribute->invalid = true;
1442 * parse one interrupt argument.
1444 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1446 static const char *const interrupts[] = {
1453 string_t string = { NULL, 0 };
1454 parse_gnu_attribute_string_arg(attribute, &string);
1455 if (string.begin != NULL) {
1456 for(size_t i = 0; i < 5; ++i) {
1457 if (strcmp(interrupts[i], string.begin) == 0) {
1458 attribute->u.value = i;
1462 errorf(HERE, "'%s' is not an interrupt", string.begin);
1464 attribute->invalid = true;
1468 * parse ( identifier, const expression, const expression )
1470 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1472 static const char *const format_names[] = {
1480 if (token.type != T_IDENTIFIER) {
1481 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1484 const char *name = token.v.symbol->string;
1485 for(i = 0; i < 4; ++i) {
1486 if (strcmp_underscore(format_names[i], name) == 0)
1490 if (warning.attribute)
1491 warningf(HERE, "'%s' is an unrecognized format function type", name);
1496 add_anchor_token(')');
1497 add_anchor_token(',');
1498 parse_constant_expression();
1499 rem_anchor_token(',');
1500 rem_anchor_token('(');
1503 add_anchor_token(')');
1504 parse_constant_expression();
1505 rem_anchor_token('(');
1509 attribute->u.value = true;
1512 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1514 if (!attribute->have_arguments)
1517 /* should have no arguments */
1518 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1519 eat_until_matching_token('(');
1520 /* we have already consumed '(', so we stop before ')', eat it */
1522 attribute->invalid = true;
1526 * Parse one GNU attribute.
1528 * Note that attribute names can be specified WITH or WITHOUT
1529 * double underscores, ie const or __const__.
1531 * The following attributes are parsed without arguments
1556 * no_instrument_function
1557 * warn_unused_result
1574 * externally_visible
1582 * The following attributes are parsed with arguments
1583 * aligned( const expression )
1584 * alias( string literal )
1585 * section( string literal )
1586 * format( identifier, const expression, const expression )
1587 * format_arg( const expression )
1588 * tls_model( string literal )
1589 * visibility( string literal )
1590 * regparm( const expression )
1591 * model( string leteral )
1592 * trap_exit( const expression )
1593 * sp_switch( string literal )
1595 * The following attributes might have arguments
1596 * weak_ref( string literal )
1597 * non_null( const expression // ',' )
1598 * interrupt( string literal )
1599 * sentinel( constant expression )
1601 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1603 gnu_attribute_t *head = *attributes;
1604 gnu_attribute_t *last = *attributes;
1605 decl_modifiers_t modifiers = 0;
1606 gnu_attribute_t *attribute;
1608 eat(T___attribute__);
1612 if (token.type != ')') {
1613 /* find the end of the list */
1615 while (last->next != NULL)
1619 /* non-empty attribute list */
1622 if (token.type == T_const) {
1624 } else if (token.type == T_volatile) {
1626 } else if (token.type == T_cdecl) {
1627 /* __attribute__((cdecl)), WITH ms mode */
1629 } else if (token.type == T_IDENTIFIER) {
1630 const symbol_t *sym = token.v.symbol;
1633 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1640 for(i = 0; i < GNU_AK_LAST; ++i) {
1641 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1644 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1647 if (kind == GNU_AK_LAST) {
1648 if (warning.attribute)
1649 warningf(HERE, "'%s' attribute directive ignored", name);
1651 /* skip possible arguments */
1652 if (token.type == '(') {
1653 eat_until_matching_token(')');
1656 /* check for arguments */
1657 attribute = allocate_gnu_attribute(kind);
1658 if (token.type == '(') {
1660 if (token.type == ')') {
1661 /* empty args are allowed */
1664 attribute->have_arguments = true;
1669 case GNU_AK_VOLATILE:
1674 case GNU_AK_NOCOMMON:
1676 case GNU_AK_NOTSHARED:
1677 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1678 case GNU_AK_WARN_UNUSED_RESULT:
1679 case GNU_AK_LONGCALL:
1680 case GNU_AK_SHORTCALL:
1681 case GNU_AK_LONG_CALL:
1682 case GNU_AK_SHORT_CALL:
1683 case GNU_AK_FUNCTION_VECTOR:
1684 case GNU_AK_INTERRUPT_HANDLER:
1685 case GNU_AK_NMI_HANDLER:
1686 case GNU_AK_NESTING:
1690 case GNU_AK_EIGTHBIT_DATA:
1691 case GNU_AK_TINY_DATA:
1692 case GNU_AK_SAVEALL:
1693 case GNU_AK_FLATTEN:
1694 case GNU_AK_SSEREGPARM:
1695 case GNU_AK_EXTERNALLY_VISIBLE:
1696 case GNU_AK_RETURN_TWICE:
1697 case GNU_AK_MAY_ALIAS:
1698 case GNU_AK_MS_STRUCT:
1699 case GNU_AK_GCC_STRUCT:
1702 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1703 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1704 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1705 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1706 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1707 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1708 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1709 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1710 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1711 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1712 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1713 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1714 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1715 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1716 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1717 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1718 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1720 case GNU_AK_ALIGNED:
1721 /* __align__ may be used without an argument */
1722 if (attribute->have_arguments) {
1723 parse_gnu_attribute_const_arg(attribute);
1727 case GNU_AK_FORMAT_ARG:
1728 case GNU_AK_REGPARM:
1729 case GNU_AK_TRAP_EXIT:
1730 if (!attribute->have_arguments) {
1731 /* should have arguments */
1732 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1733 attribute->invalid = true;
1735 parse_gnu_attribute_const_arg(attribute);
1738 case GNU_AK_SECTION:
1739 case GNU_AK_SP_SWITCH:
1740 if (!attribute->have_arguments) {
1741 /* should have arguments */
1742 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1743 attribute->invalid = true;
1745 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1748 if (!attribute->have_arguments) {
1749 /* should have arguments */
1750 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1751 attribute->invalid = true;
1753 parse_gnu_attribute_format_args(attribute);
1755 case GNU_AK_WEAKREF:
1756 /* may have one string argument */
1757 if (attribute->have_arguments)
1758 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1760 case GNU_AK_NONNULL:
1761 if (attribute->have_arguments)
1762 parse_gnu_attribute_const_arg_list(attribute);
1764 case GNU_AK_TLS_MODEL:
1765 if (!attribute->have_arguments) {
1766 /* should have arguments */
1767 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1769 parse_gnu_attribute_tls_model_arg(attribute);
1771 case GNU_AK_VISIBILITY:
1772 if (!attribute->have_arguments) {
1773 /* should have arguments */
1774 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1776 parse_gnu_attribute_visibility_arg(attribute);
1779 if (!attribute->have_arguments) {
1780 /* should have arguments */
1781 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1783 parse_gnu_attribute_model_arg(attribute);
1787 if (!attribute->have_arguments) {
1788 /* should have arguments */
1789 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1791 parse_gnu_attribute_mode_arg(attribute);
1794 case GNU_AK_INTERRUPT:
1795 /* may have one string argument */
1796 if (attribute->have_arguments)
1797 parse_gnu_attribute_interrupt_arg(attribute);
1799 case GNU_AK_SENTINEL:
1800 /* may have one string argument */
1801 if (attribute->have_arguments)
1802 parse_gnu_attribute_const_arg(attribute);
1805 /* already handled */
1809 check_no_argument(attribute, name);
1812 if (attribute != NULL) {
1814 last->next = attribute;
1817 head = last = attribute;
1821 if (token.type != ',')
1835 * Parse GNU attributes.
1837 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1839 decl_modifiers_t modifiers = 0;
1842 switch(token.type) {
1843 case T___attribute__:
1844 modifiers |= parse_gnu_attribute(attributes);
1850 if (token.type != T_STRING_LITERAL) {
1851 parse_error_expected("while parsing assembler attribute",
1852 T_STRING_LITERAL, NULL);
1853 eat_until_matching_token('(');
1856 parse_string_literals();
1861 case T_cdecl: modifiers |= DM_CDECL; break;
1862 case T__fastcall: modifiers |= DM_FASTCALL; break;
1863 case T__stdcall: modifiers |= DM_STDCALL; break;
1866 /* TODO record modifier */
1867 warningf(HERE, "Ignoring declaration modifier %K", &token);
1871 default: return modifiers;
1878 static designator_t *parse_designation(void)
1880 designator_t *result = NULL;
1881 designator_t *last = NULL;
1884 designator_t *designator;
1885 switch(token.type) {
1887 designator = allocate_ast_zero(sizeof(designator[0]));
1888 designator->source_position = token.source_position;
1890 add_anchor_token(']');
1891 designator->array_index = parse_constant_expression();
1892 rem_anchor_token(']');
1896 designator = allocate_ast_zero(sizeof(designator[0]));
1897 designator->source_position = token.source_position;
1899 if (token.type != T_IDENTIFIER) {
1900 parse_error_expected("while parsing designator",
1901 T_IDENTIFIER, NULL);
1904 designator->symbol = token.v.symbol;
1912 assert(designator != NULL);
1914 last->next = designator;
1916 result = designator;
1924 static initializer_t *initializer_from_string(array_type_t *type,
1925 const string_t *const string)
1927 /* TODO: check len vs. size of array type */
1930 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1931 initializer->string.string = *string;
1936 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1937 wide_string_t *const string)
1939 /* TODO: check len vs. size of array type */
1942 initializer_t *const initializer =
1943 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1944 initializer->wide_string.string = *string;
1950 * Build an initializer from a given expression.
1952 static initializer_t *initializer_from_expression(type_t *orig_type,
1953 expression_t *expression)
1955 /* TODO check that expression is a constant expression */
1957 /* § 6.7.8.14/15 char array may be initialized by string literals */
1958 type_t *type = skip_typeref(orig_type);
1959 type_t *expr_type_orig = expression->base.type;
1960 type_t *expr_type = skip_typeref(expr_type_orig);
1961 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1962 array_type_t *const array_type = &type->array;
1963 type_t *const element_type = skip_typeref(array_type->element_type);
1965 if (element_type->kind == TYPE_ATOMIC) {
1966 atomic_type_kind_t akind = element_type->atomic.akind;
1967 switch (expression->kind) {
1968 case EXPR_STRING_LITERAL:
1969 if (akind == ATOMIC_TYPE_CHAR
1970 || akind == ATOMIC_TYPE_SCHAR
1971 || akind == ATOMIC_TYPE_UCHAR) {
1972 return initializer_from_string(array_type,
1973 &expression->string.value);
1976 case EXPR_WIDE_STRING_LITERAL: {
1977 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1978 if (get_unqualified_type(element_type) == bare_wchar_type) {
1979 return initializer_from_wide_string(array_type,
1980 &expression->wide_string.value);
1990 assign_error_t error = semantic_assign(type, expression);
1991 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1993 report_assign_error(error, type, expression, "initializer",
1994 &expression->base.source_position);
1996 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1997 result->value.value = create_implicit_cast(expression, type);
2003 * Checks if a given expression can be used as an constant initializer.
2005 static bool is_initializer_constant(const expression_t *expression)
2007 return is_constant_expression(expression)
2008 || is_address_constant(expression);
2012 * Parses an scalar initializer.
2014 * § 6.7.8.11; eat {} without warning
2016 static initializer_t *parse_scalar_initializer(type_t *type,
2017 bool must_be_constant)
2019 /* there might be extra {} hierarchies */
2021 if (token.type == '{') {
2022 warningf(HERE, "extra curly braces around scalar initializer");
2026 } while (token.type == '{');
2029 expression_t *expression = parse_assignment_expression();
2030 if (must_be_constant && !is_initializer_constant(expression)) {
2031 errorf(&expression->base.source_position,
2032 "Initialisation expression '%E' is not constant\n",
2036 initializer_t *initializer = initializer_from_expression(type, expression);
2038 if (initializer == NULL) {
2039 errorf(&expression->base.source_position,
2040 "expression '%E' (type '%T') doesn't match expected type '%T'",
2041 expression, expression->base.type, type);
2046 bool additional_warning_displayed = false;
2047 while (braces > 0) {
2048 if (token.type == ',') {
2051 if (token.type != '}') {
2052 if (!additional_warning_displayed) {
2053 warningf(HERE, "additional elements in scalar initializer");
2054 additional_warning_displayed = true;
2065 * An entry in the type path.
2067 typedef struct type_path_entry_t type_path_entry_t;
2068 struct type_path_entry_t {
2069 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2071 size_t index; /**< For array types: the current index. */
2072 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2077 * A type path expression a position inside compound or array types.
2079 typedef struct type_path_t type_path_t;
2080 struct type_path_t {
2081 type_path_entry_t *path; /**< An flexible array containing the current path. */
2082 type_t *top_type; /**< type of the element the path points */
2083 size_t max_index; /**< largest index in outermost array */
2087 * Prints a type path for debugging.
2089 static __attribute__((unused)) void debug_print_type_path(
2090 const type_path_t *path)
2092 size_t len = ARR_LEN(path->path);
2094 for(size_t i = 0; i < len; ++i) {
2095 const type_path_entry_t *entry = & path->path[i];
2097 type_t *type = skip_typeref(entry->type);
2098 if (is_type_compound(type)) {
2099 /* in gcc mode structs can have no members */
2100 if (entry->v.compound_entry == NULL) {
2104 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2105 } else if (is_type_array(type)) {
2106 fprintf(stderr, "[%zu]", entry->v.index);
2108 fprintf(stderr, "-INVALID-");
2111 if (path->top_type != NULL) {
2112 fprintf(stderr, " (");
2113 print_type(path->top_type);
2114 fprintf(stderr, ")");
2119 * Return the top type path entry, ie. in a path
2120 * (type).a.b returns the b.
2122 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2124 size_t len = ARR_LEN(path->path);
2126 return &path->path[len-1];
2130 * Enlarge the type path by an (empty) element.
2132 static type_path_entry_t *append_to_type_path(type_path_t *path)
2134 size_t len = ARR_LEN(path->path);
2135 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2137 type_path_entry_t *result = & path->path[len];
2138 memset(result, 0, sizeof(result[0]));
2143 * Descending into a sub-type. Enter the scope of the current
2146 static void descend_into_subtype(type_path_t *path)
2148 type_t *orig_top_type = path->top_type;
2149 type_t *top_type = skip_typeref(orig_top_type);
2151 assert(is_type_compound(top_type) || is_type_array(top_type));
2153 type_path_entry_t *top = append_to_type_path(path);
2154 top->type = top_type;
2156 if (is_type_compound(top_type)) {
2157 declaration_t *declaration = top_type->compound.declaration;
2158 declaration_t *entry = declaration->scope.declarations;
2159 top->v.compound_entry = entry;
2161 if (entry != NULL) {
2162 path->top_type = entry->type;
2164 path->top_type = NULL;
2167 assert(is_type_array(top_type));
2170 path->top_type = top_type->array.element_type;
2175 * Pop an entry from the given type path, ie. returning from
2176 * (type).a.b to (type).a
2178 static void ascend_from_subtype(type_path_t *path)
2180 type_path_entry_t *top = get_type_path_top(path);
2182 path->top_type = top->type;
2184 size_t len = ARR_LEN(path->path);
2185 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2189 * Pop entries from the given type path until the given
2190 * path level is reached.
2192 static void ascend_to(type_path_t *path, size_t top_path_level)
2194 size_t len = ARR_LEN(path->path);
2196 while (len > top_path_level) {
2197 ascend_from_subtype(path);
2198 len = ARR_LEN(path->path);
2202 static bool walk_designator(type_path_t *path, const designator_t *designator,
2203 bool used_in_offsetof)
2205 for( ; designator != NULL; designator = designator->next) {
2206 type_path_entry_t *top = get_type_path_top(path);
2207 type_t *orig_type = top->type;
2209 type_t *type = skip_typeref(orig_type);
2211 if (designator->symbol != NULL) {
2212 symbol_t *symbol = designator->symbol;
2213 if (!is_type_compound(type)) {
2214 if (is_type_valid(type)) {
2215 errorf(&designator->source_position,
2216 "'.%Y' designator used for non-compound type '%T'",
2222 declaration_t *declaration = type->compound.declaration;
2223 declaration_t *iter = declaration->scope.declarations;
2224 for( ; iter != NULL; iter = iter->next) {
2225 if (iter->symbol == symbol) {
2230 errorf(&designator->source_position,
2231 "'%T' has no member named '%Y'", orig_type, symbol);
2234 if (used_in_offsetof) {
2235 type_t *real_type = skip_typeref(iter->type);
2236 if (real_type->kind == TYPE_BITFIELD) {
2237 errorf(&designator->source_position,
2238 "offsetof designator '%Y' may not specify bitfield",
2244 top->type = orig_type;
2245 top->v.compound_entry = iter;
2246 orig_type = iter->type;
2248 expression_t *array_index = designator->array_index;
2249 assert(designator->array_index != NULL);
2251 if (!is_type_array(type)) {
2252 if (is_type_valid(type)) {
2253 errorf(&designator->source_position,
2254 "[%E] designator used for non-array type '%T'",
2255 array_index, orig_type);
2259 if (!is_type_valid(array_index->base.type)) {
2263 long index = fold_constant(array_index);
2264 if (!used_in_offsetof) {
2266 errorf(&designator->source_position,
2267 "array index [%E] must be positive", array_index);
2270 if (type->array.size_constant == true) {
2271 long array_size = type->array.size;
2272 if (index >= array_size) {
2273 errorf(&designator->source_position,
2274 "designator [%E] (%d) exceeds array size %d",
2275 array_index, index, array_size);
2281 top->type = orig_type;
2282 top->v.index = (size_t) index;
2283 orig_type = type->array.element_type;
2285 path->top_type = orig_type;
2287 if (designator->next != NULL) {
2288 descend_into_subtype(path);
2297 static void advance_current_object(type_path_t *path, size_t top_path_level)
2299 type_path_entry_t *top = get_type_path_top(path);
2301 type_t *type = skip_typeref(top->type);
2302 if (is_type_union(type)) {
2303 /* in unions only the first element is initialized */
2304 top->v.compound_entry = NULL;
2305 } else if (is_type_struct(type)) {
2306 declaration_t *entry = top->v.compound_entry;
2308 entry = entry->next;
2309 top->v.compound_entry = entry;
2310 if (entry != NULL) {
2311 path->top_type = entry->type;
2315 assert(is_type_array(type));
2319 if (!type->array.size_constant || top->v.index < type->array.size) {
2324 /* we're past the last member of the current sub-aggregate, try if we
2325 * can ascend in the type hierarchy and continue with another subobject */
2326 size_t len = ARR_LEN(path->path);
2328 if (len > top_path_level) {
2329 ascend_from_subtype(path);
2330 advance_current_object(path, top_path_level);
2332 path->top_type = NULL;
2337 * skip until token is found.
2339 static void skip_until(int type)
2341 while (token.type != type) {
2342 if (token.type == T_EOF)
2349 * skip any {...} blocks until a closing bracket is reached.
2351 static void skip_initializers(void)
2353 if (token.type == '{')
2356 while (token.type != '}') {
2357 if (token.type == T_EOF)
2359 if (token.type == '{') {
2367 static initializer_t *create_empty_initializer(void)
2369 static initializer_t empty_initializer
2370 = { .list = { { INITIALIZER_LIST }, 0 } };
2371 return &empty_initializer;
2375 * Parse a part of an initialiser for a struct or union,
2377 static initializer_t *parse_sub_initializer(type_path_t *path,
2378 type_t *outer_type, size_t top_path_level,
2379 parse_initializer_env_t *env)
2381 if (token.type == '}') {
2382 /* empty initializer */
2383 return create_empty_initializer();
2386 type_t *orig_type = path->top_type;
2387 type_t *type = NULL;
2389 if (orig_type == NULL) {
2390 /* We are initializing an empty compound. */
2392 type = skip_typeref(orig_type);
2394 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2395 * initializers in this case. */
2396 if (!is_type_valid(type)) {
2397 skip_initializers();
2398 return create_empty_initializer();
2402 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2405 designator_t *designator = NULL;
2406 if (token.type == '.' || token.type == '[') {
2407 designator = parse_designation();
2408 goto finish_designator;
2409 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2410 /* GNU-style designator ("identifier: value") */
2411 designator = allocate_ast_zero(sizeof(designator[0]));
2412 designator->source_position = token.source_position;
2413 designator->symbol = token.v.symbol;
2418 /* reset path to toplevel, evaluate designator from there */
2419 ascend_to(path, top_path_level);
2420 if (!walk_designator(path, designator, false)) {
2421 /* can't continue after designation error */
2425 initializer_t *designator_initializer
2426 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2427 designator_initializer->designator.designator = designator;
2428 ARR_APP1(initializer_t*, initializers, designator_initializer);
2430 orig_type = path->top_type;
2431 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2436 if (token.type == '{') {
2437 if (type != NULL && is_type_scalar(type)) {
2438 sub = parse_scalar_initializer(type, env->must_be_constant);
2442 if (env->declaration != NULL) {
2443 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2444 env->declaration->symbol);
2446 errorf(HERE, "extra brace group at end of initializer");
2449 descend_into_subtype(path);
2451 add_anchor_token('}');
2452 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2454 rem_anchor_token('}');
2457 ascend_from_subtype(path);
2461 goto error_parse_next;
2465 /* must be an expression */
2466 expression_t *expression = parse_assignment_expression();
2468 if (env->must_be_constant && !is_initializer_constant(expression)) {
2469 errorf(&expression->base.source_position,
2470 "Initialisation expression '%E' is not constant\n",
2475 /* we are already outside, ... */
2479 /* handle { "string" } special case */
2480 if ((expression->kind == EXPR_STRING_LITERAL
2481 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2482 && outer_type != NULL) {
2483 sub = initializer_from_expression(outer_type, expression);
2485 if (token.type == ',') {
2488 if (token.type != '}') {
2489 warningf(HERE, "excessive elements in initializer for type '%T'",
2492 /* TODO: eat , ... */
2497 /* descend into subtypes until expression matches type */
2499 orig_type = path->top_type;
2500 type = skip_typeref(orig_type);
2502 sub = initializer_from_expression(orig_type, expression);
2506 if (!is_type_valid(type)) {
2509 if (is_type_scalar(type)) {
2510 errorf(&expression->base.source_position,
2511 "expression '%E' doesn't match expected type '%T'",
2512 expression, orig_type);
2516 descend_into_subtype(path);
2520 /* update largest index of top array */
2521 const type_path_entry_t *first = &path->path[0];
2522 type_t *first_type = first->type;
2523 first_type = skip_typeref(first_type);
2524 if (is_type_array(first_type)) {
2525 size_t index = first->v.index;
2526 if (index > path->max_index)
2527 path->max_index = index;
2531 /* append to initializers list */
2532 ARR_APP1(initializer_t*, initializers, sub);
2535 if (env->declaration != NULL)
2536 warningf(HERE, "excess elements in struct initializer for '%Y'",
2537 env->declaration->symbol);
2539 warningf(HERE, "excess elements in struct initializer");
2543 if (token.type == '}') {
2547 if (token.type == '}') {
2552 /* advance to the next declaration if we are not at the end */
2553 advance_current_object(path, top_path_level);
2554 orig_type = path->top_type;
2555 if (orig_type != NULL)
2556 type = skip_typeref(orig_type);
2562 size_t len = ARR_LEN(initializers);
2563 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2564 initializer_t *result = allocate_ast_zero(size);
2565 result->kind = INITIALIZER_LIST;
2566 result->list.len = len;
2567 memcpy(&result->list.initializers, initializers,
2568 len * sizeof(initializers[0]));
2570 DEL_ARR_F(initializers);
2571 ascend_to(path, top_path_level+1);
2576 skip_initializers();
2577 DEL_ARR_F(initializers);
2578 ascend_to(path, top_path_level+1);
2583 * Parses an initializer. Parsers either a compound literal
2584 * (env->declaration == NULL) or an initializer of a declaration.
2586 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2588 type_t *type = skip_typeref(env->type);
2589 initializer_t *result = NULL;
2592 if (is_type_scalar(type)) {
2593 result = parse_scalar_initializer(type, env->must_be_constant);
2594 } else if (token.type == '{') {
2598 memset(&path, 0, sizeof(path));
2599 path.top_type = env->type;
2600 path.path = NEW_ARR_F(type_path_entry_t, 0);
2602 descend_into_subtype(&path);
2604 add_anchor_token('}');
2605 result = parse_sub_initializer(&path, env->type, 1, env);
2606 rem_anchor_token('}');
2608 max_index = path.max_index;
2609 DEL_ARR_F(path.path);
2613 /* parse_scalar_initializer() also works in this case: we simply
2614 * have an expression without {} around it */
2615 result = parse_scalar_initializer(type, env->must_be_constant);
2618 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2619 * the array type size */
2620 if (is_type_array(type) && type->array.size_expression == NULL
2621 && result != NULL) {
2623 switch (result->kind) {
2624 case INITIALIZER_LIST:
2625 size = max_index + 1;
2628 case INITIALIZER_STRING:
2629 size = result->string.string.size;
2632 case INITIALIZER_WIDE_STRING:
2633 size = result->wide_string.string.size;
2636 case INITIALIZER_DESIGNATOR:
2637 case INITIALIZER_VALUE:
2638 /* can happen for parse errors */
2643 internal_errorf(HERE, "invalid initializer type");
2646 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2647 cnst->base.type = type_size_t;
2648 cnst->conste.v.int_value = size;
2650 type_t *new_type = duplicate_type(type);
2652 new_type->array.size_expression = cnst;
2653 new_type->array.size_constant = true;
2654 new_type->array.size = size;
2655 env->type = new_type;
2663 static declaration_t *append_declaration(declaration_t *declaration);
2665 static declaration_t *parse_compound_type_specifier(bool is_struct)
2667 gnu_attribute_t *attributes = NULL;
2668 decl_modifiers_t modifiers = 0;
2675 symbol_t *symbol = NULL;
2676 declaration_t *declaration = NULL;
2678 if (token.type == T___attribute__) {
2679 modifiers |= parse_attributes(&attributes);
2682 if (token.type == T_IDENTIFIER) {
2683 symbol = token.v.symbol;
2686 namespace_t const namespc =
2687 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2688 declaration = get_declaration(symbol, namespc);
2689 if (declaration != NULL) {
2690 if (declaration->parent_scope != scope &&
2691 (token.type == '{' || token.type == ';')) {
2693 } else if (declaration->init.complete &&
2694 token.type == '{') {
2695 assert(symbol != NULL);
2696 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2697 is_struct ? "struct" : "union", symbol,
2698 &declaration->source_position);
2699 declaration->scope.declarations = NULL;
2702 } else if (token.type != '{') {
2704 parse_error_expected("while parsing struct type specifier",
2705 T_IDENTIFIER, '{', NULL);
2707 parse_error_expected("while parsing union type specifier",
2708 T_IDENTIFIER, '{', NULL);
2714 if (declaration == NULL) {
2715 declaration = allocate_declaration_zero();
2716 declaration->namespc =
2717 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2718 declaration->source_position = token.source_position;
2719 declaration->symbol = symbol;
2720 declaration->parent_scope = scope;
2721 if (symbol != NULL) {
2722 environment_push(declaration);
2724 append_declaration(declaration);
2727 if (token.type == '{') {
2728 declaration->init.complete = true;
2730 parse_compound_type_entries(declaration);
2731 modifiers |= parse_attributes(&attributes);
2734 declaration->modifiers |= modifiers;
2738 static void parse_enum_entries(type_t *const enum_type)
2742 if (token.type == '}') {
2744 errorf(HERE, "empty enum not allowed");
2748 add_anchor_token('}');
2750 if (token.type != T_IDENTIFIER) {
2751 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2753 rem_anchor_token('}');
2757 declaration_t *const entry = allocate_declaration_zero();
2758 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2759 entry->type = enum_type;
2760 entry->symbol = token.v.symbol;
2761 entry->source_position = token.source_position;
2764 if (token.type == '=') {
2766 expression_t *value = parse_constant_expression();
2768 value = create_implicit_cast(value, enum_type);
2769 entry->init.enum_value = value;
2774 record_declaration(entry, false);
2776 if (token.type != ',')
2779 } while (token.type != '}');
2780 rem_anchor_token('}');
2788 static type_t *parse_enum_specifier(void)
2790 gnu_attribute_t *attributes = NULL;
2791 declaration_t *declaration;
2795 if (token.type == T_IDENTIFIER) {
2796 symbol = token.v.symbol;
2799 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2800 } else if (token.type != '{') {
2801 parse_error_expected("while parsing enum type specifier",
2802 T_IDENTIFIER, '{', NULL);
2809 if (declaration == NULL) {
2810 declaration = allocate_declaration_zero();
2811 declaration->namespc = NAMESPACE_ENUM;
2812 declaration->source_position = token.source_position;
2813 declaration->symbol = symbol;
2814 declaration->parent_scope = scope;
2817 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2818 type->enumt.declaration = declaration;
2820 if (token.type == '{') {
2821 if (declaration->init.complete) {
2822 errorf(HERE, "multiple definitions of enum %Y", symbol);
2824 if (symbol != NULL) {
2825 environment_push(declaration);
2827 append_declaration(declaration);
2828 declaration->init.complete = true;
2830 parse_enum_entries(type);
2831 parse_attributes(&attributes);
2838 * if a symbol is a typedef to another type, return true
2840 static bool is_typedef_symbol(symbol_t *symbol)
2842 const declaration_t *const declaration =
2843 get_declaration(symbol, NAMESPACE_NORMAL);
2845 declaration != NULL &&
2846 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2849 static type_t *parse_typeof(void)
2856 add_anchor_token(')');
2858 expression_t *expression = NULL;
2861 switch(token.type) {
2862 case T___extension__:
2863 /* This can be a prefix to a typename or an expression. We simply eat
2867 } while (token.type == T___extension__);
2871 if (is_typedef_symbol(token.v.symbol)) {
2872 type = parse_typename();
2874 expression = parse_expression();
2875 type = expression->base.type;
2880 type = parse_typename();
2884 expression = parse_expression();
2885 type = expression->base.type;
2889 rem_anchor_token(')');
2892 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2893 typeof_type->typeoft.expression = expression;
2894 typeof_type->typeoft.typeof_type = type;
2901 typedef enum specifiers_t {
2902 SPECIFIER_SIGNED = 1 << 0,
2903 SPECIFIER_UNSIGNED = 1 << 1,
2904 SPECIFIER_LONG = 1 << 2,
2905 SPECIFIER_INT = 1 << 3,
2906 SPECIFIER_DOUBLE = 1 << 4,
2907 SPECIFIER_CHAR = 1 << 5,
2908 SPECIFIER_SHORT = 1 << 6,
2909 SPECIFIER_LONG_LONG = 1 << 7,
2910 SPECIFIER_FLOAT = 1 << 8,
2911 SPECIFIER_BOOL = 1 << 9,
2912 SPECIFIER_VOID = 1 << 10,
2913 SPECIFIER_INT8 = 1 << 11,
2914 SPECIFIER_INT16 = 1 << 12,
2915 SPECIFIER_INT32 = 1 << 13,
2916 SPECIFIER_INT64 = 1 << 14,
2917 SPECIFIER_INT128 = 1 << 15,
2918 SPECIFIER_COMPLEX = 1 << 16,
2919 SPECIFIER_IMAGINARY = 1 << 17,
2922 static type_t *create_builtin_type(symbol_t *const symbol,
2923 type_t *const real_type)
2925 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2926 type->builtin.symbol = symbol;
2927 type->builtin.real_type = real_type;
2929 type_t *result = typehash_insert(type);
2930 if (type != result) {
2937 static type_t *get_typedef_type(symbol_t *symbol)
2939 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2940 if (declaration == NULL ||
2941 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2944 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2945 type->typedeft.declaration = declaration;
2951 * check for the allowed MS alignment values.
2953 static bool check_alignment_value(long long intvalue)
2955 if (intvalue < 1 || intvalue > 8192) {
2956 errorf(HERE, "illegal alignment value");
2959 unsigned v = (unsigned)intvalue;
2960 for(unsigned i = 1; i <= 8192; i += i) {
2964 errorf(HERE, "alignment must be power of two");
2968 #define DET_MOD(name, tag) do { \
2969 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2970 *modifiers |= tag; \
2973 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2975 decl_modifiers_t *modifiers = &specifiers->modifiers;
2978 if (token.type == T_restrict) {
2980 DET_MOD(restrict, DM_RESTRICT);
2982 } else if (token.type != T_IDENTIFIER)
2984 symbol_t *symbol = token.v.symbol;
2985 if (symbol == sym_align) {
2988 if (token.type != T_INTEGER)
2990 if (check_alignment_value(token.v.intvalue)) {
2991 if (specifiers->alignment != 0)
2992 warningf(HERE, "align used more than once");
2993 specifiers->alignment = (unsigned char)token.v.intvalue;
2997 } else if (symbol == sym_allocate) {
3000 if (token.type != T_IDENTIFIER)
3002 (void)token.v.symbol;
3004 } else if (symbol == sym_dllimport) {
3006 DET_MOD(dllimport, DM_DLLIMPORT);
3007 } else if (symbol == sym_dllexport) {
3009 DET_MOD(dllexport, DM_DLLEXPORT);
3010 } else if (symbol == sym_thread) {
3012 DET_MOD(thread, DM_THREAD);
3013 } else if (symbol == sym_naked) {
3015 DET_MOD(naked, DM_NAKED);
3016 } else if (symbol == sym_noinline) {
3018 DET_MOD(noinline, DM_NOINLINE);
3019 } else if (symbol == sym_noreturn) {
3021 DET_MOD(noreturn, DM_NORETURN);
3022 } else if (symbol == sym_nothrow) {
3024 DET_MOD(nothrow, DM_NOTHROW);
3025 } else if (symbol == sym_novtable) {
3027 DET_MOD(novtable, DM_NOVTABLE);
3028 } else if (symbol == sym_property) {
3032 bool is_get = false;
3033 if (token.type != T_IDENTIFIER)
3035 if (token.v.symbol == sym_get) {
3037 } else if (token.v.symbol == sym_put) {
3039 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3044 if (token.type != T_IDENTIFIER)
3047 if (specifiers->get_property_sym != NULL) {
3048 errorf(HERE, "get property name already specified");
3050 specifiers->get_property_sym = token.v.symbol;
3053 if (specifiers->put_property_sym != NULL) {
3054 errorf(HERE, "put property name already specified");
3056 specifiers->put_property_sym = token.v.symbol;
3060 if (token.type == ',') {
3067 } else if (symbol == sym_selectany) {
3069 DET_MOD(selectany, DM_SELECTANY);
3070 } else if (symbol == sym_uuid) {
3073 if (token.type != T_STRING_LITERAL)
3077 } else if (symbol == sym_deprecated) {
3079 if (specifiers->deprecated != 0)
3080 warningf(HERE, "deprecated used more than once");
3081 specifiers->deprecated = 1;
3082 if (token.type == '(') {
3084 if (token.type == T_STRING_LITERAL) {
3085 specifiers->deprecated_string = token.v.string.begin;
3088 errorf(HERE, "string literal expected");
3092 } else if (symbol == sym_noalias) {
3094 DET_MOD(noalias, DM_NOALIAS);
3096 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3098 if (token.type == '(')
3102 if (token.type == ',')
3109 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3111 declaration_t *const decl = allocate_declaration_zero();
3112 decl->source_position = *HERE;
3113 decl->declared_storage_class = storage_class;
3114 decl->storage_class =
3115 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3116 storage_class : STORAGE_CLASS_AUTO;
3117 decl->symbol = symbol;
3118 decl->implicit = true;
3119 record_declaration(decl, false);
3124 * Finish the construction of a struct type by calculating
3125 * its size, offsets, alignment.
3127 static void finish_struct_type(compound_type_t *type) {
3128 if (type->declaration == NULL)
3130 declaration_t *struct_decl = type->declaration;
3131 if (! struct_decl->init.complete)
3136 il_alignment_t alignment = 1;
3137 bool need_pad = false;
3139 declaration_t *entry = struct_decl->scope.declarations;
3140 for (; entry != NULL; entry = entry->next) {
3141 if (entry->namespc != NAMESPACE_NORMAL)
3144 type_t *m_type = skip_typeref(entry->type);
3145 il_alignment_t m_alignment = m_type->base.alignment;
3147 new_size = (size + m_alignment - 1) & -m_alignment;
3148 if (m_alignment > alignment)
3149 alignment = m_alignment;
3150 if (new_size > size)
3152 entry->offset = new_size;
3153 size = new_size + m_type->base.size;
3155 if (type->base.alignment != 0) {
3156 alignment = type->base.alignment;
3159 new_size = (size + alignment - 1) & -alignment;
3160 if (new_size > size)
3163 if (warning.padded && need_pad) {
3164 warningf(&struct_decl->source_position,
3165 "'%#T' needs padding", type, struct_decl->symbol);
3167 if (warning.packed && !need_pad) {
3168 warningf(&struct_decl->source_position,
3169 "superfluous packed attribute on '%#T'",
3170 type, struct_decl->symbol);
3173 type->base.size = new_size;
3174 type->base.alignment = alignment;
3178 * Finish the construction of an union type by calculating
3179 * its size and alignment.
3181 static void finish_union_type(compound_type_t *type) {
3182 if (type->declaration == NULL)
3184 declaration_t *union_decl = type->declaration;
3185 if (! union_decl->init.complete)
3189 il_alignment_t alignment = 1;
3191 declaration_t *entry = union_decl->scope.declarations;
3192 for (; entry != NULL; entry = entry->next) {
3193 if (entry->namespc != NAMESPACE_NORMAL)
3196 type_t *m_type = skip_typeref(entry->type);
3199 if (m_type->base.size > size)
3200 size = m_type->base.size;
3201 if (m_type->base.alignment > alignment)
3202 alignment = m_type->base.alignment;
3204 if (type->base.alignment != 0) {
3205 alignment = type->base.alignment;
3207 size = (size + alignment - 1) & -alignment;
3208 type->base.size = size;
3209 type->base.alignment = alignment;
3212 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3214 type_t *type = NULL;
3215 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3216 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3217 unsigned type_specifiers = 0;
3218 bool newtype = false;
3219 bool saw_error = false;
3221 specifiers->source_position = token.source_position;
3224 specifiers->modifiers
3225 |= parse_attributes(&specifiers->gnu_attributes);
3226 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3227 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3229 switch(token.type) {
3232 #define MATCH_STORAGE_CLASS(token, class) \
3234 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3235 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3237 specifiers->declared_storage_class = class; \
3241 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3242 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3243 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3244 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3245 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3250 add_anchor_token(')');
3251 parse_microsoft_extended_decl_modifier(specifiers);
3252 rem_anchor_token(')');
3257 switch (specifiers->declared_storage_class) {
3258 case STORAGE_CLASS_NONE:
3259 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3262 case STORAGE_CLASS_EXTERN:
3263 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3266 case STORAGE_CLASS_STATIC:
3267 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3271 errorf(HERE, "multiple storage classes in declaration specifiers");
3277 /* type qualifiers */
3278 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3280 qualifiers |= qualifier; \
3284 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3285 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3286 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3287 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3288 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3289 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3290 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3291 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3293 case T___extension__:
3298 /* type specifiers */
3299 #define MATCH_SPECIFIER(token, specifier, name) \
3302 if (type_specifiers & specifier) { \
3303 errorf(HERE, "multiple " name " type specifiers given"); \
3305 type_specifiers |= specifier; \
3309 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3310 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3311 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3312 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3313 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3314 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3315 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3316 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3317 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3318 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3319 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3320 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3321 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3322 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3323 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3324 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3326 case T__forceinline:
3327 /* only in microsoft mode */
3328 specifiers->modifiers |= DM_FORCEINLINE;
3333 specifiers->is_inline = true;
3338 if (type_specifiers & SPECIFIER_LONG_LONG) {
3339 errorf(HERE, "multiple type specifiers given");
3340 } else if (type_specifiers & SPECIFIER_LONG) {
3341 type_specifiers |= SPECIFIER_LONG_LONG;
3343 type_specifiers |= SPECIFIER_LONG;
3348 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3350 type->compound.declaration = parse_compound_type_specifier(true);
3351 finish_struct_type(&type->compound);
3355 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3356 type->compound.declaration = parse_compound_type_specifier(false);
3357 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3358 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3360 finish_union_type(&type->compound);
3363 type = parse_enum_specifier();
3366 type = parse_typeof();
3368 case T___builtin_va_list:
3369 type = duplicate_type(type_valist);
3373 case T_IDENTIFIER: {
3374 /* only parse identifier if we haven't found a type yet */
3375 if (type != NULL || type_specifiers != 0) {
3376 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3377 * declaration, so it doesn't generate errors about expecting '(' or
3379 switch (look_ahead(1)->type) {
3386 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3389 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3394 goto finish_specifiers;
3398 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3399 if (typedef_type == NULL) {
3400 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3401 * declaration, so it doesn't generate 'implicit int' followed by more
3402 * errors later on. */
3403 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3408 errorf(HERE, "%K does not name a type", &token);
3410 declaration_t *const decl =
3411 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3413 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3414 type->typedeft.declaration = decl;
3418 if (la1_type == '*')
3419 goto finish_specifiers;
3424 goto finish_specifiers;
3429 type = typedef_type;
3433 /* function specifier */
3435 goto finish_specifiers;
3440 if (type == NULL || (saw_error && type_specifiers != 0)) {
3441 atomic_type_kind_t atomic_type;
3443 /* match valid basic types */
3444 switch(type_specifiers) {
3445 case SPECIFIER_VOID:
3446 atomic_type = ATOMIC_TYPE_VOID;
3448 case SPECIFIER_CHAR:
3449 atomic_type = ATOMIC_TYPE_CHAR;
3451 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3452 atomic_type = ATOMIC_TYPE_SCHAR;
3454 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3455 atomic_type = ATOMIC_TYPE_UCHAR;
3457 case SPECIFIER_SHORT:
3458 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3459 case SPECIFIER_SHORT | SPECIFIER_INT:
3460 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3461 atomic_type = ATOMIC_TYPE_SHORT;
3463 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3464 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3465 atomic_type = ATOMIC_TYPE_USHORT;
3468 case SPECIFIER_SIGNED:
3469 case SPECIFIER_SIGNED | SPECIFIER_INT:
3470 atomic_type = ATOMIC_TYPE_INT;
3472 case SPECIFIER_UNSIGNED:
3473 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3474 atomic_type = ATOMIC_TYPE_UINT;
3476 case SPECIFIER_LONG:
3477 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3478 case SPECIFIER_LONG | SPECIFIER_INT:
3479 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3480 atomic_type = ATOMIC_TYPE_LONG;
3482 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3483 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3484 atomic_type = ATOMIC_TYPE_ULONG;
3487 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3488 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3489 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3490 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3492 atomic_type = ATOMIC_TYPE_LONGLONG;
3493 goto warn_about_long_long;
3495 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3496 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3498 atomic_type = ATOMIC_TYPE_ULONGLONG;
3499 warn_about_long_long:
3500 if (warning.long_long) {
3501 warningf(&specifiers->source_position,
3502 "ISO C90 does not support 'long long'");
3506 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3507 atomic_type = unsigned_int8_type_kind;
3510 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3511 atomic_type = unsigned_int16_type_kind;
3514 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3515 atomic_type = unsigned_int32_type_kind;
3518 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3519 atomic_type = unsigned_int64_type_kind;
3522 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3523 atomic_type = unsigned_int128_type_kind;
3526 case SPECIFIER_INT8:
3527 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3528 atomic_type = int8_type_kind;
3531 case SPECIFIER_INT16:
3532 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3533 atomic_type = int16_type_kind;
3536 case SPECIFIER_INT32:
3537 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3538 atomic_type = int32_type_kind;
3541 case SPECIFIER_INT64:
3542 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3543 atomic_type = int64_type_kind;
3546 case SPECIFIER_INT128:
3547 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3548 atomic_type = int128_type_kind;
3551 case SPECIFIER_FLOAT:
3552 atomic_type = ATOMIC_TYPE_FLOAT;
3554 case SPECIFIER_DOUBLE:
3555 atomic_type = ATOMIC_TYPE_DOUBLE;
3557 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3558 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3560 case SPECIFIER_BOOL:
3561 atomic_type = ATOMIC_TYPE_BOOL;
3563 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3564 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3565 atomic_type = ATOMIC_TYPE_FLOAT;
3567 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3568 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3569 atomic_type = ATOMIC_TYPE_DOUBLE;
3571 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3572 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3573 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3576 /* invalid specifier combination, give an error message */
3577 if (type_specifiers == 0) {
3579 specifiers->type = type_error_type;
3584 if (warning.implicit_int) {
3585 warningf(HERE, "no type specifiers in declaration, using 'int'");
3587 atomic_type = ATOMIC_TYPE_INT;
3590 errorf(HERE, "no type specifiers given in declaration");
3592 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3593 (type_specifiers & SPECIFIER_UNSIGNED)) {
3594 errorf(HERE, "signed and unsigned specifiers given");
3595 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3596 errorf(HERE, "only integer types can be signed or unsigned");
3598 errorf(HERE, "multiple datatypes in declaration");
3600 atomic_type = ATOMIC_TYPE_INVALID;
3603 if (type_specifiers & SPECIFIER_COMPLEX &&
3604 atomic_type != ATOMIC_TYPE_INVALID) {
3605 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3606 type->complex.akind = atomic_type;
3607 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3608 atomic_type != ATOMIC_TYPE_INVALID) {
3609 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3610 type->imaginary.akind = atomic_type;
3612 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3613 type->atomic.akind = atomic_type;
3616 } else if (type_specifiers != 0) {
3617 errorf(HERE, "multiple datatypes in declaration");
3620 /* FIXME: check type qualifiers here */
3622 type->base.qualifiers = qualifiers;
3623 type->base.modifiers = modifiers;
3625 type_t *result = typehash_insert(type);
3626 if (newtype && result != type) {
3630 specifiers->type = result;
3635 static type_qualifiers_t parse_type_qualifiers(void)
3637 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3640 switch(token.type) {
3641 /* type qualifiers */
3642 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3643 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3644 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3645 /* microsoft extended type modifiers */
3646 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3647 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3648 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3649 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3650 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3658 static declaration_t *parse_identifier_list(void)
3660 declaration_t *declarations = NULL;
3661 declaration_t *last_declaration = NULL;
3663 declaration_t *const declaration = allocate_declaration_zero();
3664 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3665 declaration->source_position = token.source_position;
3666 declaration->symbol = token.v.symbol;
3669 if (last_declaration != NULL) {
3670 last_declaration->next = declaration;
3672 declarations = declaration;
3674 last_declaration = declaration;
3676 if (token.type != ',') {
3680 } while (token.type == T_IDENTIFIER);
3682 return declarations;
3685 static type_t *automatic_type_conversion(type_t *orig_type);
3687 static void semantic_parameter(declaration_t *declaration)
3689 /* TODO: improve error messages */
3690 source_position_t const* const pos = &declaration->source_position;
3692 switch (declaration->declared_storage_class) {
3693 case STORAGE_CLASS_TYPEDEF:
3694 errorf(pos, "typedef not allowed in parameter list");
3697 /* Allowed storage classes */
3698 case STORAGE_CLASS_NONE:
3699 case STORAGE_CLASS_REGISTER:
3703 errorf(pos, "parameter may only have none or register storage class");
3707 type_t *const orig_type = declaration->type;
3708 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3709 * sugar. Turn it into a pointer.
3710 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3711 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3713 type_t *const type = automatic_type_conversion(orig_type);
3714 declaration->type = type;
3716 if (is_type_incomplete(skip_typeref(type))) {
3717 errorf(pos, "parameter '%#T' is of incomplete type",
3718 orig_type, declaration->symbol);
3722 static declaration_t *parse_parameter(void)
3724 declaration_specifiers_t specifiers;
3725 memset(&specifiers, 0, sizeof(specifiers));
3727 parse_declaration_specifiers(&specifiers);
3729 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3734 static declaration_t *parse_parameters(function_type_t *type)
3736 declaration_t *declarations = NULL;
3739 add_anchor_token(')');
3740 int saved_comma_state = save_and_reset_anchor_state(',');
3742 if (token.type == T_IDENTIFIER &&
3743 !is_typedef_symbol(token.v.symbol)) {
3744 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3745 if (la1_type == ',' || la1_type == ')') {
3746 type->kr_style_parameters = true;
3747 declarations = parse_identifier_list();
3748 goto parameters_finished;
3752 if (token.type == ')') {
3753 type->unspecified_parameters = 1;
3754 goto parameters_finished;
3757 declaration_t *declaration;
3758 declaration_t *last_declaration = NULL;
3759 function_parameter_t *parameter;
3760 function_parameter_t *last_parameter = NULL;
3763 switch(token.type) {
3767 goto parameters_finished;
3770 case T___extension__:
3772 declaration = parse_parameter();
3774 /* func(void) is not a parameter */
3775 if (last_parameter == NULL
3776 && token.type == ')'
3777 && declaration->symbol == NULL
3778 && skip_typeref(declaration->type) == type_void) {
3779 goto parameters_finished;
3781 semantic_parameter(declaration);
3783 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3784 memset(parameter, 0, sizeof(parameter[0]));
3785 parameter->type = declaration->type;
3787 if (last_parameter != NULL) {
3788 last_declaration->next = declaration;
3789 last_parameter->next = parameter;
3791 type->parameters = parameter;
3792 declarations = declaration;
3794 last_parameter = parameter;
3795 last_declaration = declaration;
3799 goto parameters_finished;
3801 if (token.type != ',') {
3802 goto parameters_finished;
3808 parameters_finished:
3809 rem_anchor_token(')');
3812 restore_anchor_state(',', saved_comma_state);
3813 return declarations;
3816 restore_anchor_state(',', saved_comma_state);
3820 typedef enum construct_type_kind_t {
3825 } construct_type_kind_t;
3827 typedef struct construct_type_t construct_type_t;
3828 struct construct_type_t {
3829 construct_type_kind_t kind;
3830 construct_type_t *next;
3833 typedef struct parsed_pointer_t parsed_pointer_t;
3834 struct parsed_pointer_t {
3835 construct_type_t construct_type;
3836 type_qualifiers_t type_qualifiers;
3839 typedef struct construct_function_type_t construct_function_type_t;
3840 struct construct_function_type_t {
3841 construct_type_t construct_type;
3842 type_t *function_type;
3845 typedef struct parsed_array_t parsed_array_t;
3846 struct parsed_array_t {
3847 construct_type_t construct_type;
3848 type_qualifiers_t type_qualifiers;
3854 typedef struct construct_base_type_t construct_base_type_t;
3855 struct construct_base_type_t {
3856 construct_type_t construct_type;
3860 static construct_type_t *parse_pointer_declarator(void)
3864 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3865 memset(pointer, 0, sizeof(pointer[0]));
3866 pointer->construct_type.kind = CONSTRUCT_POINTER;
3867 pointer->type_qualifiers = parse_type_qualifiers();
3869 return (construct_type_t*) pointer;
3872 static construct_type_t *parse_array_declarator(void)
3875 add_anchor_token(']');
3877 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3878 memset(array, 0, sizeof(array[0]));
3879 array->construct_type.kind = CONSTRUCT_ARRAY;
3881 if (token.type == T_static) {
3882 array->is_static = true;
3886 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3887 if (type_qualifiers != 0) {
3888 if (token.type == T_static) {
3889 array->is_static = true;
3893 array->type_qualifiers = type_qualifiers;
3895 if (token.type == '*' && look_ahead(1)->type == ']') {
3896 array->is_variable = true;
3898 } else if (token.type != ']') {
3899 array->size = parse_assignment_expression();
3902 rem_anchor_token(']');
3905 return (construct_type_t*) array;
3910 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3913 if (declaration != NULL) {
3914 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3916 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3918 if (mask & (mask-1)) {
3919 const char *first = NULL, *second = NULL;
3921 /* more than one calling convention set */
3922 if (declaration->modifiers & DM_CDECL) {
3923 if (first == NULL) first = "cdecl";
3924 else if (second == NULL) second = "cdecl";
3926 if (declaration->modifiers & DM_STDCALL) {
3927 if (first == NULL) first = "stdcall";
3928 else if (second == NULL) second = "stdcall";
3930 if (declaration->modifiers & DM_FASTCALL) {
3931 if (first == NULL) first = "fastcall";
3932 else if (second == NULL) second = "fastcall";
3934 if (declaration->modifiers & DM_THISCALL) {
3935 if (first == NULL) first = "thiscall";
3936 else if (second == NULL) second = "thiscall";
3938 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3941 if (declaration->modifiers & DM_CDECL)
3942 type->function.calling_convention = CC_CDECL;
3943 else if (declaration->modifiers & DM_STDCALL)
3944 type->function.calling_convention = CC_STDCALL;
3945 else if (declaration->modifiers & DM_FASTCALL)
3946 type->function.calling_convention = CC_FASTCALL;
3947 else if (declaration->modifiers & DM_THISCALL)
3948 type->function.calling_convention = CC_THISCALL;
3950 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3953 declaration_t *parameters = parse_parameters(&type->function);
3954 if (declaration != NULL) {
3955 declaration->scope.declarations = parameters;
3958 construct_function_type_t *construct_function_type =
3959 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3960 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3961 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3962 construct_function_type->function_type = type;
3964 return &construct_function_type->construct_type;
3967 static void fix_declaration_type(declaration_t *declaration)
3969 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3970 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3972 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3973 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3975 if (declaration->type->base.modifiers == type_modifiers)
3978 type_t *copy = duplicate_type(declaration->type);
3979 copy->base.modifiers = type_modifiers;
3981 type_t *result = typehash_insert(copy);
3982 if (result != copy) {
3983 obstack_free(type_obst, copy);
3986 declaration->type = result;
3989 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3990 bool may_be_abstract)
3992 /* construct a single linked list of construct_type_t's which describe
3993 * how to construct the final declarator type */
3994 construct_type_t *first = NULL;
3995 construct_type_t *last = NULL;
3996 gnu_attribute_t *attributes = NULL;
3998 decl_modifiers_t modifiers = parse_attributes(&attributes);
4001 while (token.type == '*') {
4002 construct_type_t *type = parse_pointer_declarator();
4012 /* TODO: find out if this is correct */
4013 modifiers |= parse_attributes(&attributes);
4016 if (declaration != NULL)
4017 declaration->modifiers |= modifiers;
4019 construct_type_t *inner_types = NULL;
4021 switch(token.type) {
4023 if (declaration == NULL) {
4024 errorf(HERE, "no identifier expected in typename");
4026 declaration->symbol = token.v.symbol;
4027 declaration->source_position = token.source_position;
4033 add_anchor_token(')');
4034 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4035 if (inner_types != NULL) {
4036 /* All later declarators only modify the return type, not declaration */
4039 rem_anchor_token(')');
4043 if (may_be_abstract)
4045 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4046 /* avoid a loop in the outermost scope, because eat_statement doesn't
4048 if (token.type == '}' && current_function == NULL) {
4056 construct_type_t *p = last;
4059 construct_type_t *type;
4060 switch(token.type) {
4062 type = parse_function_declarator(declaration);
4065 type = parse_array_declarator();
4068 goto declarator_finished;
4071 /* insert in the middle of the list (behind p) */
4073 type->next = p->next;
4084 declarator_finished:
4085 /* append inner_types at the end of the list, we don't to set last anymore
4086 * as it's not needed anymore */
4088 assert(first == NULL);
4089 first = inner_types;
4091 last->next = inner_types;
4099 static void parse_declaration_attributes(declaration_t *declaration)
4101 gnu_attribute_t *attributes = NULL;
4102 decl_modifiers_t modifiers = parse_attributes(&attributes);
4104 if (declaration == NULL)
4107 declaration->modifiers |= modifiers;
4108 /* check if we have these stupid mode attributes... */
4109 type_t *old_type = declaration->type;
4110 if (old_type == NULL)
4113 gnu_attribute_t *attribute = attributes;
4114 for ( ; attribute != NULL; attribute = attribute->next) {
4115 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4118 atomic_type_kind_t akind = attribute->u.akind;
4119 if (!is_type_signed(old_type)) {
4121 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4122 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4123 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4124 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4126 panic("invalid akind in mode attribute");
4130 = make_atomic_type(akind, old_type->base.qualifiers);
4134 static type_t *construct_declarator_type(construct_type_t *construct_list,
4137 construct_type_t *iter = construct_list;
4138 for( ; iter != NULL; iter = iter->next) {
4139 switch(iter->kind) {
4140 case CONSTRUCT_INVALID:
4141 internal_errorf(HERE, "invalid type construction found");
4142 case CONSTRUCT_FUNCTION: {
4143 construct_function_type_t *construct_function_type
4144 = (construct_function_type_t*) iter;
4146 type_t *function_type = construct_function_type->function_type;
4148 function_type->function.return_type = type;
4150 type_t *skipped_return_type = skip_typeref(type);
4151 if (is_type_function(skipped_return_type)) {
4152 errorf(HERE, "function returning function is not allowed");
4153 type = type_error_type;
4154 } else if (is_type_array(skipped_return_type)) {
4155 errorf(HERE, "function returning array is not allowed");
4156 type = type_error_type;
4158 type = function_type;
4163 case CONSTRUCT_POINTER: {
4164 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4165 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4166 pointer_type->pointer.points_to = type;
4167 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4169 type = pointer_type;
4173 case CONSTRUCT_ARRAY: {
4174 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4175 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4177 expression_t *size_expression = parsed_array->size;
4178 if (size_expression != NULL) {
4180 = create_implicit_cast(size_expression, type_size_t);
4183 array_type->base.qualifiers = parsed_array->type_qualifiers;
4184 array_type->array.element_type = type;
4185 array_type->array.is_static = parsed_array->is_static;
4186 array_type->array.is_variable = parsed_array->is_variable;
4187 array_type->array.size_expression = size_expression;
4189 if (size_expression != NULL) {
4190 if (is_constant_expression(size_expression)) {
4191 array_type->array.size_constant = true;
4192 array_type->array.size
4193 = fold_constant(size_expression);
4195 array_type->array.is_vla = true;
4199 type_t *skipped_type = skip_typeref(type);
4200 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4201 errorf(HERE, "array of void is not allowed");
4202 type = type_error_type;
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 (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",
4365 orig_type, declaration->symbol);
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 declaration_t *const declaration = allocate_declaration_zero();
4597 declaration->type = specifiers->type;
4598 declaration->declared_storage_class = specifiers->declared_storage_class;
4599 declaration->source_position = specifiers->source_position;
4600 declaration->modifiers = specifiers->modifiers;
4602 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4603 warningf(&declaration->source_position,
4604 "useless storage class in empty declaration");
4606 declaration->storage_class = STORAGE_CLASS_NONE;
4608 type_t *type = declaration->type;
4609 switch (type->kind) {
4610 case TYPE_COMPOUND_STRUCT:
4611 case TYPE_COMPOUND_UNION: {
4612 if (type->compound.declaration->symbol == NULL) {
4613 warningf(&declaration->source_position,
4614 "unnamed struct/union that defines no instances");
4623 warningf(&declaration->source_position, "empty declaration");
4627 append_declaration(declaration);
4630 static void parse_declaration_rest(declaration_t *ndeclaration,
4631 const declaration_specifiers_t *specifiers,
4632 parsed_declaration_func finished_declaration)
4634 add_anchor_token(';');
4635 add_anchor_token('=');
4636 add_anchor_token(',');
4638 declaration_t *declaration =
4639 finished_declaration(ndeclaration, token.type == '=');
4641 type_t *orig_type = declaration->type;
4642 type_t *type = skip_typeref(orig_type);
4644 if (type->kind != TYPE_FUNCTION &&
4645 declaration->is_inline &&
4646 is_type_valid(type)) {
4647 warningf(&declaration->source_position,
4648 "variable '%Y' declared 'inline'\n", declaration->symbol);
4651 if (token.type == '=') {
4652 parse_init_declarator_rest(declaration);
4655 if (token.type != ',')
4659 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4664 rem_anchor_token(';');
4665 rem_anchor_token('=');
4666 rem_anchor_token(',');
4669 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4671 symbol_t *symbol = declaration->symbol;
4672 if (symbol == NULL) {
4673 errorf(HERE, "anonymous declaration not valid as function parameter");
4676 namespace_t namespc = (namespace_t) declaration->namespc;
4677 if (namespc != NAMESPACE_NORMAL) {
4678 return record_declaration(declaration, false);
4681 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4682 if (previous_declaration == NULL ||
4683 previous_declaration->parent_scope != scope) {
4684 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4689 if (is_definition) {
4690 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4693 if (previous_declaration->type == NULL) {
4694 previous_declaration->type = declaration->type;
4695 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4696 previous_declaration->storage_class = declaration->storage_class;
4697 previous_declaration->parent_scope = scope;
4698 return previous_declaration;
4700 return record_declaration(declaration, false);
4704 static void parse_declaration(parsed_declaration_func finished_declaration)
4706 declaration_specifiers_t specifiers;
4707 memset(&specifiers, 0, sizeof(specifiers));
4708 parse_declaration_specifiers(&specifiers);
4710 if (token.type == ';') {
4711 parse_anonymous_declaration_rest(&specifiers);
4713 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4714 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4718 static type_t *get_default_promoted_type(type_t *orig_type)
4720 type_t *result = orig_type;
4722 type_t *type = skip_typeref(orig_type);
4723 if (is_type_integer(type)) {
4724 result = promote_integer(type);
4725 } else if (type == type_float) {
4726 result = type_double;
4732 static void parse_kr_declaration_list(declaration_t *declaration)
4734 type_t *type = skip_typeref(declaration->type);
4735 if (!is_type_function(type))
4738 if (!type->function.kr_style_parameters)
4741 /* push function parameters */
4742 int top = environment_top();
4743 scope_t *last_scope = scope;
4744 set_scope(&declaration->scope);
4746 declaration_t *parameter = declaration->scope.declarations;
4747 for ( ; parameter != NULL; parameter = parameter->next) {
4748 assert(parameter->parent_scope == NULL);
4749 parameter->parent_scope = scope;
4750 environment_push(parameter);
4753 /* parse declaration list */
4754 while (is_declaration_specifier(&token, false)) {
4755 parse_declaration(finished_kr_declaration);
4758 /* pop function parameters */
4759 assert(scope == &declaration->scope);
4760 set_scope(last_scope);
4761 environment_pop_to(top);
4763 /* update function type */
4764 type_t *new_type = duplicate_type(type);
4766 function_parameter_t *parameters = NULL;
4767 function_parameter_t *last_parameter = NULL;
4769 declaration_t *parameter_declaration = declaration->scope.declarations;
4770 for( ; parameter_declaration != NULL;
4771 parameter_declaration = parameter_declaration->next) {
4772 type_t *parameter_type = parameter_declaration->type;
4773 if (parameter_type == NULL) {
4775 errorf(HERE, "no type specified for function parameter '%Y'",
4776 parameter_declaration->symbol);
4778 if (warning.implicit_int) {
4779 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4780 parameter_declaration->symbol);
4782 parameter_type = type_int;
4783 parameter_declaration->type = parameter_type;
4787 semantic_parameter(parameter_declaration);
4788 parameter_type = parameter_declaration->type;
4791 * we need the default promoted types for the function type
4793 parameter_type = get_default_promoted_type(parameter_type);
4795 function_parameter_t *function_parameter
4796 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4797 memset(function_parameter, 0, sizeof(function_parameter[0]));
4799 function_parameter->type = parameter_type;
4800 if (last_parameter != NULL) {
4801 last_parameter->next = function_parameter;
4803 parameters = function_parameter;
4805 last_parameter = function_parameter;
4808 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4810 new_type->function.parameters = parameters;
4811 new_type->function.unspecified_parameters = true;
4813 type = typehash_insert(new_type);
4814 if (type != new_type) {
4815 obstack_free(type_obst, new_type);
4818 declaration->type = type;
4821 static bool first_err = true;
4824 * When called with first_err set, prints the name of the current function,
4827 static void print_in_function(void)
4831 diagnosticf("%s: In function '%Y':\n",
4832 current_function->source_position.input_name,
4833 current_function->symbol);
4838 * Check if all labels are defined in the current function.
4839 * Check if all labels are used in the current function.
4841 static void check_labels(void)
4843 for (const goto_statement_t *goto_statement = goto_first;
4844 goto_statement != NULL;
4845 goto_statement = goto_statement->next) {
4846 /* skip computed gotos */
4847 if (goto_statement->expression != NULL)
4850 declaration_t *label = goto_statement->label;
4853 if (label->source_position.input_name == NULL) {
4854 print_in_function();
4855 errorf(&goto_statement->base.source_position,
4856 "label '%Y' used but not defined", label->symbol);
4859 goto_first = goto_last = NULL;
4861 if (warning.unused_label) {
4862 for (const label_statement_t *label_statement = label_first;
4863 label_statement != NULL;
4864 label_statement = label_statement->next) {
4865 const declaration_t *label = label_statement->label;
4867 if (! label->used) {
4868 print_in_function();
4869 warningf(&label_statement->base.source_position,
4870 "label '%Y' defined but not used", label->symbol);
4874 label_first = label_last = NULL;
4878 * Check declarations of current_function for unused entities.
4880 static void check_declarations(void)
4882 if (warning.unused_parameter) {
4883 const scope_t *scope = ¤t_function->scope;
4885 if (is_sym_main(current_function->symbol)) {
4886 /* do not issue unused warnings for main */
4889 const declaration_t *parameter = scope->declarations;
4890 for (; parameter != NULL; parameter = parameter->next) {
4891 if (! parameter->used) {
4892 print_in_function();
4893 warningf(¶meter->source_position,
4894 "unused parameter '%Y'", parameter->symbol);
4898 if (warning.unused_variable) {
4902 static int determine_truth(expression_t const* const cond)
4905 !is_constant_expression(cond) ? 0 :
4906 fold_constant(cond) != 0 ? 1 :
4910 static bool noreturn_candidate;
4912 static void check_reachable(statement_t *const stmt)
4914 if (stmt->base.reachable)
4916 if (stmt->kind != STATEMENT_DO_WHILE)
4917 stmt->base.reachable = true;
4919 statement_t *last = stmt;
4921 switch (stmt->kind) {
4922 case STATEMENT_INVALID:
4923 case STATEMENT_EMPTY:
4924 case STATEMENT_DECLARATION:
4926 next = stmt->base.next;
4929 case STATEMENT_COMPOUND:
4930 next = stmt->compound.statements;
4933 case STATEMENT_RETURN:
4934 noreturn_candidate = false;
4937 case STATEMENT_IF: {
4938 if_statement_t const* const ifs = &stmt->ifs;
4939 int const val = determine_truth(ifs->condition);
4942 check_reachable(ifs->true_statement);
4947 if (ifs->false_statement != NULL) {
4948 check_reachable(ifs->false_statement);
4952 next = stmt->base.next;
4956 case STATEMENT_SWITCH: {
4957 switch_statement_t const *const switchs = &stmt->switchs;
4958 expression_t const *const expr = switchs->expression;
4960 if (is_constant_expression(expr)) {
4961 long const val = fold_constant(expr);
4962 case_label_statement_t * defaults = NULL;
4963 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4964 if (i->expression == NULL) {
4969 if (i->first_case <= val && val <= i->last_case) {
4970 check_reachable((statement_t*)i);
4975 if (defaults != NULL) {
4976 check_reachable((statement_t*)defaults);
4980 bool has_default = false;
4981 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4982 if (i->expression == NULL)
4985 check_reachable((statement_t*)i);
4992 next = stmt->base.next;
4996 case STATEMENT_EXPRESSION: {
4997 /* Check for noreturn function call */
4998 expression_t const *const expr = stmt->expression.expression;
4999 if (expr->kind == EXPR_CALL) {
5000 expression_t const *const func = expr->call.function;
5001 if (func->kind == EXPR_REFERENCE) {
5002 declaration_t const *const decl = func->reference.declaration;
5003 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5009 next = stmt->base.next;
5013 case STATEMENT_CONTINUE: {
5014 statement_t *parent = stmt;
5016 parent = parent->base.parent;
5017 if (parent == NULL) /* continue not within loop */
5021 switch (parent->kind) {
5022 case STATEMENT_WHILE: goto continue_while;
5023 case STATEMENT_DO_WHILE: goto continue_do_while;
5024 case STATEMENT_FOR: goto continue_for;
5031 case STATEMENT_BREAK: {
5032 statement_t *parent = stmt;
5034 parent = parent->base.parent;
5035 if (parent == NULL) /* break not within loop/switch */
5038 switch (parent->kind) {
5039 case STATEMENT_SWITCH:
5040 case STATEMENT_WHILE:
5041 case STATEMENT_DO_WHILE:
5044 next = parent->base.next;
5045 goto found_break_parent;
5054 case STATEMENT_GOTO:
5055 if (stmt->gotos.expression) {
5056 statement_t *parent = stmt->base.parent;
5057 if (parent == NULL) /* top level goto */
5061 next = stmt->gotos.label->init.statement;
5062 if (next == NULL) /* missing label */
5067 case STATEMENT_LABEL:
5068 next = stmt->label.statement;
5071 case STATEMENT_CASE_LABEL:
5072 next = stmt->case_label.statement;
5075 case STATEMENT_WHILE: {
5076 while_statement_t const *const whiles = &stmt->whiles;
5077 int const val = determine_truth(whiles->condition);
5080 check_reachable(whiles->body);
5085 next = stmt->base.next;
5089 case STATEMENT_DO_WHILE:
5090 next = stmt->do_while.body;
5093 case STATEMENT_FOR: {
5094 for_statement_t *const fors = &stmt->fors;
5096 if (fors->condition_reachable)
5098 fors->condition_reachable = true;
5100 expression_t const *const cond = fors->condition;
5102 cond == NULL ? 1 : determine_truth(cond);
5105 check_reachable(fors->body);
5110 next = stmt->base.next;
5114 case STATEMENT_MS_TRY: {
5115 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5116 check_reachable(ms_try->try_statement);
5117 next = ms_try->final_statement;
5121 case STATEMENT_LEAVE: {
5122 statement_t *parent = stmt;
5124 parent = parent->base.parent;
5125 if (parent == NULL) /* __leave not within __try */
5128 if (parent->kind == STATEMENT_MS_TRY) {
5130 next = parent->ms_try.final_statement;
5138 while (next == NULL) {
5139 next = last->base.parent;
5141 noreturn_candidate = false;
5143 type_t *const type = current_function->type;
5144 assert(is_type_function(type));
5145 type_t *const ret = skip_typeref(type->function.return_type);
5146 if (warning.return_type &&
5147 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5148 is_type_valid(ret) &&
5149 !is_sym_main(current_function->symbol)) {
5150 warningf(&stmt->base.source_position,
5151 "control reaches end of non-void function");
5156 switch (next->kind) {
5157 case STATEMENT_INVALID:
5158 case STATEMENT_EMPTY:
5159 case STATEMENT_DECLARATION:
5160 case STATEMENT_EXPRESSION:
5162 case STATEMENT_RETURN:
5163 case STATEMENT_CONTINUE:
5164 case STATEMENT_BREAK:
5165 case STATEMENT_GOTO:
5166 case STATEMENT_LEAVE:
5167 panic("invalid control flow in function");
5169 case STATEMENT_COMPOUND:
5171 case STATEMENT_SWITCH:
5172 case STATEMENT_LABEL:
5173 case STATEMENT_CASE_LABEL:
5175 next = next->base.next;
5178 case STATEMENT_WHILE: {
5180 if (next->base.reachable)
5182 next->base.reachable = true;
5184 while_statement_t const *const whiles = &next->whiles;
5185 int const val = determine_truth(whiles->condition);
5188 check_reachable(whiles->body);
5194 next = next->base.next;
5198 case STATEMENT_DO_WHILE: {
5200 if (next->base.reachable)
5202 next->base.reachable = true;
5204 do_while_statement_t const *const dw = &next->do_while;
5205 int const val = determine_truth(dw->condition);
5208 check_reachable(dw->body);
5214 next = next->base.next;
5218 case STATEMENT_FOR: {
5220 for_statement_t *const fors = &next->fors;
5222 fors->step_reachable = true;
5224 if (fors->condition_reachable)
5226 fors->condition_reachable = true;
5228 expression_t const *const cond = fors->condition;
5230 cond == NULL ? 1 : determine_truth(cond);
5233 check_reachable(fors->body);
5239 next = next->base.next;
5243 case STATEMENT_MS_TRY:
5245 next = next->ms_try.final_statement;
5251 next = stmt->base.parent;
5253 warningf(&stmt->base.source_position,
5254 "control reaches end of non-void function");
5258 check_reachable(next);
5261 static void check_unreachable(statement_t const* const stmt)
5263 if (!stmt->base.reachable &&
5264 stmt->kind != STATEMENT_DO_WHILE &&
5265 stmt->kind != STATEMENT_FOR &&
5266 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5267 warningf(&stmt->base.source_position, "statement is unreachable");
5270 switch (stmt->kind) {
5271 case STATEMENT_INVALID:
5272 case STATEMENT_EMPTY:
5273 case STATEMENT_RETURN:
5274 case STATEMENT_DECLARATION:
5275 case STATEMENT_EXPRESSION:
5276 case STATEMENT_CONTINUE:
5277 case STATEMENT_BREAK:
5278 case STATEMENT_GOTO:
5280 case STATEMENT_LEAVE:
5283 case STATEMENT_COMPOUND:
5284 if (stmt->compound.statements)
5285 check_unreachable(stmt->compound.statements);
5289 check_unreachable(stmt->ifs.true_statement);
5290 if (stmt->ifs.false_statement != NULL)
5291 check_unreachable(stmt->ifs.false_statement);
5294 case STATEMENT_SWITCH:
5295 check_unreachable(stmt->switchs.body);
5298 case STATEMENT_LABEL:
5299 check_unreachable(stmt->label.statement);
5302 case STATEMENT_CASE_LABEL:
5303 check_unreachable(stmt->case_label.statement);
5306 case STATEMENT_WHILE:
5307 check_unreachable(stmt->whiles.body);
5310 case STATEMENT_DO_WHILE:
5311 check_unreachable(stmt->do_while.body);
5312 if (!stmt->base.reachable) {
5313 expression_t const *const cond = stmt->do_while.condition;
5314 if (determine_truth(cond) >= 0) {
5315 warningf(&cond->base.source_position,
5316 "condition of do-while-loop is unreachable");
5321 case STATEMENT_FOR: {
5322 for_statement_t const* const fors = &stmt->fors;
5324 // if init and step are unreachable, cond is unreachable, too
5325 if (!stmt->base.reachable && !fors->step_reachable) {
5326 warningf(&stmt->base.source_position, "statement is unreachable");
5328 if (!stmt->base.reachable && fors->initialisation != NULL) {
5329 warningf(&fors->initialisation->base.source_position,
5330 "initialisation of for-statement is unreachable");
5333 if (!fors->condition_reachable && fors->condition != NULL) {
5334 warningf(&fors->condition->base.source_position,
5335 "condition of for-statement is unreachable");
5338 if (!fors->step_reachable && fors->step != NULL) {
5339 warningf(&fors->step->base.source_position,
5340 "step of for-statement is unreachable");
5344 check_unreachable(fors->body);
5348 case STATEMENT_MS_TRY: {
5349 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5350 check_unreachable(ms_try->try_statement);
5351 check_unreachable(ms_try->final_statement);
5355 if (stmt->base.next)
5356 check_unreachable(stmt->base.next);
5359 static void parse_external_declaration(void)
5361 /* function-definitions and declarations both start with declaration
5363 declaration_specifiers_t specifiers;
5364 memset(&specifiers, 0, sizeof(specifiers));
5366 add_anchor_token(';');
5367 parse_declaration_specifiers(&specifiers);
5368 rem_anchor_token(';');
5370 /* must be a declaration */
5371 if (token.type == ';') {
5372 parse_anonymous_declaration_rest(&specifiers);
5376 add_anchor_token(',');
5377 add_anchor_token('=');
5378 rem_anchor_token(';');
5380 /* declarator is common to both function-definitions and declarations */
5381 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5383 rem_anchor_token(',');
5384 rem_anchor_token('=');
5385 rem_anchor_token(';');
5387 /* must be a declaration */
5388 switch (token.type) {
5392 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5396 /* must be a function definition */
5397 parse_kr_declaration_list(ndeclaration);
5399 if (token.type != '{') {
5400 parse_error_expected("while parsing function definition", '{', NULL);
5401 eat_until_matching_token(';');
5405 type_t *type = ndeclaration->type;
5407 /* note that we don't skip typerefs: the standard doesn't allow them here
5408 * (so we can't use is_type_function here) */
5409 if (type->kind != TYPE_FUNCTION) {
5410 if (is_type_valid(type)) {
5411 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5412 type, ndeclaration->symbol);
5418 if (warning.aggregate_return &&
5419 is_type_compound(skip_typeref(type->function.return_type))) {
5420 warningf(HERE, "function '%Y' returns an aggregate",
5421 ndeclaration->symbol);
5423 if (warning.traditional && !type->function.unspecified_parameters) {
5424 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5425 ndeclaration->symbol);
5427 if (warning.old_style_definition && type->function.unspecified_parameters) {
5428 warningf(HERE, "old-style function definition '%Y'",
5429 ndeclaration->symbol);
5432 /* § 6.7.5.3 (14) a function definition with () means no
5433 * parameters (and not unspecified parameters) */
5434 if (type->function.unspecified_parameters
5435 && type->function.parameters == NULL
5436 && !type->function.kr_style_parameters) {
5437 type_t *duplicate = duplicate_type(type);
5438 duplicate->function.unspecified_parameters = false;
5440 type = typehash_insert(duplicate);
5441 if (type != duplicate) {
5442 obstack_free(type_obst, duplicate);
5444 ndeclaration->type = type;
5447 declaration_t *const declaration = record_declaration(ndeclaration, true);
5448 if (ndeclaration != declaration) {
5449 declaration->scope = ndeclaration->scope;
5451 type = skip_typeref(declaration->type);
5453 /* push function parameters and switch scope */
5454 int top = environment_top();
5455 scope_t *last_scope = scope;
5456 set_scope(&declaration->scope);
5458 declaration_t *parameter = declaration->scope.declarations;
5459 for( ; parameter != NULL; parameter = parameter->next) {
5460 if (parameter->parent_scope == &ndeclaration->scope) {
5461 parameter->parent_scope = scope;
5463 assert(parameter->parent_scope == NULL
5464 || parameter->parent_scope == scope);
5465 parameter->parent_scope = scope;
5466 if (parameter->symbol == NULL) {
5467 errorf(¶meter->source_position, "parameter name omitted");
5470 environment_push(parameter);
5473 if (declaration->init.statement != NULL) {
5474 parser_error_multiple_definition(declaration, HERE);
5477 /* parse function body */
5478 int label_stack_top = label_top();
5479 declaration_t *old_current_function = current_function;
5480 current_function = declaration;
5481 current_parent = NULL;
5483 statement_t *const body = parse_compound_statement(false);
5484 declaration->init.statement = body;
5487 check_declarations();
5488 if (warning.return_type ||
5489 warning.unreachable_code ||
5490 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5491 noreturn_candidate = true;
5492 check_reachable(body);
5493 if (warning.unreachable_code)
5494 check_unreachable(body);
5495 if (warning.missing_noreturn &&
5496 noreturn_candidate &&
5497 !(declaration->modifiers & DM_NORETURN)) {
5498 warningf(&body->base.source_position,
5499 "function '%#T' is candidate for attribute 'noreturn'",
5500 type, declaration->symbol);
5504 assert(current_parent == NULL);
5505 assert(current_function == declaration);
5506 current_function = old_current_function;
5507 label_pop_to(label_stack_top);
5510 assert(scope == &declaration->scope);
5511 set_scope(last_scope);
5512 environment_pop_to(top);
5515 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5516 source_position_t *source_position)
5518 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5520 type->bitfield.base_type = base_type;
5521 type->bitfield.size = size;
5526 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5529 declaration_t *iter = compound_declaration->scope.declarations;
5530 for( ; iter != NULL; iter = iter->next) {
5531 if (iter->namespc != NAMESPACE_NORMAL)
5534 if (iter->symbol == NULL) {
5535 type_t *type = skip_typeref(iter->type);
5536 if (is_type_compound(type)) {
5537 declaration_t *result
5538 = find_compound_entry(type->compound.declaration, symbol);
5545 if (iter->symbol == symbol) {
5553 static void parse_compound_declarators(declaration_t *struct_declaration,
5554 const declaration_specifiers_t *specifiers)
5556 declaration_t *last_declaration = struct_declaration->scope.declarations;
5557 if (last_declaration != NULL) {
5558 while (last_declaration->next != NULL) {
5559 last_declaration = last_declaration->next;
5564 declaration_t *declaration;
5566 if (token.type == ':') {
5567 source_position_t source_position = *HERE;
5570 type_t *base_type = specifiers->type;
5571 expression_t *size = parse_constant_expression();
5573 if (!is_type_integer(skip_typeref(base_type))) {
5574 errorf(HERE, "bitfield base type '%T' is not an integer type",
5578 type_t *type = make_bitfield_type(base_type, size, &source_position);
5580 declaration = allocate_declaration_zero();
5581 declaration->namespc = NAMESPACE_NORMAL;
5582 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5583 declaration->storage_class = STORAGE_CLASS_NONE;
5584 declaration->source_position = source_position;
5585 declaration->modifiers = specifiers->modifiers;
5586 declaration->type = type;
5588 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5590 type_t *orig_type = declaration->type;
5591 type_t *type = skip_typeref(orig_type);
5593 if (token.type == ':') {
5594 source_position_t source_position = *HERE;
5596 expression_t *size = parse_constant_expression();
5598 if (!is_type_integer(type)) {
5599 errorf(HERE, "bitfield base type '%T' is not an integer type",
5603 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5604 declaration->type = bitfield_type;
5606 /* TODO we ignore arrays for now... what is missing is a check
5607 * that they're at the end of the struct */
5608 if (is_type_incomplete(type) && !is_type_array(type)) {
5610 "compound member '%Y' has incomplete type '%T'",
5611 declaration->symbol, orig_type);
5612 } else if (is_type_function(type)) {
5613 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5614 declaration->symbol, orig_type);
5619 /* make sure we don't define a symbol multiple times */
5620 symbol_t *symbol = declaration->symbol;
5621 if (symbol != NULL) {
5622 declaration_t *prev_decl
5623 = find_compound_entry(struct_declaration, symbol);
5625 if (prev_decl != NULL) {
5626 assert(prev_decl->symbol == symbol);
5627 errorf(&declaration->source_position,
5628 "multiple declarations of symbol '%Y' (declared %P)",
5629 symbol, &prev_decl->source_position);
5633 /* append declaration */
5634 if (last_declaration != NULL) {
5635 last_declaration->next = declaration;
5637 struct_declaration->scope.declarations = declaration;
5639 last_declaration = declaration;
5641 if (token.type != ',')
5651 static void parse_compound_type_entries(declaration_t *compound_declaration)
5654 add_anchor_token('}');
5656 while (token.type != '}' && token.type != T_EOF) {
5657 declaration_specifiers_t specifiers;
5658 memset(&specifiers, 0, sizeof(specifiers));
5659 parse_declaration_specifiers(&specifiers);
5661 parse_compound_declarators(compound_declaration, &specifiers);
5663 rem_anchor_token('}');
5665 if (token.type == T_EOF) {
5666 errorf(HERE, "EOF while parsing struct");
5671 static type_t *parse_typename(void)
5673 declaration_specifiers_t specifiers;
5674 memset(&specifiers, 0, sizeof(specifiers));
5675 parse_declaration_specifiers(&specifiers);
5676 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5677 /* TODO: improve error message, user does probably not know what a
5678 * storage class is...
5680 errorf(HERE, "typename may not have a storage class");
5683 type_t *result = parse_abstract_declarator(specifiers.type);
5691 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5692 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5693 expression_t *left);
5695 typedef struct expression_parser_function_t expression_parser_function_t;
5696 struct expression_parser_function_t {
5697 unsigned precedence;
5698 parse_expression_function parser;
5699 unsigned infix_precedence;
5700 parse_expression_infix_function infix_parser;
5703 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5706 * Prints an error message if an expression was expected but not read
5708 static expression_t *expected_expression_error(void)
5710 /* skip the error message if the error token was read */
5711 if (token.type != T_ERROR) {
5712 errorf(HERE, "expected expression, got token '%K'", &token);
5716 return create_invalid_expression();
5720 * Parse a string constant.
5722 static expression_t *parse_string_const(void)
5725 if (token.type == T_STRING_LITERAL) {
5726 string_t res = token.v.string;
5728 while (token.type == T_STRING_LITERAL) {
5729 res = concat_strings(&res, &token.v.string);
5732 if (token.type != T_WIDE_STRING_LITERAL) {
5733 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5734 /* note: that we use type_char_ptr here, which is already the
5735 * automatic converted type. revert_automatic_type_conversion
5736 * will construct the array type */
5737 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5738 cnst->string.value = res;
5742 wres = concat_string_wide_string(&res, &token.v.wide_string);
5744 wres = token.v.wide_string;
5749 switch (token.type) {
5750 case T_WIDE_STRING_LITERAL:
5751 wres = concat_wide_strings(&wres, &token.v.wide_string);
5754 case T_STRING_LITERAL:
5755 wres = concat_wide_string_string(&wres, &token.v.string);
5759 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5760 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5761 cnst->wide_string.value = wres;
5770 * Parse an integer constant.
5772 static expression_t *parse_int_const(void)
5774 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5775 cnst->base.source_position = *HERE;
5776 cnst->base.type = token.datatype;
5777 cnst->conste.v.int_value = token.v.intvalue;
5785 * Parse a character constant.
5787 static expression_t *parse_character_constant(void)
5789 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5791 cnst->base.source_position = *HERE;
5792 cnst->base.type = token.datatype;
5793 cnst->conste.v.character = token.v.string;
5795 if (cnst->conste.v.character.size != 1) {
5796 if (warning.multichar && (c_mode & _GNUC)) {
5798 warningf(HERE, "multi-character character constant");
5800 errorf(HERE, "more than 1 characters in character constant");
5809 * Parse a wide character constant.
5811 static expression_t *parse_wide_character_constant(void)
5813 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5815 cnst->base.source_position = *HERE;
5816 cnst->base.type = token.datatype;
5817 cnst->conste.v.wide_character = token.v.wide_string;
5819 if (cnst->conste.v.wide_character.size != 1) {
5820 if (warning.multichar && (c_mode & _GNUC)) {
5822 warningf(HERE, "multi-character character constant");
5824 errorf(HERE, "more than 1 characters in character constant");
5833 * Parse a float constant.
5835 static expression_t *parse_float_const(void)
5837 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5838 cnst->base.type = token.datatype;
5839 cnst->conste.v.float_value = token.v.floatvalue;
5846 static declaration_t *create_implicit_function(symbol_t *symbol,
5847 const source_position_t *source_position)
5849 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5850 ntype->function.return_type = type_int;
5851 ntype->function.unspecified_parameters = true;
5853 type_t *type = typehash_insert(ntype);
5854 if (type != ntype) {
5858 declaration_t *const declaration = allocate_declaration_zero();
5859 declaration->storage_class = STORAGE_CLASS_EXTERN;
5860 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5861 declaration->type = type;
5862 declaration->symbol = symbol;
5863 declaration->source_position = *source_position;
5864 declaration->implicit = true;
5866 bool strict_prototypes_old = warning.strict_prototypes;
5867 warning.strict_prototypes = false;
5868 record_declaration(declaration, false);
5869 warning.strict_prototypes = strict_prototypes_old;
5875 * Creates a return_type (func)(argument_type) function type if not
5878 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5879 type_t *argument_type2)
5881 function_parameter_t *parameter2
5882 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5883 memset(parameter2, 0, sizeof(parameter2[0]));
5884 parameter2->type = argument_type2;
5886 function_parameter_t *parameter1
5887 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5888 memset(parameter1, 0, sizeof(parameter1[0]));
5889 parameter1->type = argument_type1;
5890 parameter1->next = parameter2;
5892 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5893 type->function.return_type = return_type;
5894 type->function.parameters = parameter1;
5896 type_t *result = typehash_insert(type);
5897 if (result != type) {
5905 * Creates a return_type (func)(argument_type) function type if not
5908 * @param return_type the return type
5909 * @param argument_type the argument type
5911 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5913 function_parameter_t *parameter
5914 = obstack_alloc(type_obst, sizeof(parameter[0]));
5915 memset(parameter, 0, sizeof(parameter[0]));
5916 parameter->type = argument_type;
5918 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5919 type->function.return_type = return_type;
5920 type->function.parameters = parameter;
5922 type_t *result = typehash_insert(type);
5923 if (result != type) {
5930 static type_t *make_function_0_type(type_t *return_type)
5932 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5933 type->function.return_type = return_type;
5934 type->function.parameters = NULL;
5936 type_t *result = typehash_insert(type);
5937 if (result != type) {
5945 * Creates a function type for some function like builtins.
5947 * @param symbol the symbol describing the builtin
5949 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5951 switch(symbol->ID) {
5952 case T___builtin_alloca:
5953 return make_function_1_type(type_void_ptr, type_size_t);
5954 case T___builtin_huge_val:
5955 return make_function_0_type(type_double);
5956 case T___builtin_nan:
5957 return make_function_1_type(type_double, type_char_ptr);
5958 case T___builtin_nanf:
5959 return make_function_1_type(type_float, type_char_ptr);
5960 case T___builtin_nand:
5961 return make_function_1_type(type_long_double, type_char_ptr);
5962 case T___builtin_va_end:
5963 return make_function_1_type(type_void, type_valist);
5964 case T___builtin_expect:
5965 return make_function_2_type(type_long, type_long, type_long);
5967 internal_errorf(HERE, "not implemented builtin symbol found");
5972 * Performs automatic type cast as described in § 6.3.2.1.
5974 * @param orig_type the original type
5976 static type_t *automatic_type_conversion(type_t *orig_type)
5978 type_t *type = skip_typeref(orig_type);
5979 if (is_type_array(type)) {
5980 array_type_t *array_type = &type->array;
5981 type_t *element_type = array_type->element_type;
5982 unsigned qualifiers = array_type->base.qualifiers;
5984 return make_pointer_type(element_type, qualifiers);
5987 if (is_type_function(type)) {
5988 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5995 * reverts the automatic casts of array to pointer types and function
5996 * to function-pointer types as defined § 6.3.2.1
5998 type_t *revert_automatic_type_conversion(const expression_t *expression)
6000 switch (expression->kind) {
6001 case EXPR_REFERENCE: return expression->reference.declaration->type;
6004 return get_qualified_type(expression->select.compound_entry->type,
6005 expression->base.type->base.qualifiers);
6007 case EXPR_UNARY_DEREFERENCE: {
6008 const expression_t *const value = expression->unary.value;
6009 type_t *const type = skip_typeref(value->base.type);
6010 assert(is_type_pointer(type));
6011 return type->pointer.points_to;
6014 case EXPR_BUILTIN_SYMBOL:
6015 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6017 case EXPR_ARRAY_ACCESS: {
6018 const expression_t *array_ref = expression->array_access.array_ref;
6019 type_t *type_left = skip_typeref(array_ref->base.type);
6020 if (!is_type_valid(type_left))
6022 assert(is_type_pointer(type_left));
6023 return type_left->pointer.points_to;
6026 case EXPR_STRING_LITERAL: {
6027 size_t size = expression->string.value.size;
6028 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6031 case EXPR_WIDE_STRING_LITERAL: {
6032 size_t size = expression->wide_string.value.size;
6033 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6036 case EXPR_COMPOUND_LITERAL:
6037 return expression->compound_literal.type;
6042 return expression->base.type;
6045 static expression_t *parse_reference(void)
6047 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6049 reference_expression_t *ref = &expression->reference;
6050 symbol_t *const symbol = token.v.symbol;
6052 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6054 if (declaration == NULL) {
6055 if (look_ahead(1)->type == '(') {
6056 /* an implicitly declared function */
6058 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6059 } else if (warning.implicit_function_declaration) {
6060 warningf(HERE, "implicit declaration of function '%Y'",
6064 declaration = create_implicit_function(symbol, HERE);
6066 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6067 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6071 type_t *type = declaration->type;
6073 /* we always do the auto-type conversions; the & and sizeof parser contains
6074 * code to revert this! */
6075 type = automatic_type_conversion(type);
6077 ref->declaration = declaration;
6078 ref->base.type = type;
6080 /* this declaration is used */
6081 declaration->used = true;
6083 /* check for deprecated functions */
6084 if (warning.deprecated_declarations &&
6085 declaration->modifiers & DM_DEPRECATED) {
6086 char const *const prefix = is_type_function(declaration->type) ?
6087 "function" : "variable";
6089 if (declaration->deprecated_string != NULL) {
6090 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6091 prefix, declaration->symbol, &declaration->source_position,
6092 declaration->deprecated_string);
6094 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6095 declaration->symbol, &declaration->source_position);
6098 if (warning.init_self && declaration == current_init_decl) {
6099 current_init_decl = NULL;
6100 warningf(HERE, "variable '%#T' is initialized by itself",
6101 declaration->type, declaration->symbol);
6108 static bool semantic_cast(expression_t *cast)
6110 expression_t *expression = cast->unary.value;
6111 type_t *orig_dest_type = cast->base.type;
6112 type_t *orig_type_right = expression->base.type;
6113 type_t const *dst_type = skip_typeref(orig_dest_type);
6114 type_t const *src_type = skip_typeref(orig_type_right);
6115 source_position_t const *pos = &cast->base.source_position;
6117 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6118 if (dst_type == type_void)
6121 /* only integer and pointer can be casted to pointer */
6122 if (is_type_pointer(dst_type) &&
6123 !is_type_pointer(src_type) &&
6124 !is_type_integer(src_type) &&
6125 is_type_valid(src_type)) {
6126 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6130 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6131 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6135 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6136 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6140 if (warning.cast_qual &&
6141 is_type_pointer(src_type) &&
6142 is_type_pointer(dst_type)) {
6143 type_t *src = skip_typeref(src_type->pointer.points_to);
6144 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6145 unsigned missing_qualifiers =
6146 src->base.qualifiers & ~dst->base.qualifiers;
6147 if (missing_qualifiers != 0) {
6149 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6150 missing_qualifiers, orig_type_right);
6156 static expression_t *parse_compound_literal(type_t *type)
6158 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6160 parse_initializer_env_t env;
6162 env.declaration = NULL;
6163 env.must_be_constant = false;
6164 initializer_t *initializer = parse_initializer(&env);
6167 expression->compound_literal.initializer = initializer;
6168 expression->compound_literal.type = type;
6169 expression->base.type = automatic_type_conversion(type);
6175 * Parse a cast expression.
6177 static expression_t *parse_cast(void)
6179 source_position_t source_position = token.source_position;
6181 type_t *type = parse_typename();
6183 /* matching add_anchor_token() is at call site */
6184 rem_anchor_token(')');
6187 if (token.type == '{') {
6188 return parse_compound_literal(type);
6191 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6192 cast->base.source_position = source_position;
6194 expression_t *value = parse_sub_expression(20);
6195 cast->base.type = type;
6196 cast->unary.value = value;
6198 if (! semantic_cast(cast)) {
6199 /* TODO: record the error in the AST. else it is impossible to detect it */
6204 return create_invalid_expression();
6208 * Parse a statement expression.
6210 static expression_t *parse_statement_expression(void)
6212 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6214 statement_t *statement = parse_compound_statement(true);
6215 expression->statement.statement = statement;
6216 expression->base.source_position = statement->base.source_position;
6218 /* find last statement and use its type */
6219 type_t *type = type_void;
6220 const statement_t *stmt = statement->compound.statements;
6222 while (stmt->base.next != NULL)
6223 stmt = stmt->base.next;
6225 if (stmt->kind == STATEMENT_EXPRESSION) {
6226 type = stmt->expression.expression->base.type;
6229 warningf(&expression->base.source_position, "empty statement expression ({})");
6231 expression->base.type = type;
6237 return create_invalid_expression();
6241 * Parse a parenthesized expression.
6243 static expression_t *parse_parenthesized_expression(void)
6246 add_anchor_token(')');
6248 switch(token.type) {
6250 /* gcc extension: a statement expression */
6251 return parse_statement_expression();
6255 return parse_cast();
6257 if (is_typedef_symbol(token.v.symbol)) {
6258 return parse_cast();
6262 expression_t *result = parse_expression();
6263 rem_anchor_token(')');
6268 return create_invalid_expression();
6271 static expression_t *parse_function_keyword(void)
6276 if (current_function == NULL) {
6277 errorf(HERE, "'__func__' used outside of a function");
6280 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6281 expression->base.type = type_char_ptr;
6282 expression->funcname.kind = FUNCNAME_FUNCTION;
6287 static expression_t *parse_pretty_function_keyword(void)
6289 eat(T___PRETTY_FUNCTION__);
6291 if (current_function == NULL) {
6292 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6295 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6296 expression->base.type = type_char_ptr;
6297 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6302 static expression_t *parse_funcsig_keyword(void)
6306 if (current_function == NULL) {
6307 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6310 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6311 expression->base.type = type_char_ptr;
6312 expression->funcname.kind = FUNCNAME_FUNCSIG;
6317 static expression_t *parse_funcdname_keyword(void)
6319 eat(T___FUNCDNAME__);
6321 if (current_function == NULL) {
6322 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6325 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6326 expression->base.type = type_char_ptr;
6327 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6332 static designator_t *parse_designator(void)
6334 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6335 result->source_position = *HERE;
6337 if (token.type != T_IDENTIFIER) {
6338 parse_error_expected("while parsing member designator",
6339 T_IDENTIFIER, NULL);
6342 result->symbol = token.v.symbol;
6345 designator_t *last_designator = result;
6347 if (token.type == '.') {
6349 if (token.type != T_IDENTIFIER) {
6350 parse_error_expected("while parsing member designator",
6351 T_IDENTIFIER, NULL);
6354 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6355 designator->source_position = *HERE;
6356 designator->symbol = token.v.symbol;
6359 last_designator->next = designator;
6360 last_designator = designator;
6363 if (token.type == '[') {
6365 add_anchor_token(']');
6366 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6367 designator->source_position = *HERE;
6368 designator->array_index = parse_expression();
6369 rem_anchor_token(']');
6371 if (designator->array_index == NULL) {
6375 last_designator->next = designator;
6376 last_designator = designator;
6388 * Parse the __builtin_offsetof() expression.
6390 static expression_t *parse_offsetof(void)
6392 eat(T___builtin_offsetof);
6394 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6395 expression->base.type = type_size_t;
6398 add_anchor_token(',');
6399 type_t *type = parse_typename();
6400 rem_anchor_token(',');
6402 add_anchor_token(')');
6403 designator_t *designator = parse_designator();
6404 rem_anchor_token(')');
6407 expression->offsetofe.type = type;
6408 expression->offsetofe.designator = designator;
6411 memset(&path, 0, sizeof(path));
6412 path.top_type = type;
6413 path.path = NEW_ARR_F(type_path_entry_t, 0);
6415 descend_into_subtype(&path);
6417 if (!walk_designator(&path, designator, true)) {
6418 return create_invalid_expression();
6421 DEL_ARR_F(path.path);
6425 return create_invalid_expression();
6429 * Parses a _builtin_va_start() expression.
6431 static expression_t *parse_va_start(void)
6433 eat(T___builtin_va_start);
6435 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6438 add_anchor_token(',');
6439 expression->va_starte.ap = parse_assignment_expression();
6440 rem_anchor_token(',');
6442 expression_t *const expr = parse_assignment_expression();
6443 if (expr->kind == EXPR_REFERENCE) {
6444 declaration_t *const decl = expr->reference.declaration;
6446 return create_invalid_expression();
6447 if (decl->parent_scope == ¤t_function->scope &&
6448 decl->next == NULL) {
6449 expression->va_starte.parameter = decl;
6454 errorf(&expr->base.source_position,
6455 "second argument of 'va_start' must be last parameter of the current function");
6457 return create_invalid_expression();
6461 * Parses a _builtin_va_arg() expression.
6463 static expression_t *parse_va_arg(void)
6465 eat(T___builtin_va_arg);
6467 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6470 expression->va_arge.ap = parse_assignment_expression();
6472 expression->base.type = parse_typename();
6477 return create_invalid_expression();
6480 static expression_t *parse_builtin_symbol(void)
6482 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6484 symbol_t *symbol = token.v.symbol;
6486 expression->builtin_symbol.symbol = symbol;
6489 type_t *type = get_builtin_symbol_type(symbol);
6490 type = automatic_type_conversion(type);
6492 expression->base.type = type;
6497 * Parses a __builtin_constant() expression.
6499 static expression_t *parse_builtin_constant(void)
6501 eat(T___builtin_constant_p);
6503 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6506 add_anchor_token(')');
6507 expression->builtin_constant.value = parse_assignment_expression();
6508 rem_anchor_token(')');
6510 expression->base.type = type_int;
6514 return create_invalid_expression();
6518 * Parses a __builtin_prefetch() expression.
6520 static expression_t *parse_builtin_prefetch(void)
6522 eat(T___builtin_prefetch);
6524 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6527 add_anchor_token(')');
6528 expression->builtin_prefetch.adr = parse_assignment_expression();
6529 if (token.type == ',') {
6531 expression->builtin_prefetch.rw = parse_assignment_expression();
6533 if (token.type == ',') {
6535 expression->builtin_prefetch.locality = parse_assignment_expression();
6537 rem_anchor_token(')');
6539 expression->base.type = type_void;
6543 return create_invalid_expression();
6547 * Parses a __builtin_is_*() compare expression.
6549 static expression_t *parse_compare_builtin(void)
6551 expression_t *expression;
6553 switch(token.type) {
6554 case T___builtin_isgreater:
6555 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6557 case T___builtin_isgreaterequal:
6558 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6560 case T___builtin_isless:
6561 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6563 case T___builtin_islessequal:
6564 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6566 case T___builtin_islessgreater:
6567 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6569 case T___builtin_isunordered:
6570 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6573 internal_errorf(HERE, "invalid compare builtin found");
6576 expression->base.source_position = *HERE;
6580 expression->binary.left = parse_assignment_expression();
6582 expression->binary.right = parse_assignment_expression();
6585 type_t *const orig_type_left = expression->binary.left->base.type;
6586 type_t *const orig_type_right = expression->binary.right->base.type;
6588 type_t *const type_left = skip_typeref(orig_type_left);
6589 type_t *const type_right = skip_typeref(orig_type_right);
6590 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6591 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6592 type_error_incompatible("invalid operands in comparison",
6593 &expression->base.source_position, orig_type_left, orig_type_right);
6596 semantic_comparison(&expression->binary);
6601 return create_invalid_expression();
6606 * Parses a __builtin_expect() expression.
6608 static expression_t *parse_builtin_expect(void)
6610 eat(T___builtin_expect);
6612 expression_t *expression
6613 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6616 expression->binary.left = parse_assignment_expression();
6618 expression->binary.right = parse_constant_expression();
6621 expression->base.type = expression->binary.left->base.type;
6625 return create_invalid_expression();
6630 * Parses a MS assume() expression.
6632 static expression_t *parse_assume(void)
6636 expression_t *expression
6637 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6640 add_anchor_token(')');
6641 expression->unary.value = parse_assignment_expression();
6642 rem_anchor_token(')');
6645 expression->base.type = type_void;
6648 return create_invalid_expression();
6652 * Return the declaration for a given label symbol or create a new one.
6654 * @param symbol the symbol of the label
6656 static declaration_t *get_label(symbol_t *symbol)
6658 declaration_t *candidate;
6659 assert(current_function != NULL);
6661 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6662 /* if we found a local label, we already created the declaration */
6663 if (candidate != NULL) {
6664 assert(candidate->parent_scope == scope);
6668 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6669 /* if we found a label in the same function, then we already created the
6671 if (candidate != NULL
6672 && candidate->parent_scope == ¤t_function->scope) {
6676 /* otherwise we need to create a new one */
6677 declaration_t *const declaration = allocate_declaration_zero();
6678 declaration->namespc = NAMESPACE_LABEL;
6679 declaration->symbol = symbol;
6681 label_push(declaration);
6687 * Parses a GNU && label address expression.
6689 static expression_t *parse_label_address(void)
6691 source_position_t source_position = token.source_position;
6693 if (token.type != T_IDENTIFIER) {
6694 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6697 symbol_t *symbol = token.v.symbol;
6700 declaration_t *label = get_label(symbol);
6703 label->address_taken = true;
6705 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6706 expression->base.source_position = source_position;
6708 /* label address is threaten as a void pointer */
6709 expression->base.type = type_void_ptr;
6710 expression->label_address.declaration = label;
6713 return create_invalid_expression();
6717 * Parse a microsoft __noop expression.
6719 static expression_t *parse_noop_expression(void)
6721 source_position_t source_position = *HERE;
6724 if (token.type == '(') {
6725 /* parse arguments */
6727 add_anchor_token(')');
6728 add_anchor_token(',');
6730 if (token.type != ')') {
6732 (void)parse_assignment_expression();
6733 if (token.type != ',')
6739 rem_anchor_token(',');
6740 rem_anchor_token(')');
6743 /* the result is a (int)0 */
6744 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6745 cnst->base.source_position = source_position;
6746 cnst->base.type = type_int;
6747 cnst->conste.v.int_value = 0;
6748 cnst->conste.is_ms_noop = true;
6753 return create_invalid_expression();
6757 * Parses a primary expression.
6759 static expression_t *parse_primary_expression(void)
6761 switch (token.type) {
6762 case T_INTEGER: return parse_int_const();
6763 case T_CHARACTER_CONSTANT: return parse_character_constant();
6764 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6765 case T_FLOATINGPOINT: return parse_float_const();
6766 case T_STRING_LITERAL:
6767 case T_WIDE_STRING_LITERAL: return parse_string_const();
6768 case T_IDENTIFIER: return parse_reference();
6769 case T___FUNCTION__:
6770 case T___func__: return parse_function_keyword();
6771 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6772 case T___FUNCSIG__: return parse_funcsig_keyword();
6773 case T___FUNCDNAME__: return parse_funcdname_keyword();
6774 case T___builtin_offsetof: return parse_offsetof();
6775 case T___builtin_va_start: return parse_va_start();
6776 case T___builtin_va_arg: return parse_va_arg();
6777 case T___builtin_expect:
6778 case T___builtin_alloca:
6779 case T___builtin_nan:
6780 case T___builtin_nand:
6781 case T___builtin_nanf:
6782 case T___builtin_huge_val:
6783 case T___builtin_va_end: return parse_builtin_symbol();
6784 case T___builtin_isgreater:
6785 case T___builtin_isgreaterequal:
6786 case T___builtin_isless:
6787 case T___builtin_islessequal:
6788 case T___builtin_islessgreater:
6789 case T___builtin_isunordered: return parse_compare_builtin();
6790 case T___builtin_constant_p: return parse_builtin_constant();
6791 case T___builtin_prefetch: return parse_builtin_prefetch();
6792 case T__assume: return parse_assume();
6795 return parse_label_address();
6798 case '(': return parse_parenthesized_expression();
6799 case T___noop: return parse_noop_expression();
6802 errorf(HERE, "unexpected token %K, expected an expression", &token);
6803 return create_invalid_expression();
6807 * Check if the expression has the character type and issue a warning then.
6809 static void check_for_char_index_type(const expression_t *expression)
6811 type_t *const type = expression->base.type;
6812 const type_t *const base_type = skip_typeref(type);
6814 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6815 warning.char_subscripts) {
6816 warningf(&expression->base.source_position,
6817 "array subscript has type '%T'", type);
6821 static expression_t *parse_array_expression(unsigned precedence,
6827 add_anchor_token(']');
6829 expression_t *inside = parse_expression();
6831 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6833 array_access_expression_t *array_access = &expression->array_access;
6835 type_t *const orig_type_left = left->base.type;
6836 type_t *const orig_type_inside = inside->base.type;
6838 type_t *const type_left = skip_typeref(orig_type_left);
6839 type_t *const type_inside = skip_typeref(orig_type_inside);
6841 type_t *return_type;
6842 if (is_type_pointer(type_left)) {
6843 return_type = type_left->pointer.points_to;
6844 array_access->array_ref = left;
6845 array_access->index = inside;
6846 check_for_char_index_type(inside);
6847 } else if (is_type_pointer(type_inside)) {
6848 return_type = type_inside->pointer.points_to;
6849 array_access->array_ref = inside;
6850 array_access->index = left;
6851 array_access->flipped = true;
6852 check_for_char_index_type(left);
6854 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6856 "array access on object with non-pointer types '%T', '%T'",
6857 orig_type_left, orig_type_inside);
6859 return_type = type_error_type;
6860 array_access->array_ref = create_invalid_expression();
6863 rem_anchor_token(']');
6864 if (token.type != ']') {
6865 parse_error_expected("Problem while parsing array access", ']', NULL);
6870 return_type = automatic_type_conversion(return_type);
6871 expression->base.type = return_type;
6876 static expression_t *parse_typeprop(expression_kind_t const kind,
6877 source_position_t const pos,
6878 unsigned const precedence)
6880 expression_t *tp_expression = allocate_expression_zero(kind);
6881 tp_expression->base.type = type_size_t;
6882 tp_expression->base.source_position = pos;
6884 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6886 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6888 add_anchor_token(')');
6889 type_t* const orig_type = parse_typename();
6890 tp_expression->typeprop.type = orig_type;
6892 type_t const* const type = skip_typeref(orig_type);
6893 char const* const wrong_type =
6894 is_type_incomplete(type) ? "incomplete" :
6895 type->kind == TYPE_FUNCTION ? "function designator" :
6896 type->kind == TYPE_BITFIELD ? "bitfield" :
6898 if (wrong_type != NULL) {
6899 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6900 what, wrong_type, type);
6903 rem_anchor_token(')');
6906 expression_t *expression = parse_sub_expression(precedence);
6908 type_t* const orig_type = revert_automatic_type_conversion(expression);
6909 expression->base.type = orig_type;
6911 type_t const* const type = skip_typeref(orig_type);
6912 char const* const wrong_type =
6913 is_type_incomplete(type) ? "incomplete" :
6914 type->kind == TYPE_FUNCTION ? "function designator" :
6915 type->kind == TYPE_BITFIELD ? "bitfield" :
6917 if (wrong_type != NULL) {
6918 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6921 tp_expression->typeprop.type = expression->base.type;
6922 tp_expression->typeprop.tp_expression = expression;
6925 return tp_expression;
6927 return create_invalid_expression();
6930 static expression_t *parse_sizeof(unsigned precedence)
6932 source_position_t pos = *HERE;
6934 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6937 static expression_t *parse_alignof(unsigned precedence)
6939 source_position_t pos = *HERE;
6941 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6944 static expression_t *parse_select_expression(unsigned precedence,
6945 expression_t *compound)
6948 assert(token.type == '.' || token.type == T_MINUSGREATER);
6950 bool is_pointer = (token.type == T_MINUSGREATER);
6953 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6954 select->select.compound = compound;
6956 if (token.type != T_IDENTIFIER) {
6957 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6960 symbol_t *symbol = token.v.symbol;
6963 type_t *const orig_type = compound->base.type;
6964 type_t *const type = skip_typeref(orig_type);
6967 bool saw_error = false;
6968 if (is_type_pointer(type)) {
6971 "request for member '%Y' in something not a struct or union, but '%T'",
6975 type_left = skip_typeref(type->pointer.points_to);
6977 if (is_pointer && is_type_valid(type)) {
6978 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6984 declaration_t *entry;
6985 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
6986 type_left->kind == TYPE_COMPOUND_UNION) {
6987 declaration_t *const declaration = type_left->compound.declaration;
6989 if (!declaration->init.complete) {
6990 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6992 goto create_error_entry;
6995 entry = find_compound_entry(declaration, symbol);
6996 if (entry == NULL) {
6997 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6998 goto create_error_entry;
7001 if (is_type_valid(type_left) && !saw_error) {
7003 "request for member '%Y' in something not a struct or union, but '%T'",
7007 entry = allocate_declaration_zero();
7008 entry->symbol = symbol;
7011 select->select.compound_entry = entry;
7013 type_t *const res_type =
7014 get_qualified_type(entry->type, type_left->base.qualifiers);
7016 /* we always do the auto-type conversions; the & and sizeof parser contains
7017 * code to revert this! */
7018 select->base.type = automatic_type_conversion(res_type);
7020 type_t *skipped = skip_typeref(res_type);
7021 if (skipped->kind == TYPE_BITFIELD) {
7022 select->base.type = skipped->bitfield.base_type;
7028 static void check_call_argument(const function_parameter_t *parameter,
7029 call_argument_t *argument, unsigned pos)
7031 type_t *expected_type = parameter->type;
7032 type_t *expected_type_skip = skip_typeref(expected_type);
7033 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7034 expression_t *arg_expr = argument->expression;
7035 type_t *arg_type = skip_typeref(arg_expr->base.type);
7037 /* handle transparent union gnu extension */
7038 if (is_type_union(expected_type_skip)
7039 && (expected_type_skip->base.modifiers
7040 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7041 declaration_t *union_decl = expected_type_skip->compound.declaration;
7043 declaration_t *declaration = union_decl->scope.declarations;
7044 type_t *best_type = NULL;
7045 for ( ; declaration != NULL; declaration = declaration->next) {
7046 type_t *decl_type = declaration->type;
7047 error = semantic_assign(decl_type, arg_expr);
7048 if (error == ASSIGN_ERROR_INCOMPATIBLE
7049 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7052 if (error == ASSIGN_SUCCESS) {
7053 best_type = decl_type;
7054 } else if (best_type == NULL) {
7055 best_type = decl_type;
7059 if (best_type != NULL) {
7060 expected_type = best_type;
7064 error = semantic_assign(expected_type, arg_expr);
7065 argument->expression = create_implicit_cast(argument->expression,
7068 if (error != ASSIGN_SUCCESS) {
7069 /* report exact scope in error messages (like "in argument 3") */
7071 snprintf(buf, sizeof(buf), "call argument %u", pos);
7072 report_assign_error(error, expected_type, arg_expr, buf,
7073 &arg_expr->base.source_position);
7074 } else if (warning.traditional | warning.conversion) {
7076 /* passing as integer instead of float or complex */
7077 (is_type_integer(expected_type) &&
7078 (is_type_float(arg_type) || is_type_complex(arg_type))) ||
7079 /* passing as complex instead of integer or float */
7080 (is_type_complex(expected_type) &&
7081 (is_type_integer(arg_type) || is_type_float(arg_type))) ||
7082 /* passing as float instead of integer or complex */
7083 (is_type_float(expected_type) &&
7084 (is_type_integer(arg_type) || is_type_complex(arg_type))) ||
7085 /* passing as float instead of double */
7086 (is_type_float(expected_type) && expected_type != type_double &&
7087 is_type_float(arg_type))) {
7088 warningf(&arg_expr->base.source_position,
7089 "passing call argument %u as '%T' rather than '%T' due to prototype",
7090 pos, expected_type, arg_type);
7092 if (is_type_integer(expected_type) && is_type_integer(arg_type)) {
7093 /* TODO check for size HERE */
7099 * Parse a call expression, ie. expression '( ... )'.
7101 * @param expression the function address
7103 static expression_t *parse_call_expression(unsigned precedence,
7104 expression_t *expression)
7107 expression_t *result = allocate_expression_zero(EXPR_CALL);
7108 result->base.source_position = expression->base.source_position;
7110 call_expression_t *call = &result->call;
7111 call->function = expression;
7113 type_t *const orig_type = expression->base.type;
7114 type_t *const type = skip_typeref(orig_type);
7116 function_type_t *function_type = NULL;
7117 if (is_type_pointer(type)) {
7118 type_t *const to_type = skip_typeref(type->pointer.points_to);
7120 if (is_type_function(to_type)) {
7121 function_type = &to_type->function;
7122 call->base.type = function_type->return_type;
7126 if (function_type == NULL && is_type_valid(type)) {
7127 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7130 /* parse arguments */
7132 add_anchor_token(')');
7133 add_anchor_token(',');
7135 if (token.type != ')') {
7136 call_argument_t *last_argument = NULL;
7139 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7141 argument->expression = parse_assignment_expression();
7142 if (last_argument == NULL) {
7143 call->arguments = argument;
7145 last_argument->next = argument;
7147 last_argument = argument;
7149 if (token.type != ',')
7154 rem_anchor_token(',');
7155 rem_anchor_token(')');
7158 if (function_type == NULL)
7161 function_parameter_t *parameter = function_type->parameters;
7162 call_argument_t *argument = call->arguments;
7163 if (!function_type->unspecified_parameters) {
7164 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7165 parameter = parameter->next, argument = argument->next) {
7166 check_call_argument(parameter, argument, ++pos);
7169 if (parameter != NULL) {
7170 errorf(HERE, "too few arguments to function '%E'", expression);
7171 } else if (argument != NULL && !function_type->variadic) {
7172 errorf(HERE, "too many arguments to function '%E'", expression);
7176 /* do default promotion */
7177 for( ; argument != NULL; argument = argument->next) {
7178 type_t *type = argument->expression->base.type;
7180 type = get_default_promoted_type(type);
7182 argument->expression
7183 = create_implicit_cast(argument->expression, type);
7186 check_format(&result->call);
7188 if (warning.aggregate_return &&
7189 is_type_compound(skip_typeref(function_type->return_type))) {
7190 warningf(&result->base.source_position,
7191 "function call has aggregate value");
7196 return create_invalid_expression();
7199 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7201 static bool same_compound_type(const type_t *type1, const type_t *type2)
7204 is_type_compound(type1) &&
7205 type1->kind == type2->kind &&
7206 type1->compound.declaration == type2->compound.declaration;
7210 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7212 * @param expression the conditional expression
7214 static expression_t *parse_conditional_expression(unsigned precedence,
7215 expression_t *expression)
7217 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7219 conditional_expression_t *conditional = &result->conditional;
7220 conditional->base.source_position = *HERE;
7221 conditional->condition = expression;
7224 add_anchor_token(':');
7227 type_t *const condition_type_orig = expression->base.type;
7228 type_t *const condition_type = skip_typeref(condition_type_orig);
7229 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7230 type_error("expected a scalar type in conditional condition",
7231 &expression->base.source_position, condition_type_orig);
7234 expression_t *true_expression = expression;
7235 bool gnu_cond = false;
7236 if ((c_mode & _GNUC) && token.type == ':') {
7239 true_expression = parse_expression();
7240 rem_anchor_token(':');
7242 expression_t *false_expression = parse_sub_expression(precedence);
7244 type_t *const orig_true_type = true_expression->base.type;
7245 type_t *const orig_false_type = false_expression->base.type;
7246 type_t *const true_type = skip_typeref(orig_true_type);
7247 type_t *const false_type = skip_typeref(orig_false_type);
7250 type_t *result_type;
7251 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7252 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7253 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7254 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7255 warningf(&conditional->base.source_position,
7256 "ISO C forbids conditional expression with only one void side");
7258 result_type = type_void;
7259 } else if (is_type_arithmetic(true_type)
7260 && is_type_arithmetic(false_type)) {
7261 result_type = semantic_arithmetic(true_type, false_type);
7263 true_expression = create_implicit_cast(true_expression, result_type);
7264 false_expression = create_implicit_cast(false_expression, result_type);
7266 conditional->true_expression = true_expression;
7267 conditional->false_expression = false_expression;
7268 conditional->base.type = result_type;
7269 } else if (same_compound_type(true_type, false_type)) {
7270 /* just take 1 of the 2 types */
7271 result_type = true_type;
7272 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7273 type_t *pointer_type;
7275 expression_t *other_expression;
7276 if (is_type_pointer(true_type) &&
7277 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7278 pointer_type = true_type;
7279 other_type = false_type;
7280 other_expression = false_expression;
7282 pointer_type = false_type;
7283 other_type = true_type;
7284 other_expression = true_expression;
7287 if (is_null_pointer_constant(other_expression)) {
7288 result_type = pointer_type;
7289 } else if (is_type_pointer(other_type)) {
7290 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7291 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7294 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7295 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7297 } else if (types_compatible(get_unqualified_type(to1),
7298 get_unqualified_type(to2))) {
7301 warningf(&conditional->base.source_position,
7302 "pointer types '%T' and '%T' in conditional expression are incompatible",
7303 true_type, false_type);
7307 type_t *const type =
7308 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7309 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7310 } else if (is_type_integer(other_type)) {
7311 warningf(&conditional->base.source_position,
7312 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7313 result_type = pointer_type;
7315 type_error_incompatible("while parsing conditional",
7316 &expression->base.source_position, true_type, false_type);
7317 result_type = type_error_type;
7320 /* TODO: one pointer to void*, other some pointer */
7322 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7323 type_error_incompatible("while parsing conditional",
7324 &conditional->base.source_position, true_type,
7327 result_type = type_error_type;
7330 conditional->true_expression
7331 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7332 conditional->false_expression
7333 = create_implicit_cast(false_expression, result_type);
7334 conditional->base.type = result_type;
7337 return create_invalid_expression();
7341 * Parse an extension expression.
7343 static expression_t *parse_extension(unsigned precedence)
7345 eat(T___extension__);
7347 /* TODO enable extensions */
7348 expression_t *expression = parse_sub_expression(precedence);
7349 /* TODO disable extensions */
7354 * Parse a __builtin_classify_type() expression.
7356 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7358 eat(T___builtin_classify_type);
7360 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7361 result->base.type = type_int;
7364 add_anchor_token(')');
7365 expression_t *expression = parse_sub_expression(precedence);
7366 rem_anchor_token(')');
7368 result->classify_type.type_expression = expression;
7372 return create_invalid_expression();
7375 static bool check_pointer_arithmetic(const source_position_t *source_position,
7376 type_t *pointer_type,
7377 type_t *orig_pointer_type)
7379 type_t *points_to = pointer_type->pointer.points_to;
7380 points_to = skip_typeref(points_to);
7382 if (is_type_incomplete(points_to)) {
7383 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7384 errorf(source_position,
7385 "arithmetic with pointer to incomplete type '%T' not allowed",
7388 } else if (warning.pointer_arith) {
7389 warningf(source_position,
7390 "pointer of type '%T' used in arithmetic",
7393 } else if (is_type_function(points_to)) {
7394 if (!(c_mode && _GNUC)) {
7395 errorf(source_position,
7396 "arithmetic with pointer to function type '%T' not allowed",
7399 } else if (warning.pointer_arith) {
7400 warningf(source_position,
7401 "pointer to a function '%T' used in arithmetic",
7408 static bool is_lvalue(const expression_t *expression)
7410 switch (expression->kind) {
7411 case EXPR_REFERENCE:
7412 case EXPR_ARRAY_ACCESS:
7414 case EXPR_UNARY_DEREFERENCE:
7422 static void semantic_incdec(unary_expression_t *expression)
7424 type_t *const orig_type = expression->value->base.type;
7425 type_t *const type = skip_typeref(orig_type);
7426 if (is_type_pointer(type)) {
7427 if (!check_pointer_arithmetic(&expression->base.source_position,
7431 } else if (!is_type_real(type) && is_type_valid(type)) {
7432 /* TODO: improve error message */
7433 errorf(&expression->base.source_position,
7434 "operation needs an arithmetic or pointer type");
7437 if (!is_lvalue(expression->value)) {
7438 /* TODO: improve error message */
7439 errorf(&expression->base.source_position, "lvalue required as operand");
7441 expression->base.type = orig_type;
7444 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7446 type_t *const orig_type = expression->value->base.type;
7447 type_t *const type = skip_typeref(orig_type);
7448 if (!is_type_arithmetic(type)) {
7449 if (is_type_valid(type)) {
7450 /* TODO: improve error message */
7451 errorf(&expression->base.source_position,
7452 "operation needs an arithmetic type");
7457 expression->base.type = orig_type;
7460 static void semantic_unexpr_plus(unary_expression_t *expression)
7462 semantic_unexpr_arithmetic(expression);
7463 if (warning.traditional)
7464 warningf(&expression->base.source_position,
7465 "traditional C rejects the unary plus operator");
7468 static void semantic_not(unary_expression_t *expression)
7470 type_t *const orig_type = expression->value->base.type;
7471 type_t *const type = skip_typeref(orig_type);
7472 if (!is_type_scalar(type) && is_type_valid(type)) {
7473 errorf(&expression->base.source_position,
7474 "operand of ! must be of scalar type");
7477 expression->base.type = type_int;
7480 static void semantic_unexpr_integer(unary_expression_t *expression)
7482 type_t *const orig_type = expression->value->base.type;
7483 type_t *const type = skip_typeref(orig_type);
7484 if (!is_type_integer(type)) {
7485 if (is_type_valid(type)) {
7486 errorf(&expression->base.source_position,
7487 "operand of ~ must be of integer type");
7492 expression->base.type = orig_type;
7495 static void semantic_dereference(unary_expression_t *expression)
7497 type_t *const orig_type = expression->value->base.type;
7498 type_t *const type = skip_typeref(orig_type);
7499 if (!is_type_pointer(type)) {
7500 if (is_type_valid(type)) {
7501 errorf(&expression->base.source_position,
7502 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7507 type_t *result_type = type->pointer.points_to;
7508 result_type = automatic_type_conversion(result_type);
7509 expression->base.type = result_type;
7513 * Record that an address is taken (expression represents an lvalue).
7515 * @param expression the expression
7516 * @param may_be_register if true, the expression might be an register
7518 static void set_address_taken(expression_t *expression, bool may_be_register)
7520 if (expression->kind != EXPR_REFERENCE)
7523 declaration_t *const declaration = expression->reference.declaration;
7524 /* happens for parse errors */
7525 if (declaration == NULL)
7528 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7529 errorf(&expression->base.source_position,
7530 "address of register variable '%Y' requested",
7531 declaration->symbol);
7533 declaration->address_taken = 1;
7538 * Check the semantic of the address taken expression.
7540 static void semantic_take_addr(unary_expression_t *expression)
7542 expression_t *value = expression->value;
7543 value->base.type = revert_automatic_type_conversion(value);
7545 type_t *orig_type = value->base.type;
7546 if (!is_type_valid(orig_type))
7549 set_address_taken(value, false);
7551 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7554 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7555 static expression_t *parse_##unexpression_type(unsigned precedence) \
7557 expression_t *unary_expression \
7558 = allocate_expression_zero(unexpression_type); \
7559 unary_expression->base.source_position = *HERE; \
7561 unary_expression->unary.value = parse_sub_expression(precedence); \
7563 sfunc(&unary_expression->unary); \
7565 return unary_expression; \
7568 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7569 semantic_unexpr_arithmetic)
7570 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7571 semantic_unexpr_plus)
7572 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7574 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7575 semantic_dereference)
7576 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7578 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7579 semantic_unexpr_integer)
7580 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7582 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7585 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7587 static expression_t *parse_##unexpression_type(unsigned precedence, \
7588 expression_t *left) \
7590 (void) precedence; \
7592 expression_t *unary_expression \
7593 = allocate_expression_zero(unexpression_type); \
7594 unary_expression->base.source_position = *HERE; \
7596 unary_expression->unary.value = left; \
7598 sfunc(&unary_expression->unary); \
7600 return unary_expression; \
7603 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7604 EXPR_UNARY_POSTFIX_INCREMENT,
7606 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7607 EXPR_UNARY_POSTFIX_DECREMENT,
7610 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7612 /* TODO: handle complex + imaginary types */
7614 /* § 6.3.1.8 Usual arithmetic conversions */
7615 if (type_left == type_long_double || type_right == type_long_double) {
7616 return type_long_double;
7617 } else if (type_left == type_double || type_right == type_double) {
7619 } else if (type_left == type_float || type_right == type_float) {
7623 type_left = promote_integer(type_left);
7624 type_right = promote_integer(type_right);
7626 if (type_left == type_right)
7629 bool const signed_left = is_type_signed(type_left);
7630 bool const signed_right = is_type_signed(type_right);
7631 int const rank_left = get_rank(type_left);
7632 int const rank_right = get_rank(type_right);
7634 if (signed_left == signed_right)
7635 return rank_left >= rank_right ? type_left : type_right;
7644 u_rank = rank_right;
7645 u_type = type_right;
7647 s_rank = rank_right;
7648 s_type = type_right;
7653 if (u_rank >= s_rank)
7656 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7658 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7659 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7663 case ATOMIC_TYPE_INT: return type_unsigned_int;
7664 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7665 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7667 default: panic("invalid atomic type");
7672 * Check the semantic restrictions for a binary expression.
7674 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7676 expression_t *const left = expression->left;
7677 expression_t *const right = expression->right;
7678 type_t *const orig_type_left = left->base.type;
7679 type_t *const orig_type_right = right->base.type;
7680 type_t *const type_left = skip_typeref(orig_type_left);
7681 type_t *const type_right = skip_typeref(orig_type_right);
7683 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7684 /* TODO: improve error message */
7685 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7686 errorf(&expression->base.source_position,
7687 "operation needs arithmetic types");
7692 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7693 expression->left = create_implicit_cast(left, arithmetic_type);
7694 expression->right = create_implicit_cast(right, arithmetic_type);
7695 expression->base.type = arithmetic_type;
7698 static void warn_div_by_zero(binary_expression_t const *const expression)
7700 if (warning.div_by_zero &&
7701 is_type_integer(expression->base.type) &&
7702 is_constant_expression(expression->right) &&
7703 fold_constant(expression->right) == 0) {
7704 warningf(&expression->base.source_position, "division by zero");
7709 * Check the semantic restrictions for a div/mod expression.
7711 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7712 semantic_binexpr_arithmetic(expression);
7713 warn_div_by_zero(expression);
7716 static void semantic_shift_op(binary_expression_t *expression)
7718 expression_t *const left = expression->left;
7719 expression_t *const right = expression->right;
7720 type_t *const orig_type_left = left->base.type;
7721 type_t *const orig_type_right = right->base.type;
7722 type_t * type_left = skip_typeref(orig_type_left);
7723 type_t * type_right = skip_typeref(orig_type_right);
7725 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7726 /* TODO: improve error message */
7727 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7728 errorf(&expression->base.source_position,
7729 "operands of shift operation must have integer types");
7734 type_left = promote_integer(type_left);
7735 type_right = promote_integer(type_right);
7737 expression->left = create_implicit_cast(left, type_left);
7738 expression->right = create_implicit_cast(right, type_right);
7739 expression->base.type = type_left;
7742 static void semantic_add(binary_expression_t *expression)
7744 expression_t *const left = expression->left;
7745 expression_t *const right = expression->right;
7746 type_t *const orig_type_left = left->base.type;
7747 type_t *const orig_type_right = right->base.type;
7748 type_t *const type_left = skip_typeref(orig_type_left);
7749 type_t *const type_right = skip_typeref(orig_type_right);
7752 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7753 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7754 expression->left = create_implicit_cast(left, arithmetic_type);
7755 expression->right = create_implicit_cast(right, arithmetic_type);
7756 expression->base.type = arithmetic_type;
7758 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7759 check_pointer_arithmetic(&expression->base.source_position,
7760 type_left, orig_type_left);
7761 expression->base.type = type_left;
7762 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7763 check_pointer_arithmetic(&expression->base.source_position,
7764 type_right, orig_type_right);
7765 expression->base.type = type_right;
7766 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7767 errorf(&expression->base.source_position,
7768 "invalid operands to binary + ('%T', '%T')",
7769 orig_type_left, orig_type_right);
7773 static void semantic_sub(binary_expression_t *expression)
7775 expression_t *const left = expression->left;
7776 expression_t *const right = expression->right;
7777 type_t *const orig_type_left = left->base.type;
7778 type_t *const orig_type_right = right->base.type;
7779 type_t *const type_left = skip_typeref(orig_type_left);
7780 type_t *const type_right = skip_typeref(orig_type_right);
7781 source_position_t const *const pos = &expression->base.source_position;
7784 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7785 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7786 expression->left = create_implicit_cast(left, arithmetic_type);
7787 expression->right = create_implicit_cast(right, arithmetic_type);
7788 expression->base.type = arithmetic_type;
7790 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7791 check_pointer_arithmetic(&expression->base.source_position,
7792 type_left, orig_type_left);
7793 expression->base.type = type_left;
7794 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7795 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7796 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7797 if (!types_compatible(unqual_left, unqual_right)) {
7799 "subtracting pointers to incompatible types '%T' and '%T'",
7800 orig_type_left, orig_type_right);
7801 } else if (!is_type_object(unqual_left)) {
7802 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7803 warningf(pos, "subtracting pointers to void");
7805 errorf(pos, "subtracting pointers to non-object types '%T'",
7809 expression->base.type = type_ptrdiff_t;
7810 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7811 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7812 orig_type_left, orig_type_right);
7817 * Check the semantics of comparison expressions.
7819 * @param expression The expression to check.
7821 static void semantic_comparison(binary_expression_t *expression)
7823 expression_t *left = expression->left;
7824 expression_t *right = expression->right;
7825 type_t *orig_type_left = left->base.type;
7826 type_t *orig_type_right = right->base.type;
7828 type_t *type_left = skip_typeref(orig_type_left);
7829 type_t *type_right = skip_typeref(orig_type_right);
7831 /* TODO non-arithmetic types */
7832 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7833 /* test for signed vs unsigned compares */
7834 if (warning.sign_compare &&
7835 (expression->base.kind != EXPR_BINARY_EQUAL &&
7836 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7837 (is_type_signed(type_left) != is_type_signed(type_right))) {
7839 /* check if 1 of the operands is a constant, in this case we just
7840 * check wether we can safely represent the resulting constant in
7841 * the type of the other operand. */
7842 expression_t *const_expr = NULL;
7843 expression_t *other_expr = NULL;
7845 if (is_constant_expression(left)) {
7848 } else if (is_constant_expression(right)) {
7853 if (const_expr != NULL) {
7854 type_t *other_type = skip_typeref(other_expr->base.type);
7855 long val = fold_constant(const_expr);
7856 /* TODO: check if val can be represented by other_type */
7860 warningf(&expression->base.source_position,
7861 "comparison between signed and unsigned");
7863 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7864 expression->left = create_implicit_cast(left, arithmetic_type);
7865 expression->right = create_implicit_cast(right, arithmetic_type);
7866 expression->base.type = arithmetic_type;
7867 if (warning.float_equal &&
7868 (expression->base.kind == EXPR_BINARY_EQUAL ||
7869 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7870 is_type_float(arithmetic_type)) {
7871 warningf(&expression->base.source_position,
7872 "comparing floating point with == or != is unsafe");
7874 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7875 /* TODO check compatibility */
7876 } else if (is_type_pointer(type_left)) {
7877 expression->right = create_implicit_cast(right, type_left);
7878 } else if (is_type_pointer(type_right)) {
7879 expression->left = create_implicit_cast(left, type_right);
7880 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7881 type_error_incompatible("invalid operands in comparison",
7882 &expression->base.source_position,
7883 type_left, type_right);
7885 expression->base.type = type_int;
7889 * Checks if a compound type has constant fields.
7891 static bool has_const_fields(const compound_type_t *type)
7893 const scope_t *scope = &type->declaration->scope;
7894 const declaration_t *declaration = scope->declarations;
7896 for (; declaration != NULL; declaration = declaration->next) {
7897 if (declaration->namespc != NAMESPACE_NORMAL)
7900 const type_t *decl_type = skip_typeref(declaration->type);
7901 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7908 static bool is_valid_assignment_lhs(expression_t const* const left)
7910 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7911 type_t *const type_left = skip_typeref(orig_type_left);
7913 if (!is_lvalue(left)) {
7914 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7919 if (is_type_array(type_left)) {
7920 errorf(HERE, "cannot assign to arrays ('%E')", left);
7923 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7924 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7928 if (is_type_incomplete(type_left)) {
7929 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7930 left, orig_type_left);
7933 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7934 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7935 left, orig_type_left);
7942 static void semantic_arithmetic_assign(binary_expression_t *expression)
7944 expression_t *left = expression->left;
7945 expression_t *right = expression->right;
7946 type_t *orig_type_left = left->base.type;
7947 type_t *orig_type_right = right->base.type;
7949 if (!is_valid_assignment_lhs(left))
7952 type_t *type_left = skip_typeref(orig_type_left);
7953 type_t *type_right = skip_typeref(orig_type_right);
7955 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7956 /* TODO: improve error message */
7957 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7958 errorf(&expression->base.source_position,
7959 "operation needs arithmetic types");
7964 /* combined instructions are tricky. We can't create an implicit cast on
7965 * the left side, because we need the uncasted form for the store.
7966 * The ast2firm pass has to know that left_type must be right_type
7967 * for the arithmetic operation and create a cast by itself */
7968 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7969 expression->right = create_implicit_cast(right, arithmetic_type);
7970 expression->base.type = type_left;
7973 static void semantic_divmod_assign(binary_expression_t *expression)
7975 semantic_arithmetic_assign(expression);
7976 warn_div_by_zero(expression);
7979 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7981 expression_t *const left = expression->left;
7982 expression_t *const right = expression->right;
7983 type_t *const orig_type_left = left->base.type;
7984 type_t *const orig_type_right = right->base.type;
7985 type_t *const type_left = skip_typeref(orig_type_left);
7986 type_t *const type_right = skip_typeref(orig_type_right);
7988 if (!is_valid_assignment_lhs(left))
7991 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7992 /* combined instructions are tricky. We can't create an implicit cast on
7993 * the left side, because we need the uncasted form for the store.
7994 * The ast2firm pass has to know that left_type must be right_type
7995 * for the arithmetic operation and create a cast by itself */
7996 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7997 expression->right = create_implicit_cast(right, arithmetic_type);
7998 expression->base.type = type_left;
7999 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8000 check_pointer_arithmetic(&expression->base.source_position,
8001 type_left, orig_type_left);
8002 expression->base.type = type_left;
8003 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8004 errorf(&expression->base.source_position,
8005 "incompatible types '%T' and '%T' in assignment",
8006 orig_type_left, orig_type_right);
8011 * Check the semantic restrictions of a logical expression.
8013 static void semantic_logical_op(binary_expression_t *expression)
8015 expression_t *const left = expression->left;
8016 expression_t *const right = expression->right;
8017 type_t *const orig_type_left = left->base.type;
8018 type_t *const orig_type_right = right->base.type;
8019 type_t *const type_left = skip_typeref(orig_type_left);
8020 type_t *const type_right = skip_typeref(orig_type_right);
8022 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8023 /* TODO: improve error message */
8024 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8025 errorf(&expression->base.source_position,
8026 "operation needs scalar types");
8031 expression->base.type = type_int;
8035 * Check the semantic restrictions of a binary assign expression.
8037 static void semantic_binexpr_assign(binary_expression_t *expression)
8039 expression_t *left = expression->left;
8040 type_t *orig_type_left = left->base.type;
8042 if (!is_valid_assignment_lhs(left))
8045 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8046 report_assign_error(error, orig_type_left, expression->right,
8047 "assignment", &left->base.source_position);
8048 expression->right = create_implicit_cast(expression->right, orig_type_left);
8049 expression->base.type = orig_type_left;
8053 * Determine if the outermost operation (or parts thereof) of the given
8054 * expression has no effect in order to generate a warning about this fact.
8055 * Therefore in some cases this only examines some of the operands of the
8056 * expression (see comments in the function and examples below).
8058 * f() + 23; // warning, because + has no effect
8059 * x || f(); // no warning, because x controls execution of f()
8060 * x ? y : f(); // warning, because y has no effect
8061 * (void)x; // no warning to be able to suppress the warning
8062 * This function can NOT be used for an "expression has definitely no effect"-
8064 static bool expression_has_effect(const expression_t *const expr)
8066 switch (expr->kind) {
8067 case EXPR_UNKNOWN: break;
8068 case EXPR_INVALID: return true; /* do NOT warn */
8069 case EXPR_REFERENCE: return false;
8070 /* suppress the warning for microsoft __noop operations */
8071 case EXPR_CONST: return expr->conste.is_ms_noop;
8072 case EXPR_CHARACTER_CONSTANT: return false;
8073 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8074 case EXPR_STRING_LITERAL: return false;
8075 case EXPR_WIDE_STRING_LITERAL: return false;
8076 case EXPR_LABEL_ADDRESS: return false;
8079 const call_expression_t *const call = &expr->call;
8080 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8083 switch (call->function->builtin_symbol.symbol->ID) {
8084 case T___builtin_va_end: return true;
8085 default: return false;
8089 /* Generate the warning if either the left or right hand side of a
8090 * conditional expression has no effect */
8091 case EXPR_CONDITIONAL: {
8092 const conditional_expression_t *const cond = &expr->conditional;
8094 expression_has_effect(cond->true_expression) &&
8095 expression_has_effect(cond->false_expression);
8098 case EXPR_SELECT: return false;
8099 case EXPR_ARRAY_ACCESS: return false;
8100 case EXPR_SIZEOF: return false;
8101 case EXPR_CLASSIFY_TYPE: return false;
8102 case EXPR_ALIGNOF: return false;
8104 case EXPR_FUNCNAME: return false;
8105 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8106 case EXPR_BUILTIN_CONSTANT_P: return false;
8107 case EXPR_BUILTIN_PREFETCH: return true;
8108 case EXPR_OFFSETOF: return false;
8109 case EXPR_VA_START: return true;
8110 case EXPR_VA_ARG: return true;
8111 case EXPR_STATEMENT: return true; // TODO
8112 case EXPR_COMPOUND_LITERAL: return false;
8114 case EXPR_UNARY_NEGATE: return false;
8115 case EXPR_UNARY_PLUS: return false;
8116 case EXPR_UNARY_BITWISE_NEGATE: return false;
8117 case EXPR_UNARY_NOT: return false;
8118 case EXPR_UNARY_DEREFERENCE: return false;
8119 case EXPR_UNARY_TAKE_ADDRESS: return false;
8120 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8121 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8122 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8123 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8125 /* Treat void casts as if they have an effect in order to being able to
8126 * suppress the warning */
8127 case EXPR_UNARY_CAST: {
8128 type_t *const type = skip_typeref(expr->base.type);
8129 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8132 case EXPR_UNARY_CAST_IMPLICIT: return true;
8133 case EXPR_UNARY_ASSUME: return true;
8135 case EXPR_BINARY_ADD: return false;
8136 case EXPR_BINARY_SUB: return false;
8137 case EXPR_BINARY_MUL: return false;
8138 case EXPR_BINARY_DIV: return false;
8139 case EXPR_BINARY_MOD: return false;
8140 case EXPR_BINARY_EQUAL: return false;
8141 case EXPR_BINARY_NOTEQUAL: return false;
8142 case EXPR_BINARY_LESS: return false;
8143 case EXPR_BINARY_LESSEQUAL: return false;
8144 case EXPR_BINARY_GREATER: return false;
8145 case EXPR_BINARY_GREATEREQUAL: return false;
8146 case EXPR_BINARY_BITWISE_AND: return false;
8147 case EXPR_BINARY_BITWISE_OR: return false;
8148 case EXPR_BINARY_BITWISE_XOR: return false;
8149 case EXPR_BINARY_SHIFTLEFT: return false;
8150 case EXPR_BINARY_SHIFTRIGHT: return false;
8151 case EXPR_BINARY_ASSIGN: return true;
8152 case EXPR_BINARY_MUL_ASSIGN: return true;
8153 case EXPR_BINARY_DIV_ASSIGN: return true;
8154 case EXPR_BINARY_MOD_ASSIGN: return true;
8155 case EXPR_BINARY_ADD_ASSIGN: return true;
8156 case EXPR_BINARY_SUB_ASSIGN: return true;
8157 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8158 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8159 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8160 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8161 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8163 /* Only examine the right hand side of && and ||, because the left hand
8164 * side already has the effect of controlling the execution of the right
8166 case EXPR_BINARY_LOGICAL_AND:
8167 case EXPR_BINARY_LOGICAL_OR:
8168 /* Only examine the right hand side of a comma expression, because the left
8169 * hand side has a separate warning */
8170 case EXPR_BINARY_COMMA:
8171 return expression_has_effect(expr->binary.right);
8173 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8174 case EXPR_BINARY_ISGREATER: return false;
8175 case EXPR_BINARY_ISGREATEREQUAL: return false;
8176 case EXPR_BINARY_ISLESS: return false;
8177 case EXPR_BINARY_ISLESSEQUAL: return false;
8178 case EXPR_BINARY_ISLESSGREATER: return false;
8179 case EXPR_BINARY_ISUNORDERED: return false;
8182 internal_errorf(HERE, "unexpected expression");
8185 static void semantic_comma(binary_expression_t *expression)
8187 if (warning.unused_value) {
8188 const expression_t *const left = expression->left;
8189 if (!expression_has_effect(left)) {
8190 warningf(&left->base.source_position,
8191 "left-hand operand of comma expression has no effect");
8194 expression->base.type = expression->right->base.type;
8197 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8198 static expression_t *parse_##binexpression_type(unsigned precedence, \
8199 expression_t *left) \
8201 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8202 binexpr->base.source_position = *HERE; \
8203 binexpr->binary.left = left; \
8206 expression_t *right = parse_sub_expression(precedence + lr); \
8208 binexpr->binary.right = right; \
8209 sfunc(&binexpr->binary); \
8214 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8215 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8216 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8217 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8218 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8219 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8220 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8221 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8222 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8224 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8225 semantic_comparison, 1)
8226 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8227 semantic_comparison, 1)
8228 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8229 semantic_comparison, 1)
8230 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8231 semantic_comparison, 1)
8233 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8234 semantic_binexpr_arithmetic, 1)
8235 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8236 semantic_binexpr_arithmetic, 1)
8237 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8238 semantic_binexpr_arithmetic, 1)
8239 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8240 semantic_logical_op, 1)
8241 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8242 semantic_logical_op, 1)
8243 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8244 semantic_shift_op, 1)
8245 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8246 semantic_shift_op, 1)
8247 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8248 semantic_arithmetic_addsubb_assign, 0)
8249 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8250 semantic_arithmetic_addsubb_assign, 0)
8251 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8252 semantic_arithmetic_assign, 0)
8253 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8254 semantic_divmod_assign, 0)
8255 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8256 semantic_divmod_assign, 0)
8257 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8258 semantic_arithmetic_assign, 0)
8259 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8260 semantic_arithmetic_assign, 0)
8261 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8262 semantic_arithmetic_assign, 0)
8263 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8264 semantic_arithmetic_assign, 0)
8265 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8266 semantic_arithmetic_assign, 0)
8268 static expression_t *parse_sub_expression(unsigned precedence)
8270 if (token.type < 0) {
8271 return expected_expression_error();
8274 expression_parser_function_t *parser
8275 = &expression_parsers[token.type];
8276 source_position_t source_position = token.source_position;
8279 if (parser->parser != NULL) {
8280 left = parser->parser(parser->precedence);
8282 left = parse_primary_expression();
8284 assert(left != NULL);
8285 left->base.source_position = source_position;
8288 if (token.type < 0) {
8289 return expected_expression_error();
8292 parser = &expression_parsers[token.type];
8293 if (parser->infix_parser == NULL)
8295 if (parser->infix_precedence < precedence)
8298 left = parser->infix_parser(parser->infix_precedence, left);
8300 assert(left != NULL);
8301 assert(left->kind != EXPR_UNKNOWN);
8302 left->base.source_position = source_position;
8309 * Parse an expression.
8311 static expression_t *parse_expression(void)
8313 return parse_sub_expression(1);
8317 * Register a parser for a prefix-like operator with given precedence.
8319 * @param parser the parser function
8320 * @param token_type the token type of the prefix token
8321 * @param precedence the precedence of the operator
8323 static void register_expression_parser(parse_expression_function parser,
8324 int token_type, unsigned precedence)
8326 expression_parser_function_t *entry = &expression_parsers[token_type];
8328 if (entry->parser != NULL) {
8329 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8330 panic("trying to register multiple expression parsers for a token");
8332 entry->parser = parser;
8333 entry->precedence = precedence;
8337 * Register a parser for an infix operator with given precedence.
8339 * @param parser the parser function
8340 * @param token_type the token type of the infix operator
8341 * @param precedence the precedence of the operator
8343 static void register_infix_parser(parse_expression_infix_function parser,
8344 int token_type, unsigned precedence)
8346 expression_parser_function_t *entry = &expression_parsers[token_type];
8348 if (entry->infix_parser != NULL) {
8349 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8350 panic("trying to register multiple infix expression parsers for a "
8353 entry->infix_parser = parser;
8354 entry->infix_precedence = precedence;
8358 * Initialize the expression parsers.
8360 static void init_expression_parsers(void)
8362 memset(&expression_parsers, 0, sizeof(expression_parsers));
8364 register_infix_parser(parse_array_expression, '[', 30);
8365 register_infix_parser(parse_call_expression, '(', 30);
8366 register_infix_parser(parse_select_expression, '.', 30);
8367 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8368 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8370 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8373 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8374 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8375 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8376 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8377 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8378 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8379 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8380 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8381 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8382 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8383 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8384 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8385 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8386 T_EXCLAMATIONMARKEQUAL, 13);
8387 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8388 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8389 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8390 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8391 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8392 register_infix_parser(parse_conditional_expression, '?', 7);
8393 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8394 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8395 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8396 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8397 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8398 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8399 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8400 T_LESSLESSEQUAL, 2);
8401 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8402 T_GREATERGREATEREQUAL, 2);
8403 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8405 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8407 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8410 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8412 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8413 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8414 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8415 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8416 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8417 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8418 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8420 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8422 register_expression_parser(parse_sizeof, T_sizeof, 25);
8423 register_expression_parser(parse_alignof, T___alignof__, 25);
8424 register_expression_parser(parse_extension, T___extension__, 25);
8425 register_expression_parser(parse_builtin_classify_type,
8426 T___builtin_classify_type, 25);
8430 * Parse a asm statement arguments specification.
8432 static asm_argument_t *parse_asm_arguments(bool is_out)
8434 asm_argument_t *result = NULL;
8435 asm_argument_t *last = NULL;
8437 while (token.type == T_STRING_LITERAL || token.type == '[') {
8438 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8439 memset(argument, 0, sizeof(argument[0]));
8441 if (token.type == '[') {
8443 if (token.type != T_IDENTIFIER) {
8444 parse_error_expected("while parsing asm argument",
8445 T_IDENTIFIER, NULL);
8448 argument->symbol = token.v.symbol;
8453 argument->constraints = parse_string_literals();
8455 add_anchor_token(')');
8456 expression_t *expression = parse_expression();
8457 rem_anchor_token(')');
8459 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8460 * change size or type representation (e.g. int -> long is ok, but
8461 * int -> float is not) */
8462 if (expression->kind == EXPR_UNARY_CAST) {
8463 type_t *const type = expression->base.type;
8464 type_kind_t const kind = type->kind;
8465 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8468 if (kind == TYPE_ATOMIC) {
8469 atomic_type_kind_t const akind = type->atomic.akind;
8470 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8471 size = get_atomic_type_size(akind);
8473 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8474 size = get_atomic_type_size(get_intptr_kind());
8478 expression_t *const value = expression->unary.value;
8479 type_t *const value_type = value->base.type;
8480 type_kind_t const value_kind = value_type->kind;
8482 unsigned value_flags;
8483 unsigned value_size;
8484 if (value_kind == TYPE_ATOMIC) {
8485 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8486 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8487 value_size = get_atomic_type_size(value_akind);
8488 } else if (value_kind == TYPE_POINTER) {
8489 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8490 value_size = get_atomic_type_size(get_intptr_kind());
8495 if (value_flags != flags || value_size != size)
8499 } while (expression->kind == EXPR_UNARY_CAST);
8503 if (!is_lvalue(expression)) {
8504 errorf(&expression->base.source_position,
8505 "asm output argument is not an lvalue");
8508 argument->expression = expression;
8511 set_address_taken(expression, true);
8514 last->next = argument;
8520 if (token.type != ',')
8531 * Parse a asm statement clobber specification.
8533 static asm_clobber_t *parse_asm_clobbers(void)
8535 asm_clobber_t *result = NULL;
8536 asm_clobber_t *last = NULL;
8538 while(token.type == T_STRING_LITERAL) {
8539 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8540 clobber->clobber = parse_string_literals();
8543 last->next = clobber;
8549 if (token.type != ',')
8558 * Parse an asm statement.
8560 static statement_t *parse_asm_statement(void)
8564 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8565 statement->base.source_position = token.source_position;
8567 asm_statement_t *asm_statement = &statement->asms;
8569 if (token.type == T_volatile) {
8571 asm_statement->is_volatile = true;
8575 add_anchor_token(')');
8576 add_anchor_token(':');
8577 asm_statement->asm_text = parse_string_literals();
8579 if (token.type != ':') {
8580 rem_anchor_token(':');
8585 asm_statement->outputs = parse_asm_arguments(true);
8586 if (token.type != ':') {
8587 rem_anchor_token(':');
8592 asm_statement->inputs = parse_asm_arguments(false);
8593 if (token.type != ':') {
8594 rem_anchor_token(':');
8597 rem_anchor_token(':');
8600 asm_statement->clobbers = parse_asm_clobbers();
8603 rem_anchor_token(')');
8607 if (asm_statement->outputs == NULL) {
8608 /* GCC: An 'asm' instruction without any output operands will be treated
8609 * identically to a volatile 'asm' instruction. */
8610 asm_statement->is_volatile = true;
8615 return create_invalid_statement();
8619 * Parse a case statement.
8621 static statement_t *parse_case_statement(void)
8625 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8626 source_position_t *const pos = &statement->base.source_position;
8628 *pos = token.source_position;
8629 statement->case_label.expression = parse_expression();
8630 if (! is_constant_expression(statement->case_label.expression)) {
8631 errorf(pos, "case label does not reduce to an integer constant");
8632 statement->case_label.is_bad = true;
8634 long const val = fold_constant(statement->case_label.expression);
8635 statement->case_label.first_case = val;
8636 statement->case_label.last_case = val;
8639 if (c_mode & _GNUC) {
8640 if (token.type == T_DOTDOTDOT) {
8642 statement->case_label.end_range = parse_expression();
8643 if (! is_constant_expression(statement->case_label.end_range)) {
8644 errorf(pos, "case range does not reduce to an integer constant");
8645 statement->case_label.is_bad = true;
8647 long const val = fold_constant(statement->case_label.end_range);
8648 statement->case_label.last_case = val;
8650 if (val < statement->case_label.first_case) {
8651 statement->case_label.is_empty = true;
8652 warningf(pos, "empty range specified");
8658 PUSH_PARENT(statement);
8662 if (current_switch != NULL) {
8663 if (! statement->case_label.is_bad) {
8664 /* Check for duplicate case values */
8665 case_label_statement_t *c = &statement->case_label;
8666 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8667 if (l->is_bad || l->is_empty || l->expression == NULL)
8670 if (c->last_case < l->first_case || c->first_case > l->last_case)
8673 errorf(pos, "duplicate case value (previously used %P)",
8674 &l->base.source_position);
8678 /* link all cases into the switch statement */
8679 if (current_switch->last_case == NULL) {
8680 current_switch->first_case = &statement->case_label;
8682 current_switch->last_case->next = &statement->case_label;
8684 current_switch->last_case = &statement->case_label;
8686 errorf(pos, "case label not within a switch statement");
8689 statement_t *const inner_stmt = parse_statement();
8690 statement->case_label.statement = inner_stmt;
8691 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8692 errorf(&inner_stmt->base.source_position, "declaration after case label");
8699 return create_invalid_statement();
8703 * Parse a default statement.
8705 static statement_t *parse_default_statement(void)
8709 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8710 statement->base.source_position = token.source_position;
8712 PUSH_PARENT(statement);
8715 if (current_switch != NULL) {
8716 const case_label_statement_t *def_label = current_switch->default_label;
8717 if (def_label != NULL) {
8718 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8719 &def_label->base.source_position);
8721 current_switch->default_label = &statement->case_label;
8723 /* link all cases into the switch statement */
8724 if (current_switch->last_case == NULL) {
8725 current_switch->first_case = &statement->case_label;
8727 current_switch->last_case->next = &statement->case_label;
8729 current_switch->last_case = &statement->case_label;
8732 errorf(&statement->base.source_position,
8733 "'default' label not within a switch statement");
8736 statement_t *const inner_stmt = parse_statement();
8737 statement->case_label.statement = inner_stmt;
8738 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8739 errorf(&inner_stmt->base.source_position, "declaration after default label");
8746 return create_invalid_statement();
8750 * Parse a label statement.
8752 static statement_t *parse_label_statement(void)
8754 assert(token.type == T_IDENTIFIER);
8755 symbol_t *symbol = token.v.symbol;
8758 declaration_t *label = get_label(symbol);
8760 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8761 statement->base.source_position = token.source_position;
8762 statement->label.label = label;
8764 PUSH_PARENT(statement);
8766 /* if statement is already set then the label is defined twice,
8767 * otherwise it was just mentioned in a goto/local label declaration so far */
8768 if (label->init.statement != NULL) {
8769 errorf(HERE, "duplicate label '%Y' (declared %P)",
8770 symbol, &label->source_position);
8772 label->source_position = token.source_position;
8773 label->init.statement = statement;
8778 if (token.type == '}') {
8779 /* TODO only warn? */
8781 warningf(HERE, "label at end of compound statement");
8782 statement->label.statement = create_empty_statement();
8784 errorf(HERE, "label at end of compound statement");
8785 statement->label.statement = create_invalid_statement();
8787 } else if (token.type == ';') {
8788 /* Eat an empty statement here, to avoid the warning about an empty
8789 * statement after a label. label:; is commonly used to have a label
8790 * before a closing brace. */
8791 statement->label.statement = create_empty_statement();
8794 statement_t *const inner_stmt = parse_statement();
8795 statement->label.statement = inner_stmt;
8796 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8797 errorf(&inner_stmt->base.source_position, "declaration after label");
8801 /* remember the labels in a list for later checking */
8802 if (label_last == NULL) {
8803 label_first = &statement->label;
8805 label_last->next = &statement->label;
8807 label_last = &statement->label;
8814 * Parse an if statement.
8816 static statement_t *parse_if(void)
8820 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8821 statement->base.source_position = token.source_position;
8823 PUSH_PARENT(statement);
8826 add_anchor_token(')');
8827 statement->ifs.condition = parse_expression();
8828 rem_anchor_token(')');
8831 add_anchor_token(T_else);
8832 statement->ifs.true_statement = parse_statement();
8833 rem_anchor_token(T_else);
8835 if (token.type == T_else) {
8837 statement->ifs.false_statement = parse_statement();
8844 return create_invalid_statement();
8848 * Check that all enums are handled in a switch.
8850 * @param statement the switch statement to check
8852 static void check_enum_cases(const switch_statement_t *statement) {
8853 const type_t *type = skip_typeref(statement->expression->base.type);
8854 if (! is_type_enum(type))
8856 const enum_type_t *enumt = &type->enumt;
8858 /* if we have a default, no warnings */
8859 if (statement->default_label != NULL)
8862 /* FIXME: calculation of value should be done while parsing */
8863 const declaration_t *declaration;
8864 long last_value = -1;
8865 for (declaration = enumt->declaration->next;
8866 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8867 declaration = declaration->next) {
8868 const expression_t *expression = declaration->init.enum_value;
8869 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8871 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8872 if (l->expression == NULL)
8874 if (l->first_case <= value && value <= l->last_case) {
8880 warningf(&statement->base.source_position,
8881 "enumeration value '%Y' not handled in switch", declaration->symbol);
8888 * Parse a switch statement.
8890 static statement_t *parse_switch(void)
8894 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8895 statement->base.source_position = token.source_position;
8897 PUSH_PARENT(statement);
8900 add_anchor_token(')');
8901 expression_t *const expr = parse_expression();
8902 type_t * type = skip_typeref(expr->base.type);
8903 if (is_type_integer(type)) {
8904 type = promote_integer(type);
8905 if (warning.traditional) {
8906 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8907 warningf(&expr->base.source_position,
8908 "'%T' switch expression not converted to '%T' in ISO C",
8912 } else if (is_type_valid(type)) {
8913 errorf(&expr->base.source_position,
8914 "switch quantity is not an integer, but '%T'", type);
8915 type = type_error_type;
8917 statement->switchs.expression = create_implicit_cast(expr, type);
8919 rem_anchor_token(')');
8921 switch_statement_t *rem = current_switch;
8922 current_switch = &statement->switchs;
8923 statement->switchs.body = parse_statement();
8924 current_switch = rem;
8926 if (warning.switch_default &&
8927 statement->switchs.default_label == NULL) {
8928 warningf(&statement->base.source_position, "switch has no default case");
8930 if (warning.switch_enum)
8931 check_enum_cases(&statement->switchs);
8937 return create_invalid_statement();
8940 static statement_t *parse_loop_body(statement_t *const loop)
8942 statement_t *const rem = current_loop;
8943 current_loop = loop;
8945 statement_t *const body = parse_statement();
8952 * Parse a while statement.
8954 static statement_t *parse_while(void)
8958 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8959 statement->base.source_position = token.source_position;
8961 PUSH_PARENT(statement);
8964 add_anchor_token(')');
8965 statement->whiles.condition = parse_expression();
8966 rem_anchor_token(')');
8969 statement->whiles.body = parse_loop_body(statement);
8975 return create_invalid_statement();
8979 * Parse a do statement.
8981 static statement_t *parse_do(void)
8985 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8986 statement->base.source_position = token.source_position;
8988 PUSH_PARENT(statement)
8990 add_anchor_token(T_while);
8991 statement->do_while.body = parse_loop_body(statement);
8992 rem_anchor_token(T_while);
8996 add_anchor_token(')');
8997 statement->do_while.condition = parse_expression();
8998 rem_anchor_token(')');
9006 return create_invalid_statement();
9010 * Parse a for statement.
9012 static statement_t *parse_for(void)
9016 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9017 statement->base.source_position = token.source_position;
9019 PUSH_PARENT(statement);
9021 int top = environment_top();
9022 scope_t *last_scope = scope;
9023 set_scope(&statement->fors.scope);
9026 add_anchor_token(')');
9028 if (token.type != ';') {
9029 if (is_declaration_specifier(&token, false)) {
9030 parse_declaration(record_declaration);
9032 add_anchor_token(';');
9033 expression_t *const init = parse_expression();
9034 statement->fors.initialisation = init;
9035 if (warning.unused_value && !expression_has_effect(init)) {
9036 warningf(&init->base.source_position,
9037 "initialisation of 'for'-statement has no effect");
9039 rem_anchor_token(';');
9046 if (token.type != ';') {
9047 add_anchor_token(';');
9048 statement->fors.condition = parse_expression();
9049 rem_anchor_token(';');
9052 if (token.type != ')') {
9053 expression_t *const step = parse_expression();
9054 statement->fors.step = step;
9055 if (warning.unused_value && !expression_has_effect(step)) {
9056 warningf(&step->base.source_position,
9057 "step of 'for'-statement has no effect");
9060 rem_anchor_token(')');
9062 statement->fors.body = parse_loop_body(statement);
9064 assert(scope == &statement->fors.scope);
9065 set_scope(last_scope);
9066 environment_pop_to(top);
9073 rem_anchor_token(')');
9074 assert(scope == &statement->fors.scope);
9075 set_scope(last_scope);
9076 environment_pop_to(top);
9078 return create_invalid_statement();
9082 * Parse a goto statement.
9084 static statement_t *parse_goto(void)
9086 source_position_t source_position = token.source_position;
9089 statement_t *statement;
9090 if (c_mode & _GNUC && token.type == '*') {
9092 expression_t *expression = parse_expression();
9094 /* Argh: although documentation say the expression must be of type void *,
9095 * gcc excepts anything that can be casted into void * without error */
9096 type_t *type = expression->base.type;
9098 if (type != type_error_type) {
9099 if (!is_type_pointer(type) && !is_type_integer(type)) {
9100 errorf(&source_position, "cannot convert to a pointer type");
9101 } else if (type != type_void_ptr) {
9102 warningf(&source_position,
9103 "type of computed goto expression should be 'void*' not '%T'", type);
9105 expression = create_implicit_cast(expression, type_void_ptr);
9108 statement = allocate_statement_zero(STATEMENT_GOTO);
9109 statement->base.source_position = source_position;
9110 statement->gotos.expression = expression;
9112 if (token.type != T_IDENTIFIER) {
9114 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9116 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9120 symbol_t *symbol = token.v.symbol;
9123 statement = allocate_statement_zero(STATEMENT_GOTO);
9124 statement->base.source_position = source_position;
9125 statement->gotos.label = get_label(symbol);
9128 /* remember the goto's in a list for later checking */
9129 if (goto_last == NULL) {
9130 goto_first = &statement->gotos;
9132 goto_last->next = &statement->gotos;
9134 goto_last = &statement->gotos;
9140 return create_invalid_statement();
9144 * Parse a continue statement.
9146 static statement_t *parse_continue(void)
9148 if (current_loop == NULL) {
9149 errorf(HERE, "continue statement not within loop");
9152 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9153 statement->base.source_position = token.source_position;
9163 * Parse a break statement.
9165 static statement_t *parse_break(void)
9167 if (current_switch == NULL && current_loop == NULL) {
9168 errorf(HERE, "break statement not within loop or switch");
9171 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9172 statement->base.source_position = token.source_position;
9182 * Parse a __leave statement.
9184 static statement_t *parse_leave_statement(void)
9186 if (current_try == NULL) {
9187 errorf(HERE, "__leave statement not within __try");
9190 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9191 statement->base.source_position = token.source_position;
9201 * Check if a given declaration represents a local variable.
9203 static bool is_local_var_declaration(const declaration_t *declaration)
9205 switch ((storage_class_tag_t) declaration->storage_class) {
9206 case STORAGE_CLASS_AUTO:
9207 case STORAGE_CLASS_REGISTER: {
9208 const type_t *type = skip_typeref(declaration->type);
9209 if (is_type_function(type)) {
9221 * Check if a given declaration represents a variable.
9223 static bool is_var_declaration(const declaration_t *declaration)
9225 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9228 const type_t *type = skip_typeref(declaration->type);
9229 return !is_type_function(type);
9233 * Check if a given expression represents a local variable.
9235 static bool is_local_variable(const expression_t *expression)
9237 if (expression->base.kind != EXPR_REFERENCE) {
9240 const declaration_t *declaration = expression->reference.declaration;
9241 return is_local_var_declaration(declaration);
9245 * Check if a given expression represents a local variable and
9246 * return its declaration then, else return NULL.
9248 declaration_t *expr_is_variable(const expression_t *expression)
9250 if (expression->base.kind != EXPR_REFERENCE) {
9253 declaration_t *declaration = expression->reference.declaration;
9254 if (is_var_declaration(declaration))
9260 * Parse a return statement.
9262 static statement_t *parse_return(void)
9264 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9265 statement->base.source_position = token.source_position;
9269 expression_t *return_value = NULL;
9270 if (token.type != ';') {
9271 return_value = parse_expression();
9274 const type_t *const func_type = current_function->type;
9275 assert(is_type_function(func_type));
9276 type_t *const return_type = skip_typeref(func_type->function.return_type);
9278 if (return_value != NULL) {
9279 type_t *return_value_type = skip_typeref(return_value->base.type);
9281 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9282 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9283 warningf(&statement->base.source_position,
9284 "'return' with a value, in function returning void");
9285 return_value = NULL;
9287 assign_error_t error = semantic_assign(return_type, return_value);
9288 report_assign_error(error, return_type, return_value, "'return'",
9289 &statement->base.source_position);
9290 return_value = create_implicit_cast(return_value, return_type);
9292 /* check for returning address of a local var */
9293 if (return_value != NULL &&
9294 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9295 const expression_t *expression = return_value->unary.value;
9296 if (is_local_variable(expression)) {
9297 warningf(&statement->base.source_position,
9298 "function returns address of local variable");
9302 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9303 warningf(&statement->base.source_position,
9304 "'return' without value, in function returning non-void");
9307 statement->returns.value = return_value;
9316 * Parse a declaration statement.
9318 static statement_t *parse_declaration_statement(void)
9320 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9322 statement->base.source_position = token.source_position;
9324 declaration_t *before = last_declaration;
9325 parse_declaration(record_declaration);
9327 if (before == NULL) {
9328 statement->declaration.declarations_begin = scope->declarations;
9330 statement->declaration.declarations_begin = before->next;
9332 statement->declaration.declarations_end = last_declaration;
9338 * Parse an expression statement, ie. expr ';'.
9340 static statement_t *parse_expression_statement(void)
9342 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9344 statement->base.source_position = token.source_position;
9345 expression_t *const expr = parse_expression();
9346 statement->expression.expression = expr;
9355 * Parse a microsoft __try { } __finally { } or
9356 * __try{ } __except() { }
9358 static statement_t *parse_ms_try_statment(void)
9360 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9361 statement->base.source_position = token.source_position;
9364 PUSH_PARENT(statement);
9366 ms_try_statement_t *rem = current_try;
9367 current_try = &statement->ms_try;
9368 statement->ms_try.try_statement = parse_compound_statement(false);
9373 if (token.type == T___except) {
9376 add_anchor_token(')');
9377 expression_t *const expr = parse_expression();
9378 type_t * type = skip_typeref(expr->base.type);
9379 if (is_type_integer(type)) {
9380 type = promote_integer(type);
9381 } else if (is_type_valid(type)) {
9382 errorf(&expr->base.source_position,
9383 "__expect expression is not an integer, but '%T'", type);
9384 type = type_error_type;
9386 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9387 rem_anchor_token(')');
9389 statement->ms_try.final_statement = parse_compound_statement(false);
9390 } else if (token.type == T__finally) {
9392 statement->ms_try.final_statement = parse_compound_statement(false);
9394 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9395 return create_invalid_statement();
9399 return create_invalid_statement();
9402 static statement_t *parse_empty_statement(void)
9404 if (warning.empty_statement) {
9405 warningf(HERE, "statement is empty");
9407 statement_t *const statement = create_empty_statement();
9412 static statement_t *parse_local_label_declaration(void) {
9413 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9414 statement->base.source_position = token.source_position;
9418 declaration_t *begin = NULL, *end = NULL;
9421 if (token.type != T_IDENTIFIER) {
9422 parse_error_expected("while parsing local label declaration",
9423 T_IDENTIFIER, NULL);
9426 symbol_t *symbol = token.v.symbol;
9427 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9428 if (declaration != NULL) {
9429 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9430 symbol, &declaration->source_position);
9432 declaration = allocate_declaration_zero();
9433 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9434 declaration->source_position = token.source_position;
9435 declaration->symbol = symbol;
9436 declaration->parent_scope = scope;
9437 declaration->init.statement = NULL;
9440 end->next = declaration;
9443 begin = declaration;
9445 local_label_push(declaration);
9449 if (token.type != ',')
9455 statement->declaration.declarations_begin = begin;
9456 statement->declaration.declarations_end = end;
9461 * Parse a statement.
9462 * There's also parse_statement() which additionally checks for
9463 * "statement has no effect" warnings
9465 static statement_t *intern_parse_statement(void)
9467 statement_t *statement = NULL;
9469 /* declaration or statement */
9470 add_anchor_token(';');
9471 switch (token.type) {
9472 case T_IDENTIFIER: {
9473 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9474 if (la1_type == ':') {
9475 statement = parse_label_statement();
9476 } else if (is_typedef_symbol(token.v.symbol)) {
9477 statement = parse_declaration_statement();
9478 } else switch (la1_type) {
9482 statement = parse_declaration_statement();
9486 statement = parse_expression_statement();
9492 case T___extension__:
9493 /* This can be a prefix to a declaration or an expression statement.
9494 * We simply eat it now and parse the rest with tail recursion. */
9497 } while (token.type == T___extension__);
9498 statement = parse_statement();
9502 statement = parse_declaration_statement();
9506 statement = parse_local_label_declaration();
9509 case ';': statement = parse_empty_statement(); break;
9510 case '{': statement = parse_compound_statement(false); break;
9511 case T___leave: statement = parse_leave_statement(); break;
9512 case T___try: statement = parse_ms_try_statment(); break;
9513 case T_asm: statement = parse_asm_statement(); break;
9514 case T_break: statement = parse_break(); break;
9515 case T_case: statement = parse_case_statement(); break;
9516 case T_continue: statement = parse_continue(); break;
9517 case T_default: statement = parse_default_statement(); break;
9518 case T_do: statement = parse_do(); break;
9519 case T_for: statement = parse_for(); break;
9520 case T_goto: statement = parse_goto(); break;
9521 case T_if: statement = parse_if (); break;
9522 case T_return: statement = parse_return(); break;
9523 case T_switch: statement = parse_switch(); break;
9524 case T_while: statement = parse_while(); break;
9525 default: statement = parse_expression_statement(); break;
9527 rem_anchor_token(';');
9529 assert(statement != NULL
9530 && statement->base.source_position.input_name != NULL);
9536 * parse a statement and emits "statement has no effect" warning if needed
9537 * (This is really a wrapper around intern_parse_statement with check for 1
9538 * single warning. It is needed, because for statement expressions we have
9539 * to avoid the warning on the last statement)
9541 static statement_t *parse_statement(void)
9543 statement_t *statement = intern_parse_statement();
9545 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9546 expression_t *expression = statement->expression.expression;
9547 if (!expression_has_effect(expression)) {
9548 warningf(&expression->base.source_position,
9549 "statement has no effect");
9557 * Parse a compound statement.
9559 static statement_t *parse_compound_statement(bool inside_expression_statement)
9561 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9562 statement->base.source_position = token.source_position;
9564 PUSH_PARENT(statement);
9567 add_anchor_token('}');
9569 int top = environment_top();
9570 int top_local = local_label_top();
9571 scope_t *last_scope = scope;
9572 set_scope(&statement->compound.scope);
9574 statement_t **anchor = &statement->compound.statements;
9575 bool only_decls_so_far = true;
9576 while (token.type != '}' && token.type != T_EOF) {
9577 statement_t *sub_statement = intern_parse_statement();
9578 if (is_invalid_statement(sub_statement)) {
9579 /* an error occurred. if we are at an anchor, return */
9585 if (warning.declaration_after_statement) {
9586 if (sub_statement->kind != STATEMENT_DECLARATION) {
9587 only_decls_so_far = false;
9588 } else if (!only_decls_so_far) {
9589 warningf(&sub_statement->base.source_position,
9590 "ISO C90 forbids mixed declarations and code");
9594 *anchor = sub_statement;
9596 while (sub_statement->base.next != NULL)
9597 sub_statement = sub_statement->base.next;
9599 anchor = &sub_statement->base.next;
9602 if (token.type == '}') {
9605 errorf(&statement->base.source_position,
9606 "end of file while looking for closing '}'");
9609 /* look over all statements again to produce no effect warnings */
9610 if (warning.unused_value) {
9611 statement_t *sub_statement = statement->compound.statements;
9612 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9613 if (sub_statement->kind != STATEMENT_EXPRESSION)
9615 /* don't emit a warning for the last expression in an expression
9616 * statement as it has always an effect */
9617 if (inside_expression_statement && sub_statement->base.next == NULL)
9620 expression_t *expression = sub_statement->expression.expression;
9621 if (!expression_has_effect(expression)) {
9622 warningf(&expression->base.source_position,
9623 "statement has no effect");
9629 rem_anchor_token('}');
9630 assert(scope == &statement->compound.scope);
9631 set_scope(last_scope);
9632 environment_pop_to(top);
9633 local_label_pop_to(top_local);
9640 * Initialize builtin types.
9642 static void initialize_builtin_types(void)
9644 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9645 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9646 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9647 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9648 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9649 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9650 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9651 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9653 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9654 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9655 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9656 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9658 /* const version of wchar_t */
9659 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9660 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9661 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9663 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9667 * Check for unused global static functions and variables
9669 static void check_unused_globals(void)
9671 if (!warning.unused_function && !warning.unused_variable)
9674 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9676 decl->modifiers & DM_UNUSED ||
9677 decl->modifiers & DM_USED ||
9678 decl->storage_class != STORAGE_CLASS_STATIC)
9681 type_t *const type = decl->type;
9683 if (is_type_function(skip_typeref(type))) {
9684 if (!warning.unused_function || decl->is_inline)
9687 s = (decl->init.statement != NULL ? "defined" : "declared");
9689 if (!warning.unused_variable)
9695 warningf(&decl->source_position, "'%#T' %s but not used",
9696 type, decl->symbol, s);
9700 static void parse_global_asm(void)
9705 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9706 statement->base.source_position = token.source_position;
9707 statement->asms.asm_text = parse_string_literals();
9708 statement->base.next = unit->global_asm;
9709 unit->global_asm = statement;
9718 * Parse a translation unit.
9720 static void parse_translation_unit(void)
9722 for (;;) switch (token.type) {
9725 case T___extension__:
9726 parse_external_declaration();
9737 /* TODO error in strict mode */
9738 warningf(HERE, "stray ';' outside of function");
9743 errorf(HERE, "stray %K outside of function", &token);
9744 if (token.type == '(' || token.type == '{' || token.type == '[')
9745 eat_until_matching_token(token.type);
9754 * @return the translation unit or NULL if errors occurred.
9756 void start_parsing(void)
9758 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9759 label_stack = NEW_ARR_F(stack_entry_t, 0);
9760 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
9761 diagnostic_count = 0;
9765 type_set_output(stderr);
9766 ast_set_output(stderr);
9768 assert(unit == NULL);
9769 unit = allocate_ast_zero(sizeof(unit[0]));
9771 assert(global_scope == NULL);
9772 global_scope = &unit->scope;
9774 assert(scope == NULL);
9775 set_scope(&unit->scope);
9777 initialize_builtin_types();
9780 translation_unit_t *finish_parsing(void)
9782 assert(scope == &unit->scope);
9784 last_declaration = NULL;
9786 assert(global_scope == &unit->scope);
9787 check_unused_globals();
9788 global_scope = NULL;
9790 DEL_ARR_F(environment_stack);
9791 DEL_ARR_F(label_stack);
9792 DEL_ARR_F(local_label_stack);
9794 translation_unit_t *result = unit;
9801 lookahead_bufpos = 0;
9802 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9805 parse_translation_unit();
9809 * Initialize the parser.
9811 void init_parser(void)
9814 /* add predefined symbols for extended-decl-modifier */
9815 sym_align = symbol_table_insert("align");
9816 sym_allocate = symbol_table_insert("allocate");
9817 sym_dllimport = symbol_table_insert("dllimport");
9818 sym_dllexport = symbol_table_insert("dllexport");
9819 sym_naked = symbol_table_insert("naked");
9820 sym_noinline = symbol_table_insert("noinline");
9821 sym_noreturn = symbol_table_insert("noreturn");
9822 sym_nothrow = symbol_table_insert("nothrow");
9823 sym_novtable = symbol_table_insert("novtable");
9824 sym_property = symbol_table_insert("property");
9825 sym_get = symbol_table_insert("get");
9826 sym_put = symbol_table_insert("put");
9827 sym_selectany = symbol_table_insert("selectany");
9828 sym_thread = symbol_table_insert("thread");
9829 sym_uuid = symbol_table_insert("uuid");
9830 sym_deprecated = symbol_table_insert("deprecated");
9831 sym_restrict = symbol_table_insert("restrict");
9832 sym_noalias = symbol_table_insert("noalias");
9834 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9836 init_expression_parsers();
9837 obstack_init(&temp_obst);
9839 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9840 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9844 * Terminate the parser.
9846 void exit_parser(void)
9848 obstack_free(&temp_obst, NULL);