2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
108 /** The current token. */
109 static token_t token;
110 /** The lookahead ring-buffer. */
111 static token_t lookahead_buffer[MAX_LOOKAHEAD];
112 /** Position of the next token in the lookahead buffer. */
113 static int lookahead_bufpos;
114 static stack_entry_t *environment_stack = NULL;
115 static stack_entry_t *label_stack = NULL;
116 static stack_entry_t *local_label_stack = NULL;
117 static scope_t *global_scope = NULL;
118 static scope_t *scope = NULL;
119 static declaration_t *last_declaration = NULL;
120 static declaration_t *current_function = NULL;
121 static declaration_t *current_init_decl = NULL;
122 static switch_statement_t *current_switch = NULL;
123 static statement_t *current_loop = NULL;
124 static statement_t *current_parent = NULL;
125 static ms_try_statement_t *current_try = NULL;
126 static goto_statement_t *goto_first = NULL;
127 static goto_statement_t *goto_last = NULL;
128 static label_statement_t *label_first = NULL;
129 static label_statement_t *label_last = NULL;
130 /** current translation unit. */
131 static translation_unit_t *unit = NULL;
132 /** true if we are in a type property context (evaluation only for type. */
133 static bool in_type_prop = false;
134 /** true in we are in a __extension__ context. */
135 static bool in_gcc_extension = false;
136 static struct obstack temp_obst;
139 #define PUSH_PARENT(stmt) \
140 statement_t *const prev_parent = current_parent; \
141 current_parent = (stmt);
142 #define POP_PARENT ((void)(current_parent = prev_parent))
144 static source_position_t null_position = { NULL, 0 };
146 /** special symbol used for anonymous entities. */
147 static const symbol_t *sym_anonymous = NULL;
149 /* symbols for Microsoft extended-decl-modifier */
150 static const symbol_t *sym_align = NULL;
151 static const symbol_t *sym_allocate = NULL;
152 static const symbol_t *sym_dllimport = NULL;
153 static const symbol_t *sym_dllexport = NULL;
154 static const symbol_t *sym_naked = NULL;
155 static const symbol_t *sym_noinline = NULL;
156 static const symbol_t *sym_noreturn = NULL;
157 static const symbol_t *sym_nothrow = NULL;
158 static const symbol_t *sym_novtable = NULL;
159 static const symbol_t *sym_property = NULL;
160 static const symbol_t *sym_get = NULL;
161 static const symbol_t *sym_put = NULL;
162 static const symbol_t *sym_selectany = NULL;
163 static const symbol_t *sym_thread = NULL;
164 static const symbol_t *sym_uuid = NULL;
165 static const symbol_t *sym_deprecated = NULL;
166 static const symbol_t *sym_restrict = NULL;
167 static const symbol_t *sym_noalias = NULL;
169 /** The token anchor set */
170 static unsigned char token_anchor_set[T_LAST_TOKEN];
172 /** The current source position. */
173 #define HERE (&token.source_position)
175 /** true if we are in GCC mode. */
176 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
178 static type_t *type_valist;
180 static statement_t *parse_compound_statement(bool inside_expression_statement);
181 static statement_t *parse_statement(void);
183 static expression_t *parse_sub_expression(unsigned precedence);
184 static expression_t *parse_expression(void);
185 static type_t *parse_typename(void);
187 static void parse_compound_type_entries(declaration_t *compound_declaration);
188 static declaration_t *parse_declarator(
189 const declaration_specifiers_t *specifiers, bool may_be_abstract);
190 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
192 static void semantic_comparison(binary_expression_t *expression);
194 #define STORAGE_CLASSES \
202 #define TYPE_QUALIFIERS \
207 case T__forceinline: \
208 case T___attribute__:
210 #ifdef PROVIDE_COMPLEX
211 #define COMPLEX_SPECIFIERS \
213 #define IMAGINARY_SPECIFIERS \
216 #define COMPLEX_SPECIFIERS
217 #define IMAGINARY_SPECIFIERS
220 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
240 #define DECLARATION_START \
245 #define TYPENAME_START \
250 * Allocate an AST node with given size and
251 * initialize all fields with zero.
253 static void *allocate_ast_zero(size_t size)
255 void *res = allocate_ast(size);
256 memset(res, 0, size);
260 static declaration_t *allocate_declaration_zero(void)
262 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
263 declaration->type = type_error_type;
264 declaration->alignment = 0;
269 * Returns the size of a statement node.
271 * @param kind the statement kind
273 static size_t get_statement_struct_size(statement_kind_t kind)
275 static const size_t sizes[] = {
276 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
277 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
278 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
279 [STATEMENT_RETURN] = sizeof(return_statement_t),
280 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
281 [STATEMENT_IF] = sizeof(if_statement_t),
282 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
283 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
284 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
285 [STATEMENT_BREAK] = sizeof(statement_base_t),
286 [STATEMENT_GOTO] = sizeof(goto_statement_t),
287 [STATEMENT_LABEL] = sizeof(label_statement_t),
288 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
289 [STATEMENT_WHILE] = sizeof(while_statement_t),
290 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
291 [STATEMENT_FOR] = sizeof(for_statement_t),
292 [STATEMENT_ASM] = sizeof(asm_statement_t),
293 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
294 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
296 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
297 assert(sizes[kind] != 0);
302 * Returns the size of an expression node.
304 * @param kind the expression kind
306 static size_t get_expression_struct_size(expression_kind_t kind)
308 static const size_t sizes[] = {
309 [EXPR_INVALID] = sizeof(expression_base_t),
310 [EXPR_REFERENCE] = sizeof(reference_expression_t),
311 [EXPR_CONST] = sizeof(const_expression_t),
312 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
313 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
314 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
315 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
316 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
317 [EXPR_CALL] = sizeof(call_expression_t),
318 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
319 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
320 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
321 [EXPR_SELECT] = sizeof(select_expression_t),
322 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
323 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
324 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
325 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
326 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
327 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
328 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
329 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
330 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
331 [EXPR_VA_START] = sizeof(va_start_expression_t),
332 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
333 [EXPR_STATEMENT] = sizeof(statement_expression_t),
334 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
336 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
337 return sizes[EXPR_UNARY_FIRST];
339 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
340 return sizes[EXPR_BINARY_FIRST];
342 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
343 assert(sizes[kind] != 0);
348 * Allocate a statement node of given kind and initialize all
351 static statement_t *allocate_statement_zero(statement_kind_t kind)
353 size_t size = get_statement_struct_size(kind);
354 statement_t *res = allocate_ast_zero(size);
356 res->base.kind = kind;
357 res->base.parent = current_parent;
362 * Allocate an expression node of given kind and initialize all
365 static expression_t *allocate_expression_zero(expression_kind_t kind)
367 size_t size = get_expression_struct_size(kind);
368 expression_t *res = allocate_ast_zero(size);
370 res->base.kind = kind;
371 res->base.type = type_error_type;
376 * Creates a new invalid expression.
378 static expression_t *create_invalid_expression(void)
380 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
381 expression->base.source_position = token.source_position;
386 * Creates a new invalid statement.
388 static statement_t *create_invalid_statement(void)
390 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
391 statement->base.source_position = token.source_position;
396 * Allocate a new empty statement.
398 static statement_t *create_empty_statement(void)
400 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
401 statement->base.source_position = token.source_position;
406 * Returns the size of a type node.
408 * @param kind the type kind
410 static size_t get_type_struct_size(type_kind_t kind)
412 static const size_t sizes[] = {
413 [TYPE_ATOMIC] = sizeof(atomic_type_t),
414 [TYPE_COMPLEX] = sizeof(complex_type_t),
415 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
416 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
417 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
418 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
419 [TYPE_ENUM] = sizeof(enum_type_t),
420 [TYPE_FUNCTION] = sizeof(function_type_t),
421 [TYPE_POINTER] = sizeof(pointer_type_t),
422 [TYPE_ARRAY] = sizeof(array_type_t),
423 [TYPE_BUILTIN] = sizeof(builtin_type_t),
424 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
425 [TYPE_TYPEOF] = sizeof(typeof_type_t),
427 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
428 assert(kind <= TYPE_TYPEOF);
429 assert(sizes[kind] != 0);
434 * Allocate a type node of given kind and initialize all
437 * @param kind type kind to allocate
438 * @param source_position the source position of the type definition
440 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
442 size_t size = get_type_struct_size(kind);
443 type_t *res = obstack_alloc(type_obst, size);
444 memset(res, 0, size);
446 res->base.kind = kind;
447 res->base.source_position = *source_position;
452 * Returns the size of an initializer node.
454 * @param kind the initializer kind
456 static size_t get_initializer_size(initializer_kind_t kind)
458 static const size_t sizes[] = {
459 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
460 [INITIALIZER_STRING] = sizeof(initializer_string_t),
461 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
462 [INITIALIZER_LIST] = sizeof(initializer_list_t),
463 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
465 assert(kind < sizeof(sizes) / sizeof(*sizes));
466 assert(sizes[kind] != 0);
471 * Allocate an initializer node of given kind and initialize all
474 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
476 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
483 * Free a type from the type obstack.
485 static void free_type(void *type)
487 obstack_free(type_obst, type);
491 * Returns the index of the top element of the environment stack.
493 static size_t environment_top(void)
495 return ARR_LEN(environment_stack);
499 * Returns the index of the top element of the global label stack.
501 static size_t label_top(void)
503 return ARR_LEN(label_stack);
507 * Returns the index of the top element of the local label stack.
509 static size_t local_label_top(void)
511 return ARR_LEN(local_label_stack);
515 * Return the next token.
517 static inline void next_token(void)
519 token = lookahead_buffer[lookahead_bufpos];
520 lookahead_buffer[lookahead_bufpos] = lexer_token;
523 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
526 print_token(stderr, &token);
527 fprintf(stderr, "\n");
532 * Return the next token with a given lookahead.
534 static inline const token_t *look_ahead(int num)
536 assert(num > 0 && num <= MAX_LOOKAHEAD);
537 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
538 return &lookahead_buffer[pos];
542 * Adds a token to the token anchor set (a multi-set).
544 static void add_anchor_token(int token_type)
546 assert(0 <= token_type && token_type < T_LAST_TOKEN);
547 ++token_anchor_set[token_type];
550 static int save_and_reset_anchor_state(int token_type)
552 assert(0 <= token_type && token_type < T_LAST_TOKEN);
553 int count = token_anchor_set[token_type];
554 token_anchor_set[token_type] = 0;
558 static void restore_anchor_state(int token_type, int count)
560 assert(0 <= token_type && token_type < T_LAST_TOKEN);
561 token_anchor_set[token_type] = count;
565 * Remove a token from the token anchor set (a multi-set).
567 static void rem_anchor_token(int token_type)
569 assert(0 <= token_type && token_type < T_LAST_TOKEN);
570 assert(token_anchor_set[token_type] != 0);
571 --token_anchor_set[token_type];
574 static bool at_anchor(void)
578 return token_anchor_set[token.type];
582 * Eat tokens until a matching token is found.
584 static void eat_until_matching_token(int type)
588 case '(': end_token = ')'; break;
589 case '{': end_token = '}'; break;
590 case '[': end_token = ']'; break;
591 default: end_token = type; break;
594 unsigned parenthesis_count = 0;
595 unsigned brace_count = 0;
596 unsigned bracket_count = 0;
597 while (token.type != end_token ||
598 parenthesis_count != 0 ||
600 bracket_count != 0) {
601 switch (token.type) {
603 case '(': ++parenthesis_count; break;
604 case '{': ++brace_count; break;
605 case '[': ++bracket_count; break;
608 if (parenthesis_count > 0)
618 if (bracket_count > 0)
621 if (token.type == end_token &&
622 parenthesis_count == 0 &&
636 * Eat input tokens until an anchor is found.
638 static void eat_until_anchor(void)
640 if (token.type == T_EOF)
642 while (token_anchor_set[token.type] == 0) {
643 if (token.type == '(' || token.type == '{' || token.type == '[')
644 eat_until_matching_token(token.type);
645 if (token.type == T_EOF)
651 static void eat_block(void)
653 eat_until_matching_token('{');
654 if (token.type == '}')
658 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
661 * Report a parse error because an expected token was not found.
664 #if defined __GNUC__ && __GNUC__ >= 4
665 __attribute__((sentinel))
667 void parse_error_expected(const char *message, ...)
669 if (message != NULL) {
670 errorf(HERE, "%s", message);
673 va_start(ap, message);
674 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
679 * Report a type error.
681 static void type_error(const char *msg, const source_position_t *source_position,
684 errorf(source_position, "%s, but found type '%T'", msg, type);
688 * Report an incompatible type.
690 static void type_error_incompatible(const char *msg,
691 const source_position_t *source_position, type_t *type1, type_t *type2)
693 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
698 * Expect the the current token is the expected token.
699 * If not, generate an error, eat the current statement,
700 * and goto the end_error label.
702 #define expect(expected) \
704 if (UNLIKELY(token.type != (expected))) { \
705 parse_error_expected(NULL, (expected), NULL); \
706 add_anchor_token(expected); \
707 eat_until_anchor(); \
708 if (token.type == expected) \
710 rem_anchor_token(expected); \
716 static void set_scope(scope_t *new_scope)
719 scope->last_declaration = last_declaration;
723 last_declaration = new_scope->last_declaration;
727 * Search a symbol in a given namespace and returns its declaration or
728 * NULL if this symbol was not found.
730 static declaration_t *get_declaration(const symbol_t *const symbol,
731 const namespace_t namespc)
733 declaration_t *declaration = symbol->declaration;
734 for( ; declaration != NULL; declaration = declaration->symbol_next) {
735 if (declaration->namespc == namespc)
743 * pushs an environment_entry on the environment stack and links the
744 * corresponding symbol to the new entry
746 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
748 symbol_t *symbol = declaration->symbol;
749 namespace_t namespc = (namespace_t) declaration->namespc;
751 /* replace/add declaration into declaration list of the symbol */
752 declaration_t *iter = symbol->declaration;
754 symbol->declaration = declaration;
756 declaration_t *iter_last = NULL;
757 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
758 /* replace an entry? */
759 if (iter->namespc == namespc) {
760 if (iter_last == NULL) {
761 symbol->declaration = declaration;
763 iter_last->symbol_next = declaration;
765 declaration->symbol_next = iter->symbol_next;
770 assert(iter_last->symbol_next == NULL);
771 iter_last->symbol_next = declaration;
775 /* remember old declaration */
777 entry.symbol = symbol;
778 entry.old_declaration = iter;
779 entry.namespc = (unsigned short) namespc;
780 ARR_APP1(stack_entry_t, *stack_ptr, entry);
784 * Push a declaration on the environment stack.
786 * @param declaration the declaration
788 static void environment_push(declaration_t *declaration)
790 assert(declaration->source_position.input_name != NULL);
791 assert(declaration->parent_scope != NULL);
792 stack_push(&environment_stack, declaration);
796 * Push a declaration on the global label stack.
798 * @param declaration the declaration
800 static void label_push(declaration_t *declaration)
802 declaration->parent_scope = ¤t_function->scope;
803 stack_push(&label_stack, declaration);
807 * Push a declaration of the local label stack.
809 * @param declaration the declaration
811 static void local_label_push(declaration_t *declaration)
813 assert(declaration->parent_scope != NULL);
814 stack_push(&local_label_stack, declaration);
818 * pops symbols from the environment stack until @p new_top is the top element
820 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
822 stack_entry_t *stack = *stack_ptr;
823 size_t top = ARR_LEN(stack);
826 assert(new_top <= top);
830 for(i = top; i > new_top; --i) {
831 stack_entry_t *entry = &stack[i - 1];
833 declaration_t *old_declaration = entry->old_declaration;
834 symbol_t *symbol = entry->symbol;
835 namespace_t namespc = (namespace_t)entry->namespc;
837 /* replace/remove declaration */
838 declaration_t *declaration = symbol->declaration;
839 assert(declaration != NULL);
840 if (declaration->namespc == namespc) {
841 if (old_declaration == NULL) {
842 symbol->declaration = declaration->symbol_next;
844 symbol->declaration = old_declaration;
847 declaration_t *iter_last = declaration;
848 declaration_t *iter = declaration->symbol_next;
849 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
850 /* replace an entry? */
851 if (iter->namespc == namespc) {
852 assert(iter_last != NULL);
853 iter_last->symbol_next = old_declaration;
854 if (old_declaration != NULL) {
855 old_declaration->symbol_next = iter->symbol_next;
860 assert(iter != NULL);
864 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
868 * Pop all entries from the environment stack until the new_top
871 * @param new_top the new stack top
873 static void environment_pop_to(size_t new_top)
875 stack_pop_to(&environment_stack, new_top);
879 * Pop all entries from the global label stack until the new_top
882 * @param new_top the new stack top
884 static void label_pop_to(size_t new_top)
886 stack_pop_to(&label_stack, new_top);
890 * Pop all entries from the local label stack until the new_top
893 * @param new_top the new stack top
895 static void local_label_pop_to(size_t new_top)
897 stack_pop_to(&local_label_stack, new_top);
901 static int get_akind_rank(atomic_type_kind_t akind)
906 static int get_rank(const type_t *type)
908 assert(!is_typeref(type));
909 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
910 * and esp. footnote 108). However we can't fold constants (yet), so we
911 * can't decide whether unsigned int is possible, while int always works.
912 * (unsigned int would be preferable when possible... for stuff like
913 * struct { enum { ... } bla : 4; } ) */
914 if (type->kind == TYPE_ENUM)
915 return get_akind_rank(ATOMIC_TYPE_INT);
917 assert(type->kind == TYPE_ATOMIC);
918 return get_akind_rank(type->atomic.akind);
921 static type_t *promote_integer(type_t *type)
923 if (type->kind == TYPE_BITFIELD)
924 type = type->bitfield.base_type;
926 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
933 * Create a cast expression.
935 * @param expression the expression to cast
936 * @param dest_type the destination type
938 static expression_t *create_cast_expression(expression_t *expression,
941 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
943 cast->unary.value = expression;
944 cast->base.type = dest_type;
950 * Check if a given expression represents the 0 pointer constant.
952 static bool is_null_pointer_constant(const expression_t *expression)
954 /* skip void* cast */
955 if (expression->kind == EXPR_UNARY_CAST
956 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
957 expression = expression->unary.value;
960 /* TODO: not correct yet, should be any constant integer expression
961 * which evaluates to 0 */
962 if (expression->kind != EXPR_CONST)
965 type_t *const type = skip_typeref(expression->base.type);
966 if (!is_type_integer(type))
969 return expression->conste.v.int_value == 0;
973 * Create an implicit cast expression.
975 * @param expression the expression to cast
976 * @param dest_type the destination type
978 static expression_t *create_implicit_cast(expression_t *expression,
981 type_t *const source_type = expression->base.type;
983 if (source_type == dest_type)
986 return create_cast_expression(expression, dest_type);
989 typedef enum assign_error_t {
991 ASSIGN_ERROR_INCOMPATIBLE,
992 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
993 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
994 ASSIGN_WARNING_POINTER_FROM_INT,
995 ASSIGN_WARNING_INT_FROM_POINTER
998 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
999 const expression_t *const right,
1000 const char *context,
1001 const source_position_t *source_position)
1003 type_t *const orig_type_right = right->base.type;
1004 type_t *const type_left = skip_typeref(orig_type_left);
1005 type_t *const type_right = skip_typeref(orig_type_right);
1008 case ASSIGN_SUCCESS:
1010 case ASSIGN_ERROR_INCOMPATIBLE:
1011 errorf(source_position,
1012 "destination type '%T' in %s is incompatible with type '%T'",
1013 orig_type_left, context, orig_type_right);
1016 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1017 type_t *points_to_left
1018 = skip_typeref(type_left->pointer.points_to);
1019 type_t *points_to_right
1020 = skip_typeref(type_right->pointer.points_to);
1022 /* the left type has all qualifiers from the right type */
1023 unsigned missing_qualifiers
1024 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1025 warningf(source_position,
1026 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1027 orig_type_left, context, orig_type_right, missing_qualifiers);
1031 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1032 warningf(source_position,
1033 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1034 orig_type_left, context, right, orig_type_right);
1037 case ASSIGN_WARNING_POINTER_FROM_INT:
1038 warningf(source_position,
1039 "%s makes pointer '%T' from integer '%T' without a cast",
1040 context, orig_type_left, orig_type_right);
1043 case ASSIGN_WARNING_INT_FROM_POINTER:
1044 warningf(source_position,
1045 "%s makes integer '%T' from pointer '%T' without a cast",
1046 context, orig_type_left, orig_type_right);
1050 panic("invalid error value");
1054 /** Implements the rules from § 6.5.16.1 */
1055 static assign_error_t semantic_assign(type_t *orig_type_left,
1056 const expression_t *const right)
1058 type_t *const orig_type_right = right->base.type;
1059 type_t *const type_left = skip_typeref(orig_type_left);
1060 type_t *const type_right = skip_typeref(orig_type_right);
1062 if (is_type_pointer(type_left)) {
1063 if (is_null_pointer_constant(right)) {
1064 return ASSIGN_SUCCESS;
1065 } else if (is_type_pointer(type_right)) {
1066 type_t *points_to_left
1067 = skip_typeref(type_left->pointer.points_to);
1068 type_t *points_to_right
1069 = skip_typeref(type_right->pointer.points_to);
1070 assign_error_t res = ASSIGN_SUCCESS;
1072 /* the left type has all qualifiers from the right type */
1073 unsigned missing_qualifiers
1074 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1075 if (missing_qualifiers != 0) {
1076 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1079 points_to_left = get_unqualified_type(points_to_left);
1080 points_to_right = get_unqualified_type(points_to_right);
1082 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1083 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1087 if (!types_compatible(points_to_left, points_to_right)) {
1088 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1092 } else if (is_type_integer(type_right)) {
1093 return ASSIGN_WARNING_POINTER_FROM_INT;
1095 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1096 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1097 && is_type_pointer(type_right))) {
1098 return ASSIGN_SUCCESS;
1099 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1100 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1101 type_t *const unqual_type_left = get_unqualified_type(type_left);
1102 type_t *const unqual_type_right = get_unqualified_type(type_right);
1103 if (types_compatible(unqual_type_left, unqual_type_right)) {
1104 return ASSIGN_SUCCESS;
1106 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1107 return ASSIGN_WARNING_INT_FROM_POINTER;
1110 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1111 return ASSIGN_SUCCESS;
1113 return ASSIGN_ERROR_INCOMPATIBLE;
1116 static expression_t *parse_constant_expression(void)
1118 /* start parsing at precedence 7 (conditional expression) */
1119 expression_t *result = parse_sub_expression(7);
1121 if (!is_constant_expression(result)) {
1122 errorf(&result->base.source_position,
1123 "expression '%E' is not constant\n", result);
1129 static expression_t *parse_assignment_expression(void)
1131 /* start parsing at precedence 2 (assignment expression) */
1132 return parse_sub_expression(2);
1135 static type_t *make_global_typedef(const char *name, type_t *type)
1137 symbol_t *const symbol = symbol_table_insert(name);
1139 declaration_t *const declaration = allocate_declaration_zero();
1140 declaration->namespc = NAMESPACE_NORMAL;
1141 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1142 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1143 declaration->type = type;
1144 declaration->symbol = symbol;
1145 declaration->source_position = builtin_source_position;
1146 declaration->implicit = true;
1148 record_declaration(declaration, false);
1150 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1151 typedef_type->typedeft.declaration = declaration;
1153 return typedef_type;
1156 static string_t parse_string_literals(void)
1158 assert(token.type == T_STRING_LITERAL);
1159 string_t result = token.v.string;
1163 while (token.type == T_STRING_LITERAL) {
1164 result = concat_strings(&result, &token.v.string);
1171 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1172 [GNU_AK_CONST] = "const",
1173 [GNU_AK_VOLATILE] = "volatile",
1174 [GNU_AK_CDECL] = "cdecl",
1175 [GNU_AK_STDCALL] = "stdcall",
1176 [GNU_AK_FASTCALL] = "fastcall",
1177 [GNU_AK_DEPRECATED] = "deprecated",
1178 [GNU_AK_NOINLINE] = "noinline",
1179 [GNU_AK_NORETURN] = "noreturn",
1180 [GNU_AK_NAKED] = "naked",
1181 [GNU_AK_PURE] = "pure",
1182 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1183 [GNU_AK_MALLOC] = "malloc",
1184 [GNU_AK_WEAK] = "weak",
1185 [GNU_AK_CONSTRUCTOR] = "constructor",
1186 [GNU_AK_DESTRUCTOR] = "destructor",
1187 [GNU_AK_NOTHROW] = "nothrow",
1188 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1189 [GNU_AK_COMMON] = "common",
1190 [GNU_AK_NOCOMMON] = "nocommon",
1191 [GNU_AK_PACKED] = "packed",
1192 [GNU_AK_SHARED] = "shared",
1193 [GNU_AK_NOTSHARED] = "notshared",
1194 [GNU_AK_USED] = "used",
1195 [GNU_AK_UNUSED] = "unused",
1196 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1197 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1198 [GNU_AK_LONGCALL] = "longcall",
1199 [GNU_AK_SHORTCALL] = "shortcall",
1200 [GNU_AK_LONG_CALL] = "long_call",
1201 [GNU_AK_SHORT_CALL] = "short_call",
1202 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1203 [GNU_AK_INTERRUPT] = "interrupt",
1204 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1205 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1206 [GNU_AK_NESTING] = "nesting",
1207 [GNU_AK_NEAR] = "near",
1208 [GNU_AK_FAR] = "far",
1209 [GNU_AK_SIGNAL] = "signal",
1210 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1211 [GNU_AK_TINY_DATA] = "tiny_data",
1212 [GNU_AK_SAVEALL] = "saveall",
1213 [GNU_AK_FLATTEN] = "flatten",
1214 [GNU_AK_SSEREGPARM] = "sseregparm",
1215 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1216 [GNU_AK_RETURN_TWICE] = "return_twice",
1217 [GNU_AK_MAY_ALIAS] = "may_alias",
1218 [GNU_AK_MS_STRUCT] = "ms_struct",
1219 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1220 [GNU_AK_DLLIMPORT] = "dllimport",
1221 [GNU_AK_DLLEXPORT] = "dllexport",
1222 [GNU_AK_ALIGNED] = "aligned",
1223 [GNU_AK_ALIAS] = "alias",
1224 [GNU_AK_SECTION] = "section",
1225 [GNU_AK_FORMAT] = "format",
1226 [GNU_AK_FORMAT_ARG] = "format_arg",
1227 [GNU_AK_WEAKREF] = "weakref",
1228 [GNU_AK_NONNULL] = "nonnull",
1229 [GNU_AK_TLS_MODEL] = "tls_model",
1230 [GNU_AK_VISIBILITY] = "visibility",
1231 [GNU_AK_REGPARM] = "regparm",
1232 [GNU_AK_MODE] = "mode",
1233 [GNU_AK_MODEL] = "model",
1234 [GNU_AK_TRAP_EXIT] = "trap_exit",
1235 [GNU_AK_SP_SWITCH] = "sp_switch",
1236 [GNU_AK_SENTINEL] = "sentinel"
1240 * compare two string, ignoring double underscores on the second.
1242 static int strcmp_underscore(const char *s1, const char *s2)
1244 if (s2[0] == '_' && s2[1] == '_') {
1245 size_t len2 = strlen(s2);
1246 size_t len1 = strlen(s1);
1247 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1248 return strncmp(s1, s2+2, len2-4);
1252 return strcmp(s1, s2);
1256 * Allocate a new gnu temporal attribute.
1258 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1260 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1261 attribute->kind = kind;
1262 attribute->next = NULL;
1263 attribute->invalid = false;
1264 attribute->have_arguments = false;
1270 * parse one constant expression argument.
1272 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1274 expression_t *expression;
1275 add_anchor_token(')');
1276 expression = parse_constant_expression();
1277 rem_anchor_token(')');
1279 attribute->u.argument = fold_constant(expression);
1282 attribute->invalid = true;
1286 * parse a list of constant expressions arguments.
1288 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1290 argument_list_t **list = &attribute->u.arguments;
1291 argument_list_t *entry;
1292 expression_t *expression;
1293 add_anchor_token(')');
1294 add_anchor_token(',');
1296 expression = parse_constant_expression();
1297 entry = obstack_alloc(&temp_obst, sizeof(entry));
1298 entry->argument = fold_constant(expression);
1301 list = &entry->next;
1302 if (token.type != ',')
1306 rem_anchor_token(',');
1307 rem_anchor_token(')');
1311 attribute->invalid = true;
1315 * parse one string literal argument.
1317 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1320 add_anchor_token('(');
1321 if (token.type != T_STRING_LITERAL) {
1322 parse_error_expected("while parsing attribute directive",
1323 T_STRING_LITERAL, NULL);
1326 *string = parse_string_literals();
1327 rem_anchor_token('(');
1331 attribute->invalid = true;
1335 * parse one tls model.
1337 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1339 static const char *const tls_models[] = {
1345 string_t string = { NULL, 0 };
1346 parse_gnu_attribute_string_arg(attribute, &string);
1347 if (string.begin != NULL) {
1348 for(size_t i = 0; i < 4; ++i) {
1349 if (strcmp(tls_models[i], string.begin) == 0) {
1350 attribute->u.value = i;
1354 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1356 attribute->invalid = true;
1360 * parse one tls model.
1362 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1364 static const char *const visibilities[] = {
1370 string_t string = { NULL, 0 };
1371 parse_gnu_attribute_string_arg(attribute, &string);
1372 if (string.begin != NULL) {
1373 for(size_t i = 0; i < 4; ++i) {
1374 if (strcmp(visibilities[i], string.begin) == 0) {
1375 attribute->u.value = i;
1379 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1381 attribute->invalid = true;
1385 * parse one (code) model.
1387 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1389 static const char *const visibilities[] = {
1394 string_t string = { NULL, 0 };
1395 parse_gnu_attribute_string_arg(attribute, &string);
1396 if (string.begin != NULL) {
1397 for(int i = 0; i < 3; ++i) {
1398 if (strcmp(visibilities[i], string.begin) == 0) {
1399 attribute->u.value = i;
1403 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1405 attribute->invalid = true;
1408 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1410 /* TODO: find out what is allowed here... */
1412 /* at least: byte, word, pointer, list of machine modes
1413 * __XXX___ is interpreted as XXX */
1414 add_anchor_token(')');
1416 if (token.type != T_IDENTIFIER) {
1417 expect(T_IDENTIFIER);
1420 /* This isn't really correct, the backend should provide a list of machine
1421 * specific modes (according to gcc philosophy that is...) */
1422 const char *symbol_str = token.v.symbol->string;
1423 if (strcmp_underscore("QI", symbol_str) == 0 ||
1424 strcmp_underscore("byte", symbol_str) == 0) {
1425 attribute->u.akind = ATOMIC_TYPE_CHAR;
1426 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1427 attribute->u.akind = ATOMIC_TYPE_SHORT;
1428 } else if (strcmp_underscore("SI", symbol_str) == 0
1429 || strcmp_underscore("word", symbol_str) == 0
1430 || strcmp_underscore("pointer", symbol_str) == 0) {
1431 attribute->u.akind = ATOMIC_TYPE_INT;
1432 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1433 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1435 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1436 attribute->invalid = true;
1440 rem_anchor_token(')');
1444 attribute->invalid = true;
1448 * parse one interrupt argument.
1450 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1452 static const char *const interrupts[] = {
1459 string_t string = { NULL, 0 };
1460 parse_gnu_attribute_string_arg(attribute, &string);
1461 if (string.begin != NULL) {
1462 for(size_t i = 0; i < 5; ++i) {
1463 if (strcmp(interrupts[i], string.begin) == 0) {
1464 attribute->u.value = i;
1468 errorf(HERE, "'%s' is not an interrupt", string.begin);
1470 attribute->invalid = true;
1474 * parse ( identifier, const expression, const expression )
1476 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1478 static const char *const format_names[] = {
1486 if (token.type != T_IDENTIFIER) {
1487 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1490 const char *name = token.v.symbol->string;
1491 for(i = 0; i < 4; ++i) {
1492 if (strcmp_underscore(format_names[i], name) == 0)
1496 if (warning.attribute)
1497 warningf(HERE, "'%s' is an unrecognized format function type", name);
1502 add_anchor_token(')');
1503 add_anchor_token(',');
1504 parse_constant_expression();
1505 rem_anchor_token(',');
1506 rem_anchor_token(')');
1509 add_anchor_token(')');
1510 parse_constant_expression();
1511 rem_anchor_token(')');
1515 attribute->u.value = true;
1518 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1520 if (!attribute->have_arguments)
1523 /* should have no arguments */
1524 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1525 eat_until_matching_token('(');
1526 /* we have already consumed '(', so we stop before ')', eat it */
1528 attribute->invalid = true;
1532 * Parse one GNU attribute.
1534 * Note that attribute names can be specified WITH or WITHOUT
1535 * double underscores, ie const or __const__.
1537 * The following attributes are parsed without arguments
1562 * no_instrument_function
1563 * warn_unused_result
1580 * externally_visible
1588 * The following attributes are parsed with arguments
1589 * aligned( const expression )
1590 * alias( string literal )
1591 * section( string literal )
1592 * format( identifier, const expression, const expression )
1593 * format_arg( const expression )
1594 * tls_model( string literal )
1595 * visibility( string literal )
1596 * regparm( const expression )
1597 * model( string leteral )
1598 * trap_exit( const expression )
1599 * sp_switch( string literal )
1601 * The following attributes might have arguments
1602 * weak_ref( string literal )
1603 * non_null( const expression // ',' )
1604 * interrupt( string literal )
1605 * sentinel( constant expression )
1607 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1609 gnu_attribute_t *head = *attributes;
1610 gnu_attribute_t *last = *attributes;
1611 decl_modifiers_t modifiers = 0;
1612 gnu_attribute_t *attribute;
1614 eat(T___attribute__);
1618 if (token.type != ')') {
1619 /* find the end of the list */
1621 while (last->next != NULL)
1625 /* non-empty attribute list */
1628 if (token.type == T_const) {
1630 } else if (token.type == T_volatile) {
1632 } else if (token.type == T_cdecl) {
1633 /* __attribute__((cdecl)), WITH ms mode */
1635 } else if (token.type == T_IDENTIFIER) {
1636 const symbol_t *sym = token.v.symbol;
1639 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1646 for(i = 0; i < GNU_AK_LAST; ++i) {
1647 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1650 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1653 if (kind == GNU_AK_LAST) {
1654 if (warning.attribute)
1655 warningf(HERE, "'%s' attribute directive ignored", name);
1657 /* skip possible arguments */
1658 if (token.type == '(') {
1659 eat_until_matching_token(')');
1662 /* check for arguments */
1663 attribute = allocate_gnu_attribute(kind);
1664 if (token.type == '(') {
1666 if (token.type == ')') {
1667 /* empty args are allowed */
1670 attribute->have_arguments = true;
1675 case GNU_AK_VOLATILE:
1680 case GNU_AK_NOCOMMON:
1682 case GNU_AK_NOTSHARED:
1683 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1684 case GNU_AK_WARN_UNUSED_RESULT:
1685 case GNU_AK_LONGCALL:
1686 case GNU_AK_SHORTCALL:
1687 case GNU_AK_LONG_CALL:
1688 case GNU_AK_SHORT_CALL:
1689 case GNU_AK_FUNCTION_VECTOR:
1690 case GNU_AK_INTERRUPT_HANDLER:
1691 case GNU_AK_NMI_HANDLER:
1692 case GNU_AK_NESTING:
1696 case GNU_AK_EIGTHBIT_DATA:
1697 case GNU_AK_TINY_DATA:
1698 case GNU_AK_SAVEALL:
1699 case GNU_AK_FLATTEN:
1700 case GNU_AK_SSEREGPARM:
1701 case GNU_AK_EXTERNALLY_VISIBLE:
1702 case GNU_AK_RETURN_TWICE:
1703 case GNU_AK_MAY_ALIAS:
1704 case GNU_AK_MS_STRUCT:
1705 case GNU_AK_GCC_STRUCT:
1708 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1709 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1710 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1711 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1712 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1713 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1714 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1715 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1716 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1717 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1718 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1719 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1720 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1721 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1722 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1723 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1724 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1726 case GNU_AK_ALIGNED:
1727 /* __align__ may be used without an argument */
1728 if (attribute->have_arguments) {
1729 parse_gnu_attribute_const_arg(attribute);
1733 case GNU_AK_FORMAT_ARG:
1734 case GNU_AK_REGPARM:
1735 case GNU_AK_TRAP_EXIT:
1736 if (!attribute->have_arguments) {
1737 /* should have arguments */
1738 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1739 attribute->invalid = true;
1741 parse_gnu_attribute_const_arg(attribute);
1744 case GNU_AK_SECTION:
1745 case GNU_AK_SP_SWITCH:
1746 if (!attribute->have_arguments) {
1747 /* should have arguments */
1748 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1749 attribute->invalid = true;
1751 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1754 if (!attribute->have_arguments) {
1755 /* should have arguments */
1756 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1757 attribute->invalid = true;
1759 parse_gnu_attribute_format_args(attribute);
1761 case GNU_AK_WEAKREF:
1762 /* may have one string argument */
1763 if (attribute->have_arguments)
1764 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1766 case GNU_AK_NONNULL:
1767 if (attribute->have_arguments)
1768 parse_gnu_attribute_const_arg_list(attribute);
1770 case GNU_AK_TLS_MODEL:
1771 if (!attribute->have_arguments) {
1772 /* should have arguments */
1773 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1775 parse_gnu_attribute_tls_model_arg(attribute);
1777 case GNU_AK_VISIBILITY:
1778 if (!attribute->have_arguments) {
1779 /* should have arguments */
1780 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1782 parse_gnu_attribute_visibility_arg(attribute);
1785 if (!attribute->have_arguments) {
1786 /* should have arguments */
1787 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1789 parse_gnu_attribute_model_arg(attribute);
1793 if (!attribute->have_arguments) {
1794 /* should have arguments */
1795 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1797 parse_gnu_attribute_mode_arg(attribute);
1800 case GNU_AK_INTERRUPT:
1801 /* may have one string argument */
1802 if (attribute->have_arguments)
1803 parse_gnu_attribute_interrupt_arg(attribute);
1805 case GNU_AK_SENTINEL:
1806 /* may have one string argument */
1807 if (attribute->have_arguments)
1808 parse_gnu_attribute_const_arg(attribute);
1811 /* already handled */
1815 check_no_argument(attribute, name);
1818 if (attribute != NULL) {
1820 last->next = attribute;
1823 head = last = attribute;
1827 if (token.type != ',')
1841 * Parse GNU attributes.
1843 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1845 decl_modifiers_t modifiers = 0;
1848 switch(token.type) {
1849 case T___attribute__:
1850 modifiers |= parse_gnu_attribute(attributes);
1856 if (token.type != T_STRING_LITERAL) {
1857 parse_error_expected("while parsing assembler attribute",
1858 T_STRING_LITERAL, NULL);
1859 eat_until_matching_token('(');
1862 parse_string_literals();
1867 case T_cdecl: modifiers |= DM_CDECL; break;
1868 case T__fastcall: modifiers |= DM_FASTCALL; break;
1869 case T__stdcall: modifiers |= DM_STDCALL; break;
1872 /* TODO record modifier */
1873 warningf(HERE, "Ignoring declaration modifier %K", &token);
1877 default: return modifiers;
1884 static designator_t *parse_designation(void)
1886 designator_t *result = NULL;
1887 designator_t *last = NULL;
1890 designator_t *designator;
1891 switch(token.type) {
1893 designator = allocate_ast_zero(sizeof(designator[0]));
1894 designator->source_position = token.source_position;
1896 add_anchor_token(']');
1897 designator->array_index = parse_constant_expression();
1898 rem_anchor_token(']');
1902 designator = allocate_ast_zero(sizeof(designator[0]));
1903 designator->source_position = token.source_position;
1905 if (token.type != T_IDENTIFIER) {
1906 parse_error_expected("while parsing designator",
1907 T_IDENTIFIER, NULL);
1910 designator->symbol = token.v.symbol;
1918 assert(designator != NULL);
1920 last->next = designator;
1922 result = designator;
1930 static initializer_t *initializer_from_string(array_type_t *type,
1931 const string_t *const string)
1933 /* TODO: check len vs. size of array type */
1936 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1937 initializer->string.string = *string;
1942 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1943 wide_string_t *const string)
1945 /* TODO: check len vs. size of array type */
1948 initializer_t *const initializer =
1949 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1950 initializer->wide_string.string = *string;
1956 * Build an initializer from a given expression.
1958 static initializer_t *initializer_from_expression(type_t *orig_type,
1959 expression_t *expression)
1961 /* TODO check that expression is a constant expression */
1963 /* § 6.7.8.14/15 char array may be initialized by string literals */
1964 type_t *type = skip_typeref(orig_type);
1965 type_t *expr_type_orig = expression->base.type;
1966 type_t *expr_type = skip_typeref(expr_type_orig);
1967 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1968 array_type_t *const array_type = &type->array;
1969 type_t *const element_type = skip_typeref(array_type->element_type);
1971 if (element_type->kind == TYPE_ATOMIC) {
1972 atomic_type_kind_t akind = element_type->atomic.akind;
1973 switch (expression->kind) {
1974 case EXPR_STRING_LITERAL:
1975 if (akind == ATOMIC_TYPE_CHAR
1976 || akind == ATOMIC_TYPE_SCHAR
1977 || akind == ATOMIC_TYPE_UCHAR) {
1978 return initializer_from_string(array_type,
1979 &expression->string.value);
1982 case EXPR_WIDE_STRING_LITERAL: {
1983 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1984 if (get_unqualified_type(element_type) == bare_wchar_type) {
1985 return initializer_from_wide_string(array_type,
1986 &expression->wide_string.value);
1996 assign_error_t error = semantic_assign(type, expression);
1997 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1999 report_assign_error(error, type, expression, "initializer",
2000 &expression->base.source_position);
2002 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2003 result->value.value = create_implicit_cast(expression, type);
2009 * Checks if a given expression can be used as an constant initializer.
2011 static bool is_initializer_constant(const expression_t *expression)
2013 return is_constant_expression(expression)
2014 || is_address_constant(expression);
2018 * Parses an scalar initializer.
2020 * § 6.7.8.11; eat {} without warning
2022 static initializer_t *parse_scalar_initializer(type_t *type,
2023 bool must_be_constant)
2025 /* there might be extra {} hierarchies */
2027 if (token.type == '{') {
2028 warningf(HERE, "extra curly braces around scalar initializer");
2032 } while (token.type == '{');
2035 expression_t *expression = parse_assignment_expression();
2036 if (must_be_constant && !is_initializer_constant(expression)) {
2037 errorf(&expression->base.source_position,
2038 "Initialisation expression '%E' is not constant\n",
2042 initializer_t *initializer = initializer_from_expression(type, expression);
2044 if (initializer == NULL) {
2045 errorf(&expression->base.source_position,
2046 "expression '%E' (type '%T') doesn't match expected type '%T'",
2047 expression, expression->base.type, type);
2052 bool additional_warning_displayed = false;
2053 while (braces > 0) {
2054 if (token.type == ',') {
2057 if (token.type != '}') {
2058 if (!additional_warning_displayed) {
2059 warningf(HERE, "additional elements in scalar initializer");
2060 additional_warning_displayed = true;
2071 * An entry in the type path.
2073 typedef struct type_path_entry_t type_path_entry_t;
2074 struct type_path_entry_t {
2075 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2077 size_t index; /**< For array types: the current index. */
2078 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2083 * A type path expression a position inside compound or array types.
2085 typedef struct type_path_t type_path_t;
2086 struct type_path_t {
2087 type_path_entry_t *path; /**< An flexible array containing the current path. */
2088 type_t *top_type; /**< type of the element the path points */
2089 size_t max_index; /**< largest index in outermost array */
2093 * Prints a type path for debugging.
2095 static __attribute__((unused)) void debug_print_type_path(
2096 const type_path_t *path)
2098 size_t len = ARR_LEN(path->path);
2100 for(size_t i = 0; i < len; ++i) {
2101 const type_path_entry_t *entry = & path->path[i];
2103 type_t *type = skip_typeref(entry->type);
2104 if (is_type_compound(type)) {
2105 /* in gcc mode structs can have no members */
2106 if (entry->v.compound_entry == NULL) {
2110 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2111 } else if (is_type_array(type)) {
2112 fprintf(stderr, "[%zu]", entry->v.index);
2114 fprintf(stderr, "-INVALID-");
2117 if (path->top_type != NULL) {
2118 fprintf(stderr, " (");
2119 print_type(path->top_type);
2120 fprintf(stderr, ")");
2125 * Return the top type path entry, ie. in a path
2126 * (type).a.b returns the b.
2128 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2130 size_t len = ARR_LEN(path->path);
2132 return &path->path[len-1];
2136 * Enlarge the type path by an (empty) element.
2138 static type_path_entry_t *append_to_type_path(type_path_t *path)
2140 size_t len = ARR_LEN(path->path);
2141 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2143 type_path_entry_t *result = & path->path[len];
2144 memset(result, 0, sizeof(result[0]));
2149 * Descending into a sub-type. Enter the scope of the current
2152 static void descend_into_subtype(type_path_t *path)
2154 type_t *orig_top_type = path->top_type;
2155 type_t *top_type = skip_typeref(orig_top_type);
2157 type_path_entry_t *top = append_to_type_path(path);
2158 top->type = top_type;
2160 if (is_type_compound(top_type)) {
2161 declaration_t *declaration = top_type->compound.declaration;
2162 declaration_t *entry = declaration->scope.declarations;
2163 top->v.compound_entry = entry;
2165 if (entry != NULL) {
2166 path->top_type = entry->type;
2168 path->top_type = NULL;
2170 } else if (is_type_array(top_type)) {
2172 path->top_type = top_type->array.element_type;
2174 assert(!is_type_valid(top_type));
2179 * Pop an entry from the given type path, ie. returning from
2180 * (type).a.b to (type).a
2182 static void ascend_from_subtype(type_path_t *path)
2184 type_path_entry_t *top = get_type_path_top(path);
2186 path->top_type = top->type;
2188 size_t len = ARR_LEN(path->path);
2189 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2193 * Pop entries from the given type path until the given
2194 * path level is reached.
2196 static void ascend_to(type_path_t *path, size_t top_path_level)
2198 size_t len = ARR_LEN(path->path);
2200 while (len > top_path_level) {
2201 ascend_from_subtype(path);
2202 len = ARR_LEN(path->path);
2206 static bool walk_designator(type_path_t *path, const designator_t *designator,
2207 bool used_in_offsetof)
2209 for( ; designator != NULL; designator = designator->next) {
2210 type_path_entry_t *top = get_type_path_top(path);
2211 type_t *orig_type = top->type;
2213 type_t *type = skip_typeref(orig_type);
2215 if (designator->symbol != NULL) {
2216 symbol_t *symbol = designator->symbol;
2217 if (!is_type_compound(type)) {
2218 if (is_type_valid(type)) {
2219 errorf(&designator->source_position,
2220 "'.%Y' designator used for non-compound type '%T'",
2226 declaration_t *declaration = type->compound.declaration;
2227 declaration_t *iter = declaration->scope.declarations;
2228 for( ; iter != NULL; iter = iter->next) {
2229 if (iter->symbol == symbol) {
2234 errorf(&designator->source_position,
2235 "'%T' has no member named '%Y'", orig_type, symbol);
2238 if (used_in_offsetof) {
2239 type_t *real_type = skip_typeref(iter->type);
2240 if (real_type->kind == TYPE_BITFIELD) {
2241 errorf(&designator->source_position,
2242 "offsetof designator '%Y' may not specify bitfield",
2248 top->type = orig_type;
2249 top->v.compound_entry = iter;
2250 orig_type = iter->type;
2252 expression_t *array_index = designator->array_index;
2253 assert(designator->array_index != NULL);
2255 if (!is_type_array(type)) {
2256 if (is_type_valid(type)) {
2257 errorf(&designator->source_position,
2258 "[%E] designator used for non-array type '%T'",
2259 array_index, orig_type);
2263 if (!is_type_valid(array_index->base.type)) {
2267 long index = fold_constant(array_index);
2268 if (!used_in_offsetof) {
2270 errorf(&designator->source_position,
2271 "array index [%E] must be positive", array_index);
2274 if (type->array.size_constant == true) {
2275 long array_size = type->array.size;
2276 if (index >= array_size) {
2277 errorf(&designator->source_position,
2278 "designator [%E] (%d) exceeds array size %d",
2279 array_index, index, array_size);
2285 top->type = orig_type;
2286 top->v.index = (size_t) index;
2287 orig_type = type->array.element_type;
2289 path->top_type = orig_type;
2291 if (designator->next != NULL) {
2292 descend_into_subtype(path);
2301 static void advance_current_object(type_path_t *path, size_t top_path_level)
2303 type_path_entry_t *top = get_type_path_top(path);
2305 type_t *type = skip_typeref(top->type);
2306 if (is_type_union(type)) {
2307 /* in unions only the first element is initialized */
2308 top->v.compound_entry = NULL;
2309 } else if (is_type_struct(type)) {
2310 declaration_t *entry = top->v.compound_entry;
2312 entry = entry->next;
2313 top->v.compound_entry = entry;
2314 if (entry != NULL) {
2315 path->top_type = entry->type;
2319 assert(is_type_array(type));
2323 if (!type->array.size_constant || top->v.index < type->array.size) {
2328 /* we're past the last member of the current sub-aggregate, try if we
2329 * can ascend in the type hierarchy and continue with another subobject */
2330 size_t len = ARR_LEN(path->path);
2332 if (len > top_path_level) {
2333 ascend_from_subtype(path);
2334 advance_current_object(path, top_path_level);
2336 path->top_type = NULL;
2341 * skip until token is found.
2343 static void skip_until(int type)
2345 while (token.type != type) {
2346 if (token.type == T_EOF)
2353 * skip any {...} blocks until a closing bracket is reached.
2355 static void skip_initializers(void)
2357 if (token.type == '{')
2360 while (token.type != '}') {
2361 if (token.type == T_EOF)
2363 if (token.type == '{') {
2371 static initializer_t *create_empty_initializer(void)
2373 static initializer_t empty_initializer
2374 = { .list = { { INITIALIZER_LIST }, 0 } };
2375 return &empty_initializer;
2379 * Parse a part of an initialiser for a struct or union,
2381 static initializer_t *parse_sub_initializer(type_path_t *path,
2382 type_t *outer_type, size_t top_path_level,
2383 parse_initializer_env_t *env)
2385 if (token.type == '}') {
2386 /* empty initializer */
2387 return create_empty_initializer();
2390 type_t *orig_type = path->top_type;
2391 type_t *type = NULL;
2393 if (orig_type == NULL) {
2394 /* We are initializing an empty compound. */
2396 type = skip_typeref(orig_type);
2398 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2399 * initializers in this case. */
2400 if (!is_type_valid(type)) {
2401 skip_initializers();
2402 return create_empty_initializer();
2406 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2409 designator_t *designator = NULL;
2410 if (token.type == '.' || token.type == '[') {
2411 designator = parse_designation();
2412 goto finish_designator;
2413 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2414 /* GNU-style designator ("identifier: value") */
2415 designator = allocate_ast_zero(sizeof(designator[0]));
2416 designator->source_position = token.source_position;
2417 designator->symbol = token.v.symbol;
2422 /* reset path to toplevel, evaluate designator from there */
2423 ascend_to(path, top_path_level);
2424 if (!walk_designator(path, designator, false)) {
2425 /* can't continue after designation error */
2429 initializer_t *designator_initializer
2430 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2431 designator_initializer->designator.designator = designator;
2432 ARR_APP1(initializer_t*, initializers, designator_initializer);
2434 orig_type = path->top_type;
2435 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2440 if (token.type == '{') {
2441 if (type != NULL && is_type_scalar(type)) {
2442 sub = parse_scalar_initializer(type, env->must_be_constant);
2446 if (env->declaration != NULL) {
2447 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2448 env->declaration->symbol);
2450 errorf(HERE, "extra brace group at end of initializer");
2453 descend_into_subtype(path);
2455 add_anchor_token('}');
2456 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2458 rem_anchor_token('}');
2461 ascend_from_subtype(path);
2465 goto error_parse_next;
2469 /* must be an expression */
2470 expression_t *expression = parse_assignment_expression();
2472 if (env->must_be_constant && !is_initializer_constant(expression)) {
2473 errorf(&expression->base.source_position,
2474 "Initialisation expression '%E' is not constant\n",
2479 /* we are already outside, ... */
2480 if (is_type_compound(outer_type) &&
2481 !outer_type->compound.declaration->init.complete) {
2482 goto error_parse_next;
2487 /* handle { "string" } special case */
2488 if ((expression->kind == EXPR_STRING_LITERAL
2489 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2490 && outer_type != NULL) {
2491 sub = initializer_from_expression(outer_type, expression);
2493 if (token.type == ',') {
2496 if (token.type != '}') {
2497 warningf(HERE, "excessive elements in initializer for type '%T'",
2500 /* TODO: eat , ... */
2505 /* descend into subtypes until expression matches type */
2507 orig_type = path->top_type;
2508 type = skip_typeref(orig_type);
2510 sub = initializer_from_expression(orig_type, expression);
2514 if (!is_type_valid(type)) {
2517 if (is_type_scalar(type)) {
2518 errorf(&expression->base.source_position,
2519 "expression '%E' doesn't match expected type '%T'",
2520 expression, orig_type);
2524 descend_into_subtype(path);
2528 /* update largest index of top array */
2529 const type_path_entry_t *first = &path->path[0];
2530 type_t *first_type = first->type;
2531 first_type = skip_typeref(first_type);
2532 if (is_type_array(first_type)) {
2533 size_t index = first->v.index;
2534 if (index > path->max_index)
2535 path->max_index = index;
2539 /* append to initializers list */
2540 ARR_APP1(initializer_t*, initializers, sub);
2543 if (env->declaration != NULL)
2544 warningf(HERE, "excess elements in struct initializer for '%Y'",
2545 env->declaration->symbol);
2547 warningf(HERE, "excess elements in struct initializer");
2551 if (token.type == '}') {
2555 if (token.type == '}') {
2560 /* advance to the next declaration if we are not at the end */
2561 advance_current_object(path, top_path_level);
2562 orig_type = path->top_type;
2563 if (orig_type != NULL)
2564 type = skip_typeref(orig_type);
2570 size_t len = ARR_LEN(initializers);
2571 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2572 initializer_t *result = allocate_ast_zero(size);
2573 result->kind = INITIALIZER_LIST;
2574 result->list.len = len;
2575 memcpy(&result->list.initializers, initializers,
2576 len * sizeof(initializers[0]));
2578 DEL_ARR_F(initializers);
2579 ascend_to(path, top_path_level+1);
2584 skip_initializers();
2585 DEL_ARR_F(initializers);
2586 ascend_to(path, top_path_level+1);
2591 * Parses an initializer. Parsers either a compound literal
2592 * (env->declaration == NULL) or an initializer of a declaration.
2594 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2596 type_t *type = skip_typeref(env->type);
2597 initializer_t *result = NULL;
2600 if (is_type_scalar(type)) {
2601 result = parse_scalar_initializer(type, env->must_be_constant);
2602 } else if (token.type == '{') {
2606 memset(&path, 0, sizeof(path));
2607 path.top_type = env->type;
2608 path.path = NEW_ARR_F(type_path_entry_t, 0);
2610 descend_into_subtype(&path);
2612 add_anchor_token('}');
2613 result = parse_sub_initializer(&path, env->type, 1, env);
2614 rem_anchor_token('}');
2616 max_index = path.max_index;
2617 DEL_ARR_F(path.path);
2621 /* parse_scalar_initializer() also works in this case: we simply
2622 * have an expression without {} around it */
2623 result = parse_scalar_initializer(type, env->must_be_constant);
2626 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2627 * the array type size */
2628 if (is_type_array(type) && type->array.size_expression == NULL
2629 && result != NULL) {
2631 switch (result->kind) {
2632 case INITIALIZER_LIST:
2633 size = max_index + 1;
2636 case INITIALIZER_STRING:
2637 size = result->string.string.size;
2640 case INITIALIZER_WIDE_STRING:
2641 size = result->wide_string.string.size;
2644 case INITIALIZER_DESIGNATOR:
2645 case INITIALIZER_VALUE:
2646 /* can happen for parse errors */
2651 internal_errorf(HERE, "invalid initializer type");
2654 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2655 cnst->base.type = type_size_t;
2656 cnst->conste.v.int_value = size;
2658 type_t *new_type = duplicate_type(type);
2660 new_type->array.size_expression = cnst;
2661 new_type->array.size_constant = true;
2662 new_type->array.size = size;
2663 env->type = new_type;
2671 static declaration_t *append_declaration(declaration_t *declaration);
2673 static declaration_t *parse_compound_type_specifier(bool is_struct)
2675 gnu_attribute_t *attributes = NULL;
2676 decl_modifiers_t modifiers = 0;
2683 symbol_t *symbol = NULL;
2684 declaration_t *declaration = NULL;
2686 if (token.type == T___attribute__) {
2687 modifiers |= parse_attributes(&attributes);
2690 if (token.type == T_IDENTIFIER) {
2691 symbol = token.v.symbol;
2694 namespace_t const namespc =
2695 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2696 declaration = get_declaration(symbol, namespc);
2697 if (declaration != NULL) {
2698 if (declaration->parent_scope != scope &&
2699 (token.type == '{' || token.type == ';')) {
2701 } else if (declaration->init.complete &&
2702 token.type == '{') {
2703 assert(symbol != NULL);
2704 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2705 is_struct ? "struct" : "union", symbol,
2706 &declaration->source_position);
2707 declaration->scope.declarations = NULL;
2710 } else if (token.type != '{') {
2712 parse_error_expected("while parsing struct type specifier",
2713 T_IDENTIFIER, '{', NULL);
2715 parse_error_expected("while parsing union type specifier",
2716 T_IDENTIFIER, '{', NULL);
2722 if (declaration == NULL) {
2723 declaration = allocate_declaration_zero();
2724 declaration->namespc =
2725 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2726 declaration->source_position = token.source_position;
2727 declaration->symbol = symbol;
2728 declaration->parent_scope = scope;
2729 if (symbol != NULL) {
2730 environment_push(declaration);
2732 append_declaration(declaration);
2735 if (token.type == '{') {
2736 declaration->init.complete = true;
2738 parse_compound_type_entries(declaration);
2739 modifiers |= parse_attributes(&attributes);
2742 declaration->modifiers |= modifiers;
2746 static void parse_enum_entries(type_t *const enum_type)
2750 if (token.type == '}') {
2752 errorf(HERE, "empty enum not allowed");
2756 add_anchor_token('}');
2758 if (token.type != T_IDENTIFIER) {
2759 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2761 rem_anchor_token('}');
2765 declaration_t *const entry = allocate_declaration_zero();
2766 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2767 entry->type = enum_type;
2768 entry->symbol = token.v.symbol;
2769 entry->source_position = token.source_position;
2772 if (token.type == '=') {
2774 expression_t *value = parse_constant_expression();
2776 value = create_implicit_cast(value, enum_type);
2777 entry->init.enum_value = value;
2782 record_declaration(entry, false);
2784 if (token.type != ',')
2787 } while (token.type != '}');
2788 rem_anchor_token('}');
2796 static type_t *parse_enum_specifier(void)
2798 gnu_attribute_t *attributes = NULL;
2799 declaration_t *declaration;
2803 if (token.type == T_IDENTIFIER) {
2804 symbol = token.v.symbol;
2807 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2808 } else if (token.type != '{') {
2809 parse_error_expected("while parsing enum type specifier",
2810 T_IDENTIFIER, '{', NULL);
2817 if (declaration == NULL) {
2818 declaration = allocate_declaration_zero();
2819 declaration->namespc = NAMESPACE_ENUM;
2820 declaration->source_position = token.source_position;
2821 declaration->symbol = symbol;
2822 declaration->parent_scope = scope;
2825 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2826 type->enumt.declaration = declaration;
2828 if (token.type == '{') {
2829 if (declaration->init.complete) {
2830 errorf(HERE, "multiple definitions of enum %Y", symbol);
2832 if (symbol != NULL) {
2833 environment_push(declaration);
2835 append_declaration(declaration);
2836 declaration->init.complete = true;
2838 parse_enum_entries(type);
2839 parse_attributes(&attributes);
2846 * if a symbol is a typedef to another type, return true
2848 static bool is_typedef_symbol(symbol_t *symbol)
2850 const declaration_t *const declaration =
2851 get_declaration(symbol, NAMESPACE_NORMAL);
2853 declaration != NULL &&
2854 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2857 static type_t *parse_typeof(void)
2864 add_anchor_token(')');
2866 expression_t *expression = NULL;
2868 bool old_type_prop = in_type_prop;
2869 bool old_gcc_extension = in_gcc_extension;
2870 in_type_prop = true;
2872 while (token.type == T___extension__) {
2873 /* This can be a prefix to a typename or an expression. We simply eat
2876 in_gcc_extension = true;
2878 switch (token.type) {
2880 if (is_typedef_symbol(token.v.symbol)) {
2881 type = parse_typename();
2883 expression = parse_expression();
2884 type = expression->base.type;
2889 type = parse_typename();
2893 expression = parse_expression();
2894 type = expression->base.type;
2897 in_type_prop = old_type_prop;
2898 in_gcc_extension = old_gcc_extension;
2900 rem_anchor_token(')');
2903 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2904 typeof_type->typeoft.expression = expression;
2905 typeof_type->typeoft.typeof_type = type;
2912 typedef enum specifiers_t {
2913 SPECIFIER_SIGNED = 1 << 0,
2914 SPECIFIER_UNSIGNED = 1 << 1,
2915 SPECIFIER_LONG = 1 << 2,
2916 SPECIFIER_INT = 1 << 3,
2917 SPECIFIER_DOUBLE = 1 << 4,
2918 SPECIFIER_CHAR = 1 << 5,
2919 SPECIFIER_SHORT = 1 << 6,
2920 SPECIFIER_LONG_LONG = 1 << 7,
2921 SPECIFIER_FLOAT = 1 << 8,
2922 SPECIFIER_BOOL = 1 << 9,
2923 SPECIFIER_VOID = 1 << 10,
2924 SPECIFIER_INT8 = 1 << 11,
2925 SPECIFIER_INT16 = 1 << 12,
2926 SPECIFIER_INT32 = 1 << 13,
2927 SPECIFIER_INT64 = 1 << 14,
2928 SPECIFIER_INT128 = 1 << 15,
2929 SPECIFIER_COMPLEX = 1 << 16,
2930 SPECIFIER_IMAGINARY = 1 << 17,
2933 static type_t *create_builtin_type(symbol_t *const symbol,
2934 type_t *const real_type)
2936 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2937 type->builtin.symbol = symbol;
2938 type->builtin.real_type = real_type;
2940 type_t *result = typehash_insert(type);
2941 if (type != result) {
2948 static type_t *get_typedef_type(symbol_t *symbol)
2950 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2951 if (declaration == NULL ||
2952 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2955 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2956 type->typedeft.declaration = declaration;
2962 * check for the allowed MS alignment values.
2964 static bool check_alignment_value(long long intvalue)
2966 if (intvalue < 1 || intvalue > 8192) {
2967 errorf(HERE, "illegal alignment value");
2970 unsigned v = (unsigned)intvalue;
2971 for(unsigned i = 1; i <= 8192; i += i) {
2975 errorf(HERE, "alignment must be power of two");
2979 #define DET_MOD(name, tag) do { \
2980 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2981 *modifiers |= tag; \
2984 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2986 decl_modifiers_t *modifiers = &specifiers->modifiers;
2989 if (token.type == T_restrict) {
2991 DET_MOD(restrict, DM_RESTRICT);
2993 } else if (token.type != T_IDENTIFIER)
2995 symbol_t *symbol = token.v.symbol;
2996 if (symbol == sym_align) {
2999 if (token.type != T_INTEGER)
3001 if (check_alignment_value(token.v.intvalue)) {
3002 if (specifiers->alignment != 0)
3003 warningf(HERE, "align used more than once");
3004 specifiers->alignment = (unsigned char)token.v.intvalue;
3008 } else if (symbol == sym_allocate) {
3011 if (token.type != T_IDENTIFIER)
3013 (void)token.v.symbol;
3015 } else if (symbol == sym_dllimport) {
3017 DET_MOD(dllimport, DM_DLLIMPORT);
3018 } else if (symbol == sym_dllexport) {
3020 DET_MOD(dllexport, DM_DLLEXPORT);
3021 } else if (symbol == sym_thread) {
3023 DET_MOD(thread, DM_THREAD);
3024 } else if (symbol == sym_naked) {
3026 DET_MOD(naked, DM_NAKED);
3027 } else if (symbol == sym_noinline) {
3029 DET_MOD(noinline, DM_NOINLINE);
3030 } else if (symbol == sym_noreturn) {
3032 DET_MOD(noreturn, DM_NORETURN);
3033 } else if (symbol == sym_nothrow) {
3035 DET_MOD(nothrow, DM_NOTHROW);
3036 } else if (symbol == sym_novtable) {
3038 DET_MOD(novtable, DM_NOVTABLE);
3039 } else if (symbol == sym_property) {
3043 bool is_get = false;
3044 if (token.type != T_IDENTIFIER)
3046 if (token.v.symbol == sym_get) {
3048 } else if (token.v.symbol == sym_put) {
3050 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3055 if (token.type != T_IDENTIFIER)
3058 if (specifiers->get_property_sym != NULL) {
3059 errorf(HERE, "get property name already specified");
3061 specifiers->get_property_sym = token.v.symbol;
3064 if (specifiers->put_property_sym != NULL) {
3065 errorf(HERE, "put property name already specified");
3067 specifiers->put_property_sym = token.v.symbol;
3071 if (token.type == ',') {
3078 } else if (symbol == sym_selectany) {
3080 DET_MOD(selectany, DM_SELECTANY);
3081 } else if (symbol == sym_uuid) {
3084 if (token.type != T_STRING_LITERAL)
3088 } else if (symbol == sym_deprecated) {
3090 if (specifiers->deprecated != 0)
3091 warningf(HERE, "deprecated used more than once");
3092 specifiers->deprecated = 1;
3093 if (token.type == '(') {
3095 if (token.type == T_STRING_LITERAL) {
3096 specifiers->deprecated_string = token.v.string.begin;
3099 errorf(HERE, "string literal expected");
3103 } else if (symbol == sym_noalias) {
3105 DET_MOD(noalias, DM_NOALIAS);
3107 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3109 if (token.type == '(')
3113 if (token.type == ',')
3120 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3122 declaration_t *const decl = allocate_declaration_zero();
3123 decl->source_position = *HERE;
3124 decl->declared_storage_class = storage_class;
3125 decl->storage_class =
3126 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3127 storage_class : STORAGE_CLASS_AUTO;
3128 decl->symbol = symbol;
3129 decl->implicit = true;
3130 record_declaration(decl, false);
3135 * Finish the construction of a struct type by calculating
3136 * its size, offsets, alignment.
3138 static void finish_struct_type(compound_type_t *type) {
3139 if (type->declaration == NULL)
3141 declaration_t *struct_decl = type->declaration;
3142 if (! struct_decl->init.complete)
3147 il_alignment_t alignment = 1;
3148 bool need_pad = false;
3150 declaration_t *entry = struct_decl->scope.declarations;
3151 for (; entry != NULL; entry = entry->next) {
3152 if (entry->namespc != NAMESPACE_NORMAL)
3155 type_t *m_type = skip_typeref(entry->type);
3156 if (! is_type_valid(m_type)) {
3157 /* simply ignore errors here */
3160 il_alignment_t m_alignment = m_type->base.alignment;
3161 if (m_alignment > alignment)
3162 alignment = m_alignment;
3164 offset = (size + m_alignment - 1) & -m_alignment;
3168 entry->offset = offset;
3169 size = offset + m_type->base.size;
3171 if (type->base.alignment != 0) {
3172 alignment = type->base.alignment;
3175 offset = (size + alignment - 1) & -alignment;
3179 if (warning.padded && need_pad) {
3180 warningf(&struct_decl->source_position,
3181 "'%#T' needs padding", type, struct_decl->symbol);
3183 if (warning.packed && !need_pad) {
3184 warningf(&struct_decl->source_position,
3185 "superfluous packed attribute on '%#T'",
3186 type, struct_decl->symbol);
3189 type->base.size = offset;
3190 type->base.alignment = alignment;
3194 * Finish the construction of an union type by calculating
3195 * its size and alignment.
3197 static void finish_union_type(compound_type_t *type) {
3198 if (type->declaration == NULL)
3200 declaration_t *union_decl = type->declaration;
3201 if (! union_decl->init.complete)
3205 il_alignment_t alignment = 1;
3207 declaration_t *entry = union_decl->scope.declarations;
3208 for (; entry != NULL; entry = entry->next) {
3209 if (entry->namespc != NAMESPACE_NORMAL)
3212 type_t *m_type = skip_typeref(entry->type);
3213 if (! is_type_valid(m_type))
3217 if (m_type->base.size > size)
3218 size = m_type->base.size;
3219 if (m_type->base.alignment > alignment)
3220 alignment = m_type->base.alignment;
3222 if (type->base.alignment != 0) {
3223 alignment = type->base.alignment;
3225 size = (size + alignment - 1) & -alignment;
3226 type->base.size = size;
3227 type->base.alignment = alignment;
3230 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3232 type_t *type = NULL;
3233 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3234 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3235 unsigned type_specifiers = 0;
3236 bool newtype = false;
3237 bool saw_error = false;
3238 bool old_gcc_extension = in_gcc_extension;
3240 specifiers->source_position = token.source_position;
3243 specifiers->modifiers
3244 |= parse_attributes(&specifiers->gnu_attributes);
3245 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3246 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3248 switch (token.type) {
3251 #define MATCH_STORAGE_CLASS(token, class) \
3253 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3254 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3256 specifiers->declared_storage_class = class; \
3260 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3261 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3262 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3263 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3264 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3269 add_anchor_token(')');
3270 parse_microsoft_extended_decl_modifier(specifiers);
3271 rem_anchor_token(')');
3276 switch (specifiers->declared_storage_class) {
3277 case STORAGE_CLASS_NONE:
3278 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3281 case STORAGE_CLASS_EXTERN:
3282 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3285 case STORAGE_CLASS_STATIC:
3286 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3290 errorf(HERE, "multiple storage classes in declaration specifiers");
3296 /* type qualifiers */
3297 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3299 qualifiers |= qualifier; \
3303 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3304 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3305 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3306 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3307 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3308 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3309 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3310 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3312 case T___extension__:
3314 in_gcc_extension = true;
3317 /* type specifiers */
3318 #define MATCH_SPECIFIER(token, specifier, name) \
3321 if (type_specifiers & specifier) { \
3322 errorf(HERE, "multiple " name " type specifiers given"); \
3324 type_specifiers |= specifier; \
3328 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3329 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3330 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3331 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3332 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3333 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3334 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3335 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3336 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3337 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3338 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3339 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3340 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3341 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3342 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3343 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3345 case T__forceinline:
3346 /* only in microsoft mode */
3347 specifiers->modifiers |= DM_FORCEINLINE;
3352 specifiers->is_inline = true;
3357 if (type_specifiers & SPECIFIER_LONG_LONG) {
3358 errorf(HERE, "multiple type specifiers given");
3359 } else if (type_specifiers & SPECIFIER_LONG) {
3360 type_specifiers |= SPECIFIER_LONG_LONG;
3362 type_specifiers |= SPECIFIER_LONG;
3367 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3369 type->compound.declaration = parse_compound_type_specifier(true);
3370 finish_struct_type(&type->compound);
3374 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3375 type->compound.declaration = parse_compound_type_specifier(false);
3376 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3377 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3379 finish_union_type(&type->compound);
3382 type = parse_enum_specifier();
3385 type = parse_typeof();
3387 case T___builtin_va_list:
3388 type = duplicate_type(type_valist);
3392 case T_IDENTIFIER: {
3393 /* only parse identifier if we haven't found a type yet */
3394 if (type != NULL || type_specifiers != 0) {
3395 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3396 * declaration, so it doesn't generate errors about expecting '(' or
3398 switch (look_ahead(1)->type) {
3405 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3408 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3413 goto finish_specifiers;
3417 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3418 if (typedef_type == NULL) {
3419 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3420 * declaration, so it doesn't generate 'implicit int' followed by more
3421 * errors later on. */
3422 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3427 errorf(HERE, "%K does not name a type", &token);
3429 declaration_t *const decl =
3430 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3432 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3433 type->typedeft.declaration = decl;
3437 if (la1_type == '*')
3438 goto finish_specifiers;
3443 goto finish_specifiers;
3448 type = typedef_type;
3452 /* function specifier */
3454 goto finish_specifiers;
3459 in_gcc_extension = old_gcc_extension;
3461 if (type == NULL || (saw_error && type_specifiers != 0)) {
3462 atomic_type_kind_t atomic_type;
3464 /* match valid basic types */
3465 switch(type_specifiers) {
3466 case SPECIFIER_VOID:
3467 atomic_type = ATOMIC_TYPE_VOID;
3469 case SPECIFIER_CHAR:
3470 atomic_type = ATOMIC_TYPE_CHAR;
3472 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3473 atomic_type = ATOMIC_TYPE_SCHAR;
3475 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3476 atomic_type = ATOMIC_TYPE_UCHAR;
3478 case SPECIFIER_SHORT:
3479 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3480 case SPECIFIER_SHORT | SPECIFIER_INT:
3481 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3482 atomic_type = ATOMIC_TYPE_SHORT;
3484 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3485 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3486 atomic_type = ATOMIC_TYPE_USHORT;
3489 case SPECIFIER_SIGNED:
3490 case SPECIFIER_SIGNED | SPECIFIER_INT:
3491 atomic_type = ATOMIC_TYPE_INT;
3493 case SPECIFIER_UNSIGNED:
3494 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3495 atomic_type = ATOMIC_TYPE_UINT;
3497 case SPECIFIER_LONG:
3498 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3499 case SPECIFIER_LONG | SPECIFIER_INT:
3500 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3501 atomic_type = ATOMIC_TYPE_LONG;
3503 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3504 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3505 atomic_type = ATOMIC_TYPE_ULONG;
3508 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3509 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3510 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3511 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3513 atomic_type = ATOMIC_TYPE_LONGLONG;
3514 goto warn_about_long_long;
3516 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3517 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3519 atomic_type = ATOMIC_TYPE_ULONGLONG;
3520 warn_about_long_long:
3521 if (warning.long_long) {
3522 warningf(&specifiers->source_position,
3523 "ISO C90 does not support 'long long'");
3527 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3528 atomic_type = unsigned_int8_type_kind;
3531 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3532 atomic_type = unsigned_int16_type_kind;
3535 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3536 atomic_type = unsigned_int32_type_kind;
3539 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3540 atomic_type = unsigned_int64_type_kind;
3543 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3544 atomic_type = unsigned_int128_type_kind;
3547 case SPECIFIER_INT8:
3548 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3549 atomic_type = int8_type_kind;
3552 case SPECIFIER_INT16:
3553 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3554 atomic_type = int16_type_kind;
3557 case SPECIFIER_INT32:
3558 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3559 atomic_type = int32_type_kind;
3562 case SPECIFIER_INT64:
3563 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3564 atomic_type = int64_type_kind;
3567 case SPECIFIER_INT128:
3568 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3569 atomic_type = int128_type_kind;
3572 case SPECIFIER_FLOAT:
3573 atomic_type = ATOMIC_TYPE_FLOAT;
3575 case SPECIFIER_DOUBLE:
3576 atomic_type = ATOMIC_TYPE_DOUBLE;
3578 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3579 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3581 case SPECIFIER_BOOL:
3582 atomic_type = ATOMIC_TYPE_BOOL;
3584 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3585 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3586 atomic_type = ATOMIC_TYPE_FLOAT;
3588 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3589 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3590 atomic_type = ATOMIC_TYPE_DOUBLE;
3592 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3593 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3594 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3597 /* invalid specifier combination, give an error message */
3598 if (type_specifiers == 0) {
3603 if (warning.implicit_int) {
3604 warningf(HERE, "no type specifiers in declaration, using 'int'");
3606 atomic_type = ATOMIC_TYPE_INT;
3609 errorf(HERE, "no type specifiers given in declaration");
3611 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3612 (type_specifiers & SPECIFIER_UNSIGNED)) {
3613 errorf(HERE, "signed and unsigned specifiers given");
3614 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3615 errorf(HERE, "only integer types can be signed or unsigned");
3617 errorf(HERE, "multiple datatypes in declaration");
3622 if (type_specifiers & SPECIFIER_COMPLEX) {
3623 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3624 type->complex.akind = atomic_type;
3625 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3626 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3627 type->imaginary.akind = atomic_type;
3629 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3630 type->atomic.akind = atomic_type;
3633 } else if (type_specifiers != 0) {
3634 errorf(HERE, "multiple datatypes in declaration");
3637 /* FIXME: check type qualifiers here */
3639 type->base.qualifiers = qualifiers;
3640 type->base.modifiers = modifiers;
3642 type_t *result = typehash_insert(type);
3643 if (newtype && result != type) {
3647 specifiers->type = result;
3651 specifiers->type = type_error_type;
3655 static type_qualifiers_t parse_type_qualifiers(void)
3657 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3660 switch(token.type) {
3661 /* type qualifiers */
3662 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3663 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3664 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3665 /* microsoft extended type modifiers */
3666 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3667 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3668 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3669 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3670 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3678 static declaration_t *parse_identifier_list(void)
3680 declaration_t *declarations = NULL;
3681 declaration_t *last_declaration = NULL;
3683 declaration_t *const declaration = allocate_declaration_zero();
3684 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3685 declaration->source_position = token.source_position;
3686 declaration->symbol = token.v.symbol;
3689 if (last_declaration != NULL) {
3690 last_declaration->next = declaration;
3692 declarations = declaration;
3694 last_declaration = declaration;
3696 if (token.type != ',') {
3700 } while (token.type == T_IDENTIFIER);
3702 return declarations;
3705 static type_t *automatic_type_conversion(type_t *orig_type);
3707 static void semantic_parameter(declaration_t *declaration)
3709 /* TODO: improve error messages */
3710 source_position_t const* const pos = &declaration->source_position;
3712 switch (declaration->declared_storage_class) {
3713 case STORAGE_CLASS_TYPEDEF:
3714 errorf(pos, "typedef not allowed in parameter list");
3717 /* Allowed storage classes */
3718 case STORAGE_CLASS_NONE:
3719 case STORAGE_CLASS_REGISTER:
3723 errorf(pos, "parameter may only have none or register storage class");
3727 type_t *const orig_type = declaration->type;
3728 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3729 * sugar. Turn it into a pointer.
3730 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3731 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3733 type_t *const type = automatic_type_conversion(orig_type);
3734 declaration->type = type;
3736 if (is_type_incomplete(skip_typeref(type))) {
3737 errorf(pos, "parameter '%#T' is of incomplete type",
3738 orig_type, declaration->symbol);
3742 static declaration_t *parse_parameter(void)
3744 declaration_specifiers_t specifiers;
3745 memset(&specifiers, 0, sizeof(specifiers));
3747 parse_declaration_specifiers(&specifiers);
3749 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3754 static declaration_t *parse_parameters(function_type_t *type)
3756 declaration_t *declarations = NULL;
3759 add_anchor_token(')');
3760 int saved_comma_state = save_and_reset_anchor_state(',');
3762 if (token.type == T_IDENTIFIER &&
3763 !is_typedef_symbol(token.v.symbol)) {
3764 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3765 if (la1_type == ',' || la1_type == ')') {
3766 type->kr_style_parameters = true;
3767 declarations = parse_identifier_list();
3768 goto parameters_finished;
3772 if (token.type == ')') {
3773 type->unspecified_parameters = 1;
3774 goto parameters_finished;
3777 declaration_t *declaration;
3778 declaration_t *last_declaration = NULL;
3779 function_parameter_t *parameter;
3780 function_parameter_t *last_parameter = NULL;
3783 switch(token.type) {
3787 goto parameters_finished;
3790 case T___extension__:
3792 declaration = parse_parameter();
3794 /* func(void) is not a parameter */
3795 if (last_parameter == NULL
3796 && token.type == ')'
3797 && declaration->symbol == NULL
3798 && skip_typeref(declaration->type) == type_void) {
3799 goto parameters_finished;
3801 semantic_parameter(declaration);
3803 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3804 memset(parameter, 0, sizeof(parameter[0]));
3805 parameter->type = declaration->type;
3807 if (last_parameter != NULL) {
3808 last_declaration->next = declaration;
3809 last_parameter->next = parameter;
3811 type->parameters = parameter;
3812 declarations = declaration;
3814 last_parameter = parameter;
3815 last_declaration = declaration;
3819 goto parameters_finished;
3821 if (token.type != ',') {
3822 goto parameters_finished;
3828 parameters_finished:
3829 rem_anchor_token(')');
3832 restore_anchor_state(',', saved_comma_state);
3833 return declarations;
3836 restore_anchor_state(',', saved_comma_state);
3840 typedef enum construct_type_kind_t {
3845 } construct_type_kind_t;
3847 typedef struct construct_type_t construct_type_t;
3848 struct construct_type_t {
3849 construct_type_kind_t kind;
3850 construct_type_t *next;
3853 typedef struct parsed_pointer_t parsed_pointer_t;
3854 struct parsed_pointer_t {
3855 construct_type_t construct_type;
3856 type_qualifiers_t type_qualifiers;
3859 typedef struct construct_function_type_t construct_function_type_t;
3860 struct construct_function_type_t {
3861 construct_type_t construct_type;
3862 type_t *function_type;
3865 typedef struct parsed_array_t parsed_array_t;
3866 struct parsed_array_t {
3867 construct_type_t construct_type;
3868 type_qualifiers_t type_qualifiers;
3874 typedef struct construct_base_type_t construct_base_type_t;
3875 struct construct_base_type_t {
3876 construct_type_t construct_type;
3880 static construct_type_t *parse_pointer_declarator(void)
3884 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3885 memset(pointer, 0, sizeof(pointer[0]));
3886 pointer->construct_type.kind = CONSTRUCT_POINTER;
3887 pointer->type_qualifiers = parse_type_qualifiers();
3889 return (construct_type_t*) pointer;
3892 static construct_type_t *parse_array_declarator(void)
3895 add_anchor_token(']');
3897 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3898 memset(array, 0, sizeof(array[0]));
3899 array->construct_type.kind = CONSTRUCT_ARRAY;
3901 if (token.type == T_static) {
3902 array->is_static = true;
3906 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3907 if (type_qualifiers != 0) {
3908 if (token.type == T_static) {
3909 array->is_static = true;
3913 array->type_qualifiers = type_qualifiers;
3915 if (token.type == '*' && look_ahead(1)->type == ']') {
3916 array->is_variable = true;
3918 } else if (token.type != ']') {
3919 array->size = parse_assignment_expression();
3922 rem_anchor_token(']');
3926 return (construct_type_t*) array;
3929 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3932 if (declaration != NULL) {
3933 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3935 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3937 if (mask & (mask-1)) {
3938 const char *first = NULL, *second = NULL;
3940 /* more than one calling convention set */
3941 if (declaration->modifiers & DM_CDECL) {
3942 if (first == NULL) first = "cdecl";
3943 else if (second == NULL) second = "cdecl";
3945 if (declaration->modifiers & DM_STDCALL) {
3946 if (first == NULL) first = "stdcall";
3947 else if (second == NULL) second = "stdcall";
3949 if (declaration->modifiers & DM_FASTCALL) {
3950 if (first == NULL) first = "fastcall";
3951 else if (second == NULL) second = "fastcall";
3953 if (declaration->modifiers & DM_THISCALL) {
3954 if (first == NULL) first = "thiscall";
3955 else if (second == NULL) second = "thiscall";
3957 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3960 if (declaration->modifiers & DM_CDECL)
3961 type->function.calling_convention = CC_CDECL;
3962 else if (declaration->modifiers & DM_STDCALL)
3963 type->function.calling_convention = CC_STDCALL;
3964 else if (declaration->modifiers & DM_FASTCALL)
3965 type->function.calling_convention = CC_FASTCALL;
3966 else if (declaration->modifiers & DM_THISCALL)
3967 type->function.calling_convention = CC_THISCALL;
3969 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3972 declaration_t *parameters = parse_parameters(&type->function);
3973 if (declaration != NULL) {
3974 declaration->scope.declarations = parameters;
3977 construct_function_type_t *construct_function_type =
3978 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3979 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3980 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3981 construct_function_type->function_type = type;
3983 return &construct_function_type->construct_type;
3986 static void fix_declaration_type(declaration_t *declaration)
3988 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3989 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3991 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3992 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3994 if (declaration->type->base.modifiers == type_modifiers)
3997 type_t *copy = duplicate_type(declaration->type);
3998 copy->base.modifiers = type_modifiers;
4000 type_t *result = typehash_insert(copy);
4001 if (result != copy) {
4002 obstack_free(type_obst, copy);
4005 declaration->type = result;
4008 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4009 bool may_be_abstract)
4011 /* construct a single linked list of construct_type_t's which describe
4012 * how to construct the final declarator type */
4013 construct_type_t *first = NULL;
4014 construct_type_t *last = NULL;
4015 gnu_attribute_t *attributes = NULL;
4017 decl_modifiers_t modifiers = parse_attributes(&attributes);
4020 while (token.type == '*') {
4021 construct_type_t *type = parse_pointer_declarator();
4031 /* TODO: find out if this is correct */
4032 modifiers |= parse_attributes(&attributes);
4035 if (declaration != NULL)
4036 declaration->modifiers |= modifiers;
4038 construct_type_t *inner_types = NULL;
4040 switch(token.type) {
4042 if (declaration == NULL) {
4043 errorf(HERE, "no identifier expected in typename");
4045 declaration->symbol = token.v.symbol;
4046 declaration->source_position = token.source_position;
4052 add_anchor_token(')');
4053 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4054 if (inner_types != NULL) {
4055 /* All later declarators only modify the return type, not declaration */
4058 rem_anchor_token(')');
4062 if (may_be_abstract)
4064 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4069 construct_type_t *p = last;
4072 construct_type_t *type;
4073 switch(token.type) {
4075 type = parse_function_declarator(declaration);
4078 type = parse_array_declarator();
4081 goto declarator_finished;
4084 /* insert in the middle of the list (behind p) */
4086 type->next = p->next;
4097 declarator_finished:
4098 /* append inner_types at the end of the list, we don't to set last anymore
4099 * as it's not needed anymore */
4101 assert(first == NULL);
4102 first = inner_types;
4104 last->next = inner_types;
4112 static void parse_declaration_attributes(declaration_t *declaration)
4114 gnu_attribute_t *attributes = NULL;
4115 decl_modifiers_t modifiers = parse_attributes(&attributes);
4117 if (declaration == NULL)
4120 declaration->modifiers |= modifiers;
4121 /* check if we have these stupid mode attributes... */
4122 type_t *old_type = declaration->type;
4123 if (old_type == NULL)
4126 gnu_attribute_t *attribute = attributes;
4127 for ( ; attribute != NULL; attribute = attribute->next) {
4128 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4131 atomic_type_kind_t akind = attribute->u.akind;
4132 if (!is_type_signed(old_type)) {
4134 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4135 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4136 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4137 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4139 panic("invalid akind in mode attribute");
4143 = make_atomic_type(akind, old_type->base.qualifiers);
4147 static type_t *construct_declarator_type(construct_type_t *construct_list,
4150 construct_type_t *iter = construct_list;
4151 for( ; iter != NULL; iter = iter->next) {
4152 switch(iter->kind) {
4153 case CONSTRUCT_INVALID:
4154 internal_errorf(HERE, "invalid type construction found");
4155 case CONSTRUCT_FUNCTION: {
4156 construct_function_type_t *construct_function_type
4157 = (construct_function_type_t*) iter;
4159 type_t *function_type = construct_function_type->function_type;
4161 function_type->function.return_type = type;
4163 type_t *skipped_return_type = skip_typeref(type);
4165 if (is_type_function(skipped_return_type)) {
4166 errorf(HERE, "function returning function is not allowed");
4167 } else if (is_type_array(skipped_return_type)) {
4168 errorf(HERE, "function returning array is not allowed");
4170 if (skipped_return_type->base.qualifiers != 0) {
4172 "type qualifiers in return type of function type are meaningless");
4176 type = function_type;
4180 case CONSTRUCT_POINTER: {
4181 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4182 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4183 pointer_type->pointer.points_to = type;
4184 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4186 type = pointer_type;
4190 case CONSTRUCT_ARRAY: {
4191 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4192 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4194 expression_t *size_expression = parsed_array->size;
4195 if (size_expression != NULL) {
4197 = create_implicit_cast(size_expression, type_size_t);
4200 array_type->base.qualifiers = parsed_array->type_qualifiers;
4201 array_type->array.element_type = type;
4202 array_type->array.is_static = parsed_array->is_static;
4203 array_type->array.is_variable = parsed_array->is_variable;
4204 array_type->array.size_expression = size_expression;
4206 if (size_expression != NULL) {
4207 if (is_constant_expression(size_expression)) {
4208 array_type->array.size_constant = true;
4209 array_type->array.size
4210 = fold_constant(size_expression);
4212 array_type->array.is_vla = true;
4216 type_t *skipped_type = skip_typeref(type);
4218 if (is_type_incomplete(skipped_type)) {
4219 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4220 } else if (is_type_function(skipped_type)) {
4221 errorf(HERE, "array of functions is not allowed");
4228 type_t *hashed_type = typehash_insert(type);
4229 if (hashed_type != type) {
4230 /* the function type was constructed earlier freeing it here will
4231 * destroy other types... */
4232 if (iter->kind != CONSTRUCT_FUNCTION) {
4242 static declaration_t *parse_declarator(
4243 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4245 declaration_t *const declaration = allocate_declaration_zero();
4246 declaration->source_position = specifiers->source_position;
4247 declaration->declared_storage_class = specifiers->declared_storage_class;
4248 declaration->modifiers = specifiers->modifiers;
4249 declaration->deprecated_string = specifiers->deprecated_string;
4250 declaration->get_property_sym = specifiers->get_property_sym;
4251 declaration->put_property_sym = specifiers->put_property_sym;
4252 declaration->is_inline = specifiers->is_inline;
4254 declaration->storage_class = specifiers->declared_storage_class;
4255 if (declaration->storage_class == STORAGE_CLASS_NONE
4256 && scope != global_scope) {
4257 declaration->storage_class = STORAGE_CLASS_AUTO;
4260 if (specifiers->alignment != 0) {
4261 /* TODO: add checks here */
4262 declaration->alignment = specifiers->alignment;
4265 construct_type_t *construct_type
4266 = parse_inner_declarator(declaration, may_be_abstract);
4267 type_t *const type = specifiers->type;
4268 declaration->type = construct_declarator_type(construct_type, type);
4270 parse_declaration_attributes(declaration);
4272 fix_declaration_type(declaration);
4274 if (construct_type != NULL) {
4275 obstack_free(&temp_obst, construct_type);
4281 static type_t *parse_abstract_declarator(type_t *base_type)
4283 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4285 type_t *result = construct_declarator_type(construct_type, base_type);
4286 if (construct_type != NULL) {
4287 obstack_free(&temp_obst, construct_type);
4293 static declaration_t *append_declaration(declaration_t* const declaration)
4295 if (last_declaration != NULL) {
4296 last_declaration->next = declaration;
4298 scope->declarations = declaration;
4300 last_declaration = declaration;
4305 * Check if the declaration of main is suspicious. main should be a
4306 * function with external linkage, returning int, taking either zero
4307 * arguments, two, or three arguments of appropriate types, ie.
4309 * int main([ int argc, char **argv [, char **env ] ]).
4311 * @param decl the declaration to check
4312 * @param type the function type of the declaration
4314 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4316 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4317 warningf(&decl->source_position,
4318 "'main' is normally a non-static function");
4320 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4321 warningf(&decl->source_position,
4322 "return type of 'main' should be 'int', but is '%T'",
4323 func_type->return_type);
4325 const function_parameter_t *parm = func_type->parameters;
4327 type_t *const first_type = parm->type;
4328 if (!types_compatible(skip_typeref(first_type), type_int)) {
4329 warningf(&decl->source_position,
4330 "first argument of 'main' should be 'int', but is '%T'", first_type);
4334 type_t *const second_type = parm->type;
4335 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4336 warningf(&decl->source_position,
4337 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4341 type_t *const third_type = parm->type;
4342 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4343 warningf(&decl->source_position,
4344 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4348 goto warn_arg_count;
4352 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4358 * Check if a symbol is the equal to "main".
4360 static bool is_sym_main(const symbol_t *const sym)
4362 return strcmp(sym->string, "main") == 0;
4365 static declaration_t *record_declaration(
4366 declaration_t *const declaration,
4367 const bool is_definition)
4369 const symbol_t *const symbol = declaration->symbol;
4370 const namespace_t namespc = (namespace_t)declaration->namespc;
4372 assert(symbol != NULL);
4373 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4375 type_t *const orig_type = declaration->type;
4376 type_t *const type = skip_typeref(orig_type);
4377 if (is_type_function(type) &&
4378 type->function.unspecified_parameters &&
4379 warning.strict_prototypes &&
4380 previous_declaration == NULL) {
4381 warningf(&declaration->source_position,
4382 "function declaration '%#T' is not a prototype",
4386 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4387 check_type_of_main(declaration, &type->function);
4390 if (warning.nested_externs &&
4391 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4392 scope != global_scope) {
4393 warningf(&declaration->source_position,
4394 "nested extern declaration of '%#T'", declaration->type, symbol);
4397 assert(declaration != previous_declaration);
4398 if (previous_declaration != NULL
4399 && previous_declaration->parent_scope == scope) {
4400 /* can happen for K&R style declarations */
4401 if (previous_declaration->type == NULL) {
4402 previous_declaration->type = declaration->type;
4405 const type_t *prev_type = skip_typeref(previous_declaration->type);
4406 if (!types_compatible(type, prev_type)) {
4407 errorf(&declaration->source_position,
4408 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4409 orig_type, symbol, previous_declaration->type, symbol,
4410 &previous_declaration->source_position);
4412 unsigned old_storage_class = previous_declaration->storage_class;
4413 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4414 errorf(&declaration->source_position,
4415 "redeclaration of enum entry '%Y' (declared %P)",
4416 symbol, &previous_declaration->source_position);
4417 return previous_declaration;
4420 if (warning.redundant_decls &&
4422 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4423 !(previous_declaration->modifiers & DM_USED) &&
4424 !previous_declaration->used) {
4425 warningf(&previous_declaration->source_position,
4426 "unnecessary static forward declaration for '%#T'",
4427 previous_declaration->type, symbol);
4430 unsigned new_storage_class = declaration->storage_class;
4432 if (is_type_incomplete(prev_type)) {
4433 previous_declaration->type = type;
4437 /* pretend no storage class means extern for function
4438 * declarations (except if the previous declaration is neither
4439 * none nor extern) */
4440 if (is_type_function(type)) {
4441 if (prev_type->function.unspecified_parameters) {
4442 previous_declaration->type = type;
4446 switch (old_storage_class) {
4447 case STORAGE_CLASS_NONE:
4448 old_storage_class = STORAGE_CLASS_EXTERN;
4451 case STORAGE_CLASS_EXTERN:
4452 if (is_definition) {
4453 if (warning.missing_prototypes &&
4454 prev_type->function.unspecified_parameters &&
4455 !is_sym_main(symbol)) {
4456 warningf(&declaration->source_position,
4457 "no previous prototype for '%#T'",
4460 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4461 new_storage_class = STORAGE_CLASS_EXTERN;
4470 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4471 new_storage_class == STORAGE_CLASS_EXTERN) {
4472 warn_redundant_declaration:
4473 if (!is_definition &&
4474 warning.redundant_decls &&
4475 is_type_valid(prev_type) &&
4476 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4477 warningf(&declaration->source_position,
4478 "redundant declaration for '%Y' (declared %P)",
4479 symbol, &previous_declaration->source_position);
4481 } else if (current_function == NULL) {
4482 if (old_storage_class != STORAGE_CLASS_STATIC &&
4483 new_storage_class == STORAGE_CLASS_STATIC) {
4484 errorf(&declaration->source_position,
4485 "static declaration of '%Y' follows non-static declaration (declared %P)",
4486 symbol, &previous_declaration->source_position);
4487 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4488 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4489 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4491 goto warn_redundant_declaration;
4493 } else if (is_type_valid(prev_type)) {
4494 if (old_storage_class == new_storage_class) {
4495 errorf(&declaration->source_position,
4496 "redeclaration of '%Y' (declared %P)",
4497 symbol, &previous_declaration->source_position);
4499 errorf(&declaration->source_position,
4500 "redeclaration of '%Y' with different linkage (declared %P)",
4501 symbol, &previous_declaration->source_position);
4506 previous_declaration->modifiers |= declaration->modifiers;
4507 previous_declaration->is_inline |= declaration->is_inline;
4508 return previous_declaration;
4509 } else if (is_type_function(type)) {
4510 if (is_definition &&
4511 declaration->storage_class != STORAGE_CLASS_STATIC) {
4512 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4513 warningf(&declaration->source_position,
4514 "no previous prototype for '%#T'", orig_type, symbol);
4515 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4516 warningf(&declaration->source_position,
4517 "no previous declaration for '%#T'", orig_type,
4522 if (warning.missing_declarations &&
4523 scope == global_scope && (
4524 declaration->storage_class == STORAGE_CLASS_NONE ||
4525 declaration->storage_class == STORAGE_CLASS_THREAD
4527 warningf(&declaration->source_position,
4528 "no previous declaration for '%#T'", orig_type, symbol);
4532 assert(declaration->parent_scope == NULL);
4533 assert(scope != NULL);
4535 declaration->parent_scope = scope;
4537 environment_push(declaration);
4538 return append_declaration(declaration);
4541 static void parser_error_multiple_definition(declaration_t *declaration,
4542 const source_position_t *source_position)
4544 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4545 declaration->symbol, &declaration->source_position);
4548 static bool is_declaration_specifier(const token_t *token,
4549 bool only_specifiers_qualifiers)
4551 switch (token->type) {
4556 return is_typedef_symbol(token->v.symbol);
4558 case T___extension__:
4560 return !only_specifiers_qualifiers;
4567 static void parse_init_declarator_rest(declaration_t *declaration)
4571 type_t *orig_type = declaration->type;
4572 type_t *type = skip_typeref(orig_type);
4574 if (declaration->init.initializer != NULL) {
4575 parser_error_multiple_definition(declaration, HERE);
4578 bool must_be_constant = false;
4579 if (declaration->storage_class == STORAGE_CLASS_STATIC
4580 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4581 || declaration->parent_scope == global_scope) {
4582 must_be_constant = true;
4585 if (is_type_function(type)) {
4586 errorf(&declaration->source_position,
4587 "function '%#T' is initialized like a variable",
4588 orig_type, declaration->symbol);
4589 orig_type = type_error_type;
4592 parse_initializer_env_t env;
4593 env.type = orig_type;
4594 env.must_be_constant = must_be_constant;
4595 env.declaration = current_init_decl = declaration;
4597 initializer_t *initializer = parse_initializer(&env);
4598 current_init_decl = NULL;
4600 if (!is_type_function(type)) {
4601 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4602 * the array type size */
4603 declaration->type = env.type;
4604 declaration->init.initializer = initializer;
4608 /* parse rest of a declaration without any declarator */
4609 static void parse_anonymous_declaration_rest(
4610 const declaration_specifiers_t *specifiers)
4614 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4615 warningf(&specifiers->source_position,
4616 "useless storage class in empty declaration");
4619 type_t *type = specifiers->type;
4620 switch (type->kind) {
4621 case TYPE_COMPOUND_STRUCT:
4622 case TYPE_COMPOUND_UNION: {
4623 if (type->compound.declaration->symbol == NULL) {
4624 warningf(&specifiers->source_position,
4625 "unnamed struct/union that defines no instances");
4634 warningf(&specifiers->source_position, "empty declaration");
4638 #ifdef RECORD_EMPTY_DECLARATIONS
4639 declaration_t *const declaration = allocate_declaration_zero();
4640 declaration->type = specifiers->type;
4641 declaration->declared_storage_class = specifiers->declared_storage_class;
4642 declaration->source_position = specifiers->source_position;
4643 declaration->modifiers = specifiers->modifiers;
4644 declaration->storage_class = STORAGE_CLASS_NONE;
4646 append_declaration(declaration);
4650 static void parse_declaration_rest(declaration_t *ndeclaration,
4651 const declaration_specifiers_t *specifiers,
4652 parsed_declaration_func finished_declaration)
4654 add_anchor_token(';');
4655 add_anchor_token(',');
4657 declaration_t *declaration =
4658 finished_declaration(ndeclaration, token.type == '=');
4660 type_t *orig_type = declaration->type;
4661 type_t *type = skip_typeref(orig_type);
4663 if (type->kind != TYPE_FUNCTION &&
4664 declaration->is_inline &&
4665 is_type_valid(type)) {
4666 warningf(&declaration->source_position,
4667 "variable '%Y' declared 'inline'\n", declaration->symbol);
4670 if (token.type == '=') {
4671 parse_init_declarator_rest(declaration);
4674 if (token.type != ',')
4678 add_anchor_token('=');
4679 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4680 rem_anchor_token('=');
4685 rem_anchor_token(';');
4686 rem_anchor_token(',');
4689 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4691 symbol_t *symbol = declaration->symbol;
4692 if (symbol == NULL) {
4693 errorf(HERE, "anonymous declaration not valid as function parameter");
4696 namespace_t namespc = (namespace_t) declaration->namespc;
4697 if (namespc != NAMESPACE_NORMAL) {
4698 return record_declaration(declaration, false);
4701 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4702 if (previous_declaration == NULL ||
4703 previous_declaration->parent_scope != scope) {
4704 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4709 if (is_definition) {
4710 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4713 if (previous_declaration->type == NULL) {
4714 previous_declaration->type = declaration->type;
4715 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4716 previous_declaration->storage_class = declaration->storage_class;
4717 previous_declaration->parent_scope = scope;
4718 return previous_declaration;
4720 return record_declaration(declaration, false);
4724 static void parse_declaration(parsed_declaration_func finished_declaration)
4726 declaration_specifiers_t specifiers;
4727 memset(&specifiers, 0, sizeof(specifiers));
4729 add_anchor_token(';');
4730 parse_declaration_specifiers(&specifiers);
4731 rem_anchor_token(';');
4733 if (token.type == ';') {
4734 parse_anonymous_declaration_rest(&specifiers);
4736 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4737 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4741 static type_t *get_default_promoted_type(type_t *orig_type)
4743 type_t *result = orig_type;
4745 type_t *type = skip_typeref(orig_type);
4746 if (is_type_integer(type)) {
4747 result = promote_integer(type);
4748 } else if (type == type_float) {
4749 result = type_double;
4755 static void parse_kr_declaration_list(declaration_t *declaration)
4757 type_t *type = skip_typeref(declaration->type);
4758 if (!is_type_function(type))
4761 if (!type->function.kr_style_parameters)
4764 /* push function parameters */
4765 int top = environment_top();
4766 scope_t *last_scope = scope;
4767 set_scope(&declaration->scope);
4769 declaration_t *parameter = declaration->scope.declarations;
4770 for ( ; parameter != NULL; parameter = parameter->next) {
4771 assert(parameter->parent_scope == NULL);
4772 parameter->parent_scope = scope;
4773 environment_push(parameter);
4776 /* parse declaration list */
4777 while (is_declaration_specifier(&token, false)) {
4778 parse_declaration(finished_kr_declaration);
4781 /* pop function parameters */
4782 assert(scope == &declaration->scope);
4783 set_scope(last_scope);
4784 environment_pop_to(top);
4786 /* update function type */
4787 type_t *new_type = duplicate_type(type);
4789 function_parameter_t *parameters = NULL;
4790 function_parameter_t *last_parameter = NULL;
4792 declaration_t *parameter_declaration = declaration->scope.declarations;
4793 for( ; parameter_declaration != NULL;
4794 parameter_declaration = parameter_declaration->next) {
4795 type_t *parameter_type = parameter_declaration->type;
4796 if (parameter_type == NULL) {
4798 errorf(HERE, "no type specified for function parameter '%Y'",
4799 parameter_declaration->symbol);
4801 if (warning.implicit_int) {
4802 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4803 parameter_declaration->symbol);
4805 parameter_type = type_int;
4806 parameter_declaration->type = parameter_type;
4810 semantic_parameter(parameter_declaration);
4811 parameter_type = parameter_declaration->type;
4814 * we need the default promoted types for the function type
4816 parameter_type = get_default_promoted_type(parameter_type);
4818 function_parameter_t *function_parameter
4819 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4820 memset(function_parameter, 0, sizeof(function_parameter[0]));
4822 function_parameter->type = parameter_type;
4823 if (last_parameter != NULL) {
4824 last_parameter->next = function_parameter;
4826 parameters = function_parameter;
4828 last_parameter = function_parameter;
4831 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4833 new_type->function.parameters = parameters;
4834 new_type->function.unspecified_parameters = true;
4836 type = typehash_insert(new_type);
4837 if (type != new_type) {
4838 obstack_free(type_obst, new_type);
4841 declaration->type = type;
4844 static bool first_err = true;
4847 * When called with first_err set, prints the name of the current function,
4850 static void print_in_function(void)
4854 diagnosticf("%s: In function '%Y':\n",
4855 current_function->source_position.input_name,
4856 current_function->symbol);
4861 * Check if all labels are defined in the current function.
4862 * Check if all labels are used in the current function.
4864 static void check_labels(void)
4866 for (const goto_statement_t *goto_statement = goto_first;
4867 goto_statement != NULL;
4868 goto_statement = goto_statement->next) {
4869 /* skip computed gotos */
4870 if (goto_statement->expression != NULL)
4873 declaration_t *label = goto_statement->label;
4876 if (label->source_position.input_name == NULL) {
4877 print_in_function();
4878 errorf(&goto_statement->base.source_position,
4879 "label '%Y' used but not defined", label->symbol);
4882 goto_first = goto_last = NULL;
4884 if (warning.unused_label) {
4885 for (const label_statement_t *label_statement = label_first;
4886 label_statement != NULL;
4887 label_statement = label_statement->next) {
4888 const declaration_t *label = label_statement->label;
4890 if (! label->used) {
4891 print_in_function();
4892 warningf(&label_statement->base.source_position,
4893 "label '%Y' defined but not used", label->symbol);
4897 label_first = label_last = NULL;
4901 * Check declarations of current_function for unused entities.
4903 static void check_declarations(void)
4905 if (warning.unused_parameter) {
4906 const scope_t *scope = ¤t_function->scope;
4908 if (is_sym_main(current_function->symbol)) {
4909 /* do not issue unused warnings for main */
4912 const declaration_t *parameter = scope->declarations;
4913 for (; parameter != NULL; parameter = parameter->next) {
4914 if (! parameter->used) {
4915 print_in_function();
4916 warningf(¶meter->source_position,
4917 "unused parameter '%Y'", parameter->symbol);
4921 if (warning.unused_variable) {
4925 static int determine_truth(expression_t const* const cond)
4928 !is_constant_expression(cond) ? 0 :
4929 fold_constant(cond) != 0 ? 1 :
4933 static bool noreturn_candidate;
4935 static void check_reachable(statement_t *const stmt)
4937 if (stmt->base.reachable)
4939 if (stmt->kind != STATEMENT_DO_WHILE)
4940 stmt->base.reachable = true;
4942 statement_t *last = stmt;
4944 switch (stmt->kind) {
4945 case STATEMENT_INVALID:
4946 case STATEMENT_EMPTY:
4947 case STATEMENT_DECLARATION:
4949 next = stmt->base.next;
4952 case STATEMENT_COMPOUND:
4953 next = stmt->compound.statements;
4956 case STATEMENT_RETURN:
4957 noreturn_candidate = false;
4960 case STATEMENT_IF: {
4961 if_statement_t const* const ifs = &stmt->ifs;
4962 int const val = determine_truth(ifs->condition);
4965 check_reachable(ifs->true_statement);
4970 if (ifs->false_statement != NULL) {
4971 check_reachable(ifs->false_statement);
4975 next = stmt->base.next;
4979 case STATEMENT_SWITCH: {
4980 switch_statement_t const *const switchs = &stmt->switchs;
4981 expression_t const *const expr = switchs->expression;
4983 if (is_constant_expression(expr)) {
4984 long const val = fold_constant(expr);
4985 case_label_statement_t * defaults = NULL;
4986 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4987 if (i->expression == NULL) {
4992 if (i->first_case <= val && val <= i->last_case) {
4993 check_reachable((statement_t*)i);
4998 if (defaults != NULL) {
4999 check_reachable((statement_t*)defaults);
5003 bool has_default = false;
5004 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5005 if (i->expression == NULL)
5008 check_reachable((statement_t*)i);
5015 next = stmt->base.next;
5019 case STATEMENT_EXPRESSION: {
5020 /* Check for noreturn function call */
5021 expression_t const *const expr = stmt->expression.expression;
5022 if (expr->kind == EXPR_CALL) {
5023 expression_t const *const func = expr->call.function;
5024 if (func->kind == EXPR_REFERENCE) {
5025 declaration_t const *const decl = func->reference.declaration;
5026 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5032 next = stmt->base.next;
5036 case STATEMENT_CONTINUE: {
5037 statement_t *parent = stmt;
5039 parent = parent->base.parent;
5040 if (parent == NULL) /* continue not within loop */
5044 switch (parent->kind) {
5045 case STATEMENT_WHILE: goto continue_while;
5046 case STATEMENT_DO_WHILE: goto continue_do_while;
5047 case STATEMENT_FOR: goto continue_for;
5054 case STATEMENT_BREAK: {
5055 statement_t *parent = stmt;
5057 parent = parent->base.parent;
5058 if (parent == NULL) /* break not within loop/switch */
5061 switch (parent->kind) {
5062 case STATEMENT_SWITCH:
5063 case STATEMENT_WHILE:
5064 case STATEMENT_DO_WHILE:
5067 next = parent->base.next;
5068 goto found_break_parent;
5077 case STATEMENT_GOTO:
5078 if (stmt->gotos.expression) {
5079 statement_t *parent = stmt->base.parent;
5080 if (parent == NULL) /* top level goto */
5084 next = stmt->gotos.label->init.statement;
5085 if (next == NULL) /* missing label */
5090 case STATEMENT_LABEL:
5091 next = stmt->label.statement;
5094 case STATEMENT_CASE_LABEL:
5095 next = stmt->case_label.statement;
5098 case STATEMENT_WHILE: {
5099 while_statement_t const *const whiles = &stmt->whiles;
5100 int const val = determine_truth(whiles->condition);
5103 check_reachable(whiles->body);
5108 next = stmt->base.next;
5112 case STATEMENT_DO_WHILE:
5113 next = stmt->do_while.body;
5116 case STATEMENT_FOR: {
5117 for_statement_t *const fors = &stmt->fors;
5119 if (fors->condition_reachable)
5121 fors->condition_reachable = true;
5123 expression_t const *const cond = fors->condition;
5125 cond == NULL ? 1 : determine_truth(cond);
5128 check_reachable(fors->body);
5133 next = stmt->base.next;
5137 case STATEMENT_MS_TRY: {
5138 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5139 check_reachable(ms_try->try_statement);
5140 next = ms_try->final_statement;
5144 case STATEMENT_LEAVE: {
5145 statement_t *parent = stmt;
5147 parent = parent->base.parent;
5148 if (parent == NULL) /* __leave not within __try */
5151 if (parent->kind == STATEMENT_MS_TRY) {
5153 next = parent->ms_try.final_statement;
5161 while (next == NULL) {
5162 next = last->base.parent;
5164 noreturn_candidate = false;
5166 type_t *const type = current_function->type;
5167 assert(is_type_function(type));
5168 type_t *const ret = skip_typeref(type->function.return_type);
5169 if (warning.return_type &&
5170 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5171 is_type_valid(ret) &&
5172 !is_sym_main(current_function->symbol)) {
5173 warningf(&stmt->base.source_position,
5174 "control reaches end of non-void function");
5179 switch (next->kind) {
5180 case STATEMENT_INVALID:
5181 case STATEMENT_EMPTY:
5182 case STATEMENT_DECLARATION:
5183 case STATEMENT_EXPRESSION:
5185 case STATEMENT_RETURN:
5186 case STATEMENT_CONTINUE:
5187 case STATEMENT_BREAK:
5188 case STATEMENT_GOTO:
5189 case STATEMENT_LEAVE:
5190 panic("invalid control flow in function");
5192 case STATEMENT_COMPOUND:
5194 case STATEMENT_SWITCH:
5195 case STATEMENT_LABEL:
5196 case STATEMENT_CASE_LABEL:
5198 next = next->base.next;
5201 case STATEMENT_WHILE: {
5203 if (next->base.reachable)
5205 next->base.reachable = true;
5207 while_statement_t const *const whiles = &next->whiles;
5208 int const val = determine_truth(whiles->condition);
5211 check_reachable(whiles->body);
5217 next = next->base.next;
5221 case STATEMENT_DO_WHILE: {
5223 if (next->base.reachable)
5225 next->base.reachable = true;
5227 do_while_statement_t const *const dw = &next->do_while;
5228 int const val = determine_truth(dw->condition);
5231 check_reachable(dw->body);
5237 next = next->base.next;
5241 case STATEMENT_FOR: {
5243 for_statement_t *const fors = &next->fors;
5245 fors->step_reachable = true;
5247 if (fors->condition_reachable)
5249 fors->condition_reachable = true;
5251 expression_t const *const cond = fors->condition;
5253 cond == NULL ? 1 : determine_truth(cond);
5256 check_reachable(fors->body);
5262 next = next->base.next;
5266 case STATEMENT_MS_TRY:
5268 next = next->ms_try.final_statement;
5274 next = stmt->base.parent;
5276 warningf(&stmt->base.source_position,
5277 "control reaches end of non-void function");
5281 check_reachable(next);
5284 static void check_unreachable(statement_t const* const stmt)
5286 if (!stmt->base.reachable &&
5287 stmt->kind != STATEMENT_DO_WHILE &&
5288 stmt->kind != STATEMENT_FOR &&
5289 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5290 warningf(&stmt->base.source_position, "statement is unreachable");
5293 switch (stmt->kind) {
5294 case STATEMENT_INVALID:
5295 case STATEMENT_EMPTY:
5296 case STATEMENT_RETURN:
5297 case STATEMENT_DECLARATION:
5298 case STATEMENT_EXPRESSION:
5299 case STATEMENT_CONTINUE:
5300 case STATEMENT_BREAK:
5301 case STATEMENT_GOTO:
5303 case STATEMENT_LEAVE:
5306 case STATEMENT_COMPOUND:
5307 if (stmt->compound.statements)
5308 check_unreachable(stmt->compound.statements);
5312 check_unreachable(stmt->ifs.true_statement);
5313 if (stmt->ifs.false_statement != NULL)
5314 check_unreachable(stmt->ifs.false_statement);
5317 case STATEMENT_SWITCH:
5318 check_unreachable(stmt->switchs.body);
5321 case STATEMENT_LABEL:
5322 check_unreachable(stmt->label.statement);
5325 case STATEMENT_CASE_LABEL:
5326 check_unreachable(stmt->case_label.statement);
5329 case STATEMENT_WHILE:
5330 check_unreachable(stmt->whiles.body);
5333 case STATEMENT_DO_WHILE:
5334 check_unreachable(stmt->do_while.body);
5335 if (!stmt->base.reachable) {
5336 expression_t const *const cond = stmt->do_while.condition;
5337 if (determine_truth(cond) >= 0) {
5338 warningf(&cond->base.source_position,
5339 "condition of do-while-loop is unreachable");
5344 case STATEMENT_FOR: {
5345 for_statement_t const* const fors = &stmt->fors;
5347 // if init and step are unreachable, cond is unreachable, too
5348 if (!stmt->base.reachable && !fors->step_reachable) {
5349 warningf(&stmt->base.source_position, "statement is unreachable");
5351 if (!stmt->base.reachable && fors->initialisation != NULL) {
5352 warningf(&fors->initialisation->base.source_position,
5353 "initialisation of for-statement is unreachable");
5356 if (!fors->condition_reachable && fors->condition != NULL) {
5357 warningf(&fors->condition->base.source_position,
5358 "condition of for-statement is unreachable");
5361 if (!fors->step_reachable && fors->step != NULL) {
5362 warningf(&fors->step->base.source_position,
5363 "step of for-statement is unreachable");
5367 check_unreachable(fors->body);
5371 case STATEMENT_MS_TRY: {
5372 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5373 check_unreachable(ms_try->try_statement);
5374 check_unreachable(ms_try->final_statement);
5378 if (stmt->base.next)
5379 check_unreachable(stmt->base.next);
5382 static void parse_external_declaration(void)
5384 /* function-definitions and declarations both start with declaration
5386 declaration_specifiers_t specifiers;
5387 memset(&specifiers, 0, sizeof(specifiers));
5389 add_anchor_token(';');
5390 parse_declaration_specifiers(&specifiers);
5391 rem_anchor_token(';');
5393 /* must be a declaration */
5394 if (token.type == ';') {
5395 parse_anonymous_declaration_rest(&specifiers);
5399 add_anchor_token(',');
5400 add_anchor_token('=');
5401 add_anchor_token(';');
5403 /* declarator is common to both function-definitions and declarations */
5404 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5406 rem_anchor_token(',');
5407 rem_anchor_token('=');
5408 rem_anchor_token(';');
5410 /* must be a declaration */
5411 switch (token.type) {
5415 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5419 /* must be a function definition */
5420 parse_kr_declaration_list(ndeclaration);
5422 if (token.type != '{') {
5423 parse_error_expected("while parsing function definition", '{', NULL);
5424 eat_until_matching_token(';');
5428 type_t *type = ndeclaration->type;
5430 /* note that we don't skip typerefs: the standard doesn't allow them here
5431 * (so we can't use is_type_function here) */
5432 if (type->kind != TYPE_FUNCTION) {
5433 if (is_type_valid(type)) {
5434 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5435 type, ndeclaration->symbol);
5441 if (warning.aggregate_return &&
5442 is_type_compound(skip_typeref(type->function.return_type))) {
5443 warningf(HERE, "function '%Y' returns an aggregate",
5444 ndeclaration->symbol);
5446 if (warning.traditional && !type->function.unspecified_parameters) {
5447 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5448 ndeclaration->symbol);
5450 if (warning.old_style_definition && type->function.unspecified_parameters) {
5451 warningf(HERE, "old-style function definition '%Y'",
5452 ndeclaration->symbol);
5455 /* § 6.7.5.3 (14) a function definition with () means no
5456 * parameters (and not unspecified parameters) */
5457 if (type->function.unspecified_parameters
5458 && type->function.parameters == NULL
5459 && !type->function.kr_style_parameters) {
5460 type_t *duplicate = duplicate_type(type);
5461 duplicate->function.unspecified_parameters = false;
5463 type = typehash_insert(duplicate);
5464 if (type != duplicate) {
5465 obstack_free(type_obst, duplicate);
5467 ndeclaration->type = type;
5470 declaration_t *const declaration = record_declaration(ndeclaration, true);
5471 if (ndeclaration != declaration) {
5472 declaration->scope = ndeclaration->scope;
5474 type = skip_typeref(declaration->type);
5476 /* push function parameters and switch scope */
5477 int top = environment_top();
5478 scope_t *last_scope = scope;
5479 set_scope(&declaration->scope);
5481 declaration_t *parameter = declaration->scope.declarations;
5482 for( ; parameter != NULL; parameter = parameter->next) {
5483 if (parameter->parent_scope == &ndeclaration->scope) {
5484 parameter->parent_scope = scope;
5486 assert(parameter->parent_scope == NULL
5487 || parameter->parent_scope == scope);
5488 parameter->parent_scope = scope;
5489 if (parameter->symbol == NULL) {
5490 errorf(¶meter->source_position, "parameter name omitted");
5493 environment_push(parameter);
5496 if (declaration->init.statement != NULL) {
5497 parser_error_multiple_definition(declaration, HERE);
5500 /* parse function body */
5501 int label_stack_top = label_top();
5502 declaration_t *old_current_function = current_function;
5503 current_function = declaration;
5504 current_parent = NULL;
5506 statement_t *const body = parse_compound_statement(false);
5507 declaration->init.statement = body;
5510 check_declarations();
5511 if (warning.return_type ||
5512 warning.unreachable_code ||
5513 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5514 noreturn_candidate = true;
5515 check_reachable(body);
5516 if (warning.unreachable_code)
5517 check_unreachable(body);
5518 if (warning.missing_noreturn &&
5519 noreturn_candidate &&
5520 !(declaration->modifiers & DM_NORETURN)) {
5521 warningf(&body->base.source_position,
5522 "function '%#T' is candidate for attribute 'noreturn'",
5523 type, declaration->symbol);
5527 assert(current_parent == NULL);
5528 assert(current_function == declaration);
5529 current_function = old_current_function;
5530 label_pop_to(label_stack_top);
5533 assert(scope == &declaration->scope);
5534 set_scope(last_scope);
5535 environment_pop_to(top);
5538 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5539 source_position_t *source_position,
5540 const symbol_t *symbol)
5542 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5544 type->bitfield.base_type = base_type;
5545 type->bitfield.size_expression = size;
5548 type_t *skipped_type = skip_typeref(base_type);
5549 if (!is_type_integer(skipped_type)) {
5550 errorf(HERE, "bitfield base type '%T' is not an integer type",
5554 bit_size = skipped_type->base.size * 8;
5557 if (is_constant_expression(size)) {
5558 long v = fold_constant(size);
5561 errorf(source_position, "negative width in bit-field '%Y'",
5563 } else if (v == 0) {
5564 errorf(source_position, "zero width for bit-field '%Y'",
5566 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5567 errorf(source_position, "width of '%Y' exceeds its type",
5570 type->bitfield.bit_size = v;
5577 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5580 declaration_t *iter = compound_declaration->scope.declarations;
5581 for( ; iter != NULL; iter = iter->next) {
5582 if (iter->namespc != NAMESPACE_NORMAL)
5585 if (iter->symbol == NULL) {
5586 type_t *type = skip_typeref(iter->type);
5587 if (is_type_compound(type)) {
5588 declaration_t *result
5589 = find_compound_entry(type->compound.declaration, symbol);
5596 if (iter->symbol == symbol) {
5604 static void parse_compound_declarators(declaration_t *struct_declaration,
5605 const declaration_specifiers_t *specifiers)
5607 declaration_t *last_declaration = struct_declaration->scope.declarations;
5608 if (last_declaration != NULL) {
5609 while (last_declaration->next != NULL) {
5610 last_declaration = last_declaration->next;
5615 declaration_t *declaration;
5617 if (token.type == ':') {
5618 source_position_t source_position = *HERE;
5621 type_t *base_type = specifiers->type;
5622 expression_t *size = parse_constant_expression();
5624 type_t *type = make_bitfield_type(base_type, size,
5625 &source_position, sym_anonymous);
5627 declaration = allocate_declaration_zero();
5628 declaration->namespc = NAMESPACE_NORMAL;
5629 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5630 declaration->storage_class = STORAGE_CLASS_NONE;
5631 declaration->source_position = source_position;
5632 declaration->modifiers = specifiers->modifiers;
5633 declaration->type = type;
5635 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5637 type_t *orig_type = declaration->type;
5638 type_t *type = skip_typeref(orig_type);
5640 if (token.type == ':') {
5641 source_position_t source_position = *HERE;
5643 expression_t *size = parse_constant_expression();
5645 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5646 &source_position, declaration->symbol);
5647 declaration->type = bitfield_type;
5649 /* TODO we ignore arrays for now... what is missing is a check
5650 * that they're at the end of the struct */
5651 if (is_type_incomplete(type) && !is_type_array(type)) {
5653 "compound member '%Y' has incomplete type '%T'",
5654 declaration->symbol, orig_type);
5655 } else if (is_type_function(type)) {
5656 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5657 declaration->symbol, orig_type);
5662 /* make sure we don't define a symbol multiple times */
5663 symbol_t *symbol = declaration->symbol;
5664 if (symbol != NULL) {
5665 declaration_t *prev_decl
5666 = find_compound_entry(struct_declaration, symbol);
5668 if (prev_decl != NULL) {
5669 assert(prev_decl->symbol == symbol);
5670 errorf(&declaration->source_position,
5671 "multiple declarations of symbol '%Y' (declared %P)",
5672 symbol, &prev_decl->source_position);
5676 /* append declaration */
5677 if (last_declaration != NULL) {
5678 last_declaration->next = declaration;
5680 struct_declaration->scope.declarations = declaration;
5682 last_declaration = declaration;
5684 if (token.type != ',')
5694 static void parse_compound_type_entries(declaration_t *compound_declaration)
5697 add_anchor_token('}');
5699 while (token.type != '}' && token.type != T_EOF) {
5700 declaration_specifiers_t specifiers;
5701 memset(&specifiers, 0, sizeof(specifiers));
5702 parse_declaration_specifiers(&specifiers);
5704 parse_compound_declarators(compound_declaration, &specifiers);
5706 rem_anchor_token('}');
5708 if (token.type == T_EOF) {
5709 errorf(HERE, "EOF while parsing struct");
5714 static type_t *parse_typename(void)
5716 declaration_specifiers_t specifiers;
5717 memset(&specifiers, 0, sizeof(specifiers));
5718 parse_declaration_specifiers(&specifiers);
5719 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5720 /* TODO: improve error message, user does probably not know what a
5721 * storage class is...
5723 errorf(HERE, "typename may not have a storage class");
5726 type_t *result = parse_abstract_declarator(specifiers.type);
5734 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5735 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5736 expression_t *left);
5738 typedef struct expression_parser_function_t expression_parser_function_t;
5739 struct expression_parser_function_t {
5740 unsigned precedence;
5741 parse_expression_function parser;
5742 unsigned infix_precedence;
5743 parse_expression_infix_function infix_parser;
5746 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5749 * Prints an error message if an expression was expected but not read
5751 static expression_t *expected_expression_error(void)
5753 /* skip the error message if the error token was read */
5754 if (token.type != T_ERROR) {
5755 errorf(HERE, "expected expression, got token '%K'", &token);
5759 return create_invalid_expression();
5763 * Parse a string constant.
5765 static expression_t *parse_string_const(void)
5768 if (token.type == T_STRING_LITERAL) {
5769 string_t res = token.v.string;
5771 while (token.type == T_STRING_LITERAL) {
5772 res = concat_strings(&res, &token.v.string);
5775 if (token.type != T_WIDE_STRING_LITERAL) {
5776 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5777 /* note: that we use type_char_ptr here, which is already the
5778 * automatic converted type. revert_automatic_type_conversion
5779 * will construct the array type */
5780 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5781 cnst->string.value = res;
5785 wres = concat_string_wide_string(&res, &token.v.wide_string);
5787 wres = token.v.wide_string;
5792 switch (token.type) {
5793 case T_WIDE_STRING_LITERAL:
5794 wres = concat_wide_strings(&wres, &token.v.wide_string);
5797 case T_STRING_LITERAL:
5798 wres = concat_wide_string_string(&wres, &token.v.string);
5802 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5803 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5804 cnst->wide_string.value = wres;
5813 * Parse an integer constant.
5815 static expression_t *parse_int_const(void)
5817 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5818 cnst->base.source_position = *HERE;
5819 cnst->base.type = token.datatype;
5820 cnst->conste.v.int_value = token.v.intvalue;
5828 * Parse a character constant.
5830 static expression_t *parse_character_constant(void)
5832 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5834 cnst->base.source_position = *HERE;
5835 cnst->base.type = token.datatype;
5836 cnst->conste.v.character = token.v.string;
5838 if (cnst->conste.v.character.size != 1) {
5839 if (warning.multichar && GNU_MODE) {
5840 warningf(HERE, "multi-character character constant");
5842 errorf(HERE, "more than 1 characters in character constant");
5851 * Parse a wide character constant.
5853 static expression_t *parse_wide_character_constant(void)
5855 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5857 cnst->base.source_position = *HERE;
5858 cnst->base.type = token.datatype;
5859 cnst->conste.v.wide_character = token.v.wide_string;
5861 if (cnst->conste.v.wide_character.size != 1) {
5862 if (warning.multichar && GNU_MODE) {
5863 warningf(HERE, "multi-character character constant");
5865 errorf(HERE, "more than 1 characters in character constant");
5874 * Parse a float constant.
5876 static expression_t *parse_float_const(void)
5878 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5879 cnst->base.type = token.datatype;
5880 cnst->conste.v.float_value = token.v.floatvalue;
5887 static declaration_t *create_implicit_function(symbol_t *symbol,
5888 const source_position_t *source_position)
5890 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5891 ntype->function.return_type = type_int;
5892 ntype->function.unspecified_parameters = true;
5894 type_t *type = typehash_insert(ntype);
5895 if (type != ntype) {
5899 declaration_t *const declaration = allocate_declaration_zero();
5900 declaration->storage_class = STORAGE_CLASS_EXTERN;
5901 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5902 declaration->type = type;
5903 declaration->symbol = symbol;
5904 declaration->source_position = *source_position;
5905 declaration->implicit = true;
5907 bool strict_prototypes_old = warning.strict_prototypes;
5908 warning.strict_prototypes = false;
5909 record_declaration(declaration, false);
5910 warning.strict_prototypes = strict_prototypes_old;
5916 * Creates a return_type (func)(argument_type) function type if not
5919 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5920 type_t *argument_type2)
5922 function_parameter_t *parameter2
5923 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5924 memset(parameter2, 0, sizeof(parameter2[0]));
5925 parameter2->type = argument_type2;
5927 function_parameter_t *parameter1
5928 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5929 memset(parameter1, 0, sizeof(parameter1[0]));
5930 parameter1->type = argument_type1;
5931 parameter1->next = parameter2;
5933 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5934 type->function.return_type = return_type;
5935 type->function.parameters = parameter1;
5937 type_t *result = typehash_insert(type);
5938 if (result != type) {
5946 * Creates a return_type (func)(argument_type) function type if not
5949 * @param return_type the return type
5950 * @param argument_type the argument type
5952 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5954 function_parameter_t *parameter
5955 = obstack_alloc(type_obst, sizeof(parameter[0]));
5956 memset(parameter, 0, sizeof(parameter[0]));
5957 parameter->type = argument_type;
5959 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5960 type->function.return_type = return_type;
5961 type->function.parameters = parameter;
5963 type_t *result = typehash_insert(type);
5964 if (result != type) {
5971 static type_t *make_function_0_type(type_t *return_type)
5973 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5974 type->function.return_type = return_type;
5975 type->function.parameters = NULL;
5977 type_t *result = typehash_insert(type);
5978 if (result != type) {
5986 * Creates a function type for some function like builtins.
5988 * @param symbol the symbol describing the builtin
5990 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5992 switch(symbol->ID) {
5993 case T___builtin_alloca:
5994 return make_function_1_type(type_void_ptr, type_size_t);
5995 case T___builtin_huge_val:
5996 return make_function_0_type(type_double);
5997 case T___builtin_nan:
5998 return make_function_1_type(type_double, type_char_ptr);
5999 case T___builtin_nanf:
6000 return make_function_1_type(type_float, type_char_ptr);
6001 case T___builtin_nand:
6002 return make_function_1_type(type_long_double, type_char_ptr);
6003 case T___builtin_va_end:
6004 return make_function_1_type(type_void, type_valist);
6005 case T___builtin_expect:
6006 return make_function_2_type(type_long, type_long, type_long);
6008 internal_errorf(HERE, "not implemented builtin symbol found");
6013 * Performs automatic type cast as described in § 6.3.2.1.
6015 * @param orig_type the original type
6017 static type_t *automatic_type_conversion(type_t *orig_type)
6019 type_t *type = skip_typeref(orig_type);
6020 if (is_type_array(type)) {
6021 array_type_t *array_type = &type->array;
6022 type_t *element_type = array_type->element_type;
6023 unsigned qualifiers = array_type->base.qualifiers;
6025 return make_pointer_type(element_type, qualifiers);
6028 if (is_type_function(type)) {
6029 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6036 * reverts the automatic casts of array to pointer types and function
6037 * to function-pointer types as defined § 6.3.2.1
6039 type_t *revert_automatic_type_conversion(const expression_t *expression)
6041 switch (expression->kind) {
6042 case EXPR_REFERENCE: return expression->reference.declaration->type;
6045 return get_qualified_type(expression->select.compound_entry->type,
6046 expression->base.type->base.qualifiers);
6048 case EXPR_UNARY_DEREFERENCE: {
6049 const expression_t *const value = expression->unary.value;
6050 type_t *const type = skip_typeref(value->base.type);
6051 assert(is_type_pointer(type));
6052 return type->pointer.points_to;
6055 case EXPR_BUILTIN_SYMBOL:
6056 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6058 case EXPR_ARRAY_ACCESS: {
6059 const expression_t *array_ref = expression->array_access.array_ref;
6060 type_t *type_left = skip_typeref(array_ref->base.type);
6061 if (!is_type_valid(type_left))
6063 assert(is_type_pointer(type_left));
6064 return type_left->pointer.points_to;
6067 case EXPR_STRING_LITERAL: {
6068 size_t size = expression->string.value.size;
6069 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6072 case EXPR_WIDE_STRING_LITERAL: {
6073 size_t size = expression->wide_string.value.size;
6074 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6077 case EXPR_COMPOUND_LITERAL:
6078 return expression->compound_literal.type;
6083 return expression->base.type;
6086 static expression_t *parse_reference(void)
6088 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6090 reference_expression_t *ref = &expression->reference;
6091 symbol_t *const symbol = token.v.symbol;
6093 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6095 if (declaration == NULL) {
6096 if (!strict_mode && look_ahead(1)->type == '(') {
6097 /* an implicitly declared function */
6098 if (warning.implicit_function_declaration) {
6099 warningf(HERE, "implicit declaration of function '%Y'",
6103 declaration = create_implicit_function(symbol, HERE);
6105 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6106 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6110 type_t *type = declaration->type;
6112 /* we always do the auto-type conversions; the & and sizeof parser contains
6113 * code to revert this! */
6114 type = automatic_type_conversion(type);
6116 ref->declaration = declaration;
6117 ref->base.type = type;
6119 /* this declaration is used */
6120 declaration->used = true;
6122 /* check for deprecated functions */
6123 if (warning.deprecated_declarations &&
6124 declaration->modifiers & DM_DEPRECATED) {
6125 char const *const prefix = is_type_function(declaration->type) ?
6126 "function" : "variable";
6128 if (declaration->deprecated_string != NULL) {
6129 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6130 prefix, declaration->symbol, &declaration->source_position,
6131 declaration->deprecated_string);
6133 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6134 declaration->symbol, &declaration->source_position);
6137 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6138 current_init_decl = NULL;
6139 warningf(HERE, "variable '%#T' is initialized by itself",
6140 declaration->type, declaration->symbol);
6147 static bool semantic_cast(expression_t *cast)
6149 expression_t *expression = cast->unary.value;
6150 type_t *orig_dest_type = cast->base.type;
6151 type_t *orig_type_right = expression->base.type;
6152 type_t const *dst_type = skip_typeref(orig_dest_type);
6153 type_t const *src_type = skip_typeref(orig_type_right);
6154 source_position_t const *pos = &cast->base.source_position;
6156 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6157 if (dst_type == type_void)
6160 /* only integer and pointer can be casted to pointer */
6161 if (is_type_pointer(dst_type) &&
6162 !is_type_pointer(src_type) &&
6163 !is_type_integer(src_type) &&
6164 is_type_valid(src_type)) {
6165 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6169 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6170 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6174 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6175 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6179 if (warning.cast_qual &&
6180 is_type_pointer(src_type) &&
6181 is_type_pointer(dst_type)) {
6182 type_t *src = skip_typeref(src_type->pointer.points_to);
6183 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6184 unsigned missing_qualifiers =
6185 src->base.qualifiers & ~dst->base.qualifiers;
6186 if (missing_qualifiers != 0) {
6188 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6189 missing_qualifiers, orig_type_right);
6195 static expression_t *parse_compound_literal(type_t *type)
6197 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6199 parse_initializer_env_t env;
6201 env.declaration = NULL;
6202 env.must_be_constant = false;
6203 initializer_t *initializer = parse_initializer(&env);
6206 expression->compound_literal.initializer = initializer;
6207 expression->compound_literal.type = type;
6208 expression->base.type = automatic_type_conversion(type);
6214 * Parse a cast expression.
6216 static expression_t *parse_cast(void)
6218 add_anchor_token(')');
6220 source_position_t source_position = token.source_position;
6222 type_t *type = parse_typename();
6224 rem_anchor_token(')');
6227 if (token.type == '{') {
6228 return parse_compound_literal(type);
6231 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6232 cast->base.source_position = source_position;
6234 expression_t *value = parse_sub_expression(20);
6235 cast->base.type = type;
6236 cast->unary.value = value;
6238 if (! semantic_cast(cast)) {
6239 /* TODO: record the error in the AST. else it is impossible to detect it */
6244 return create_invalid_expression();
6248 * Parse a statement expression.
6250 static expression_t *parse_statement_expression(void)
6252 add_anchor_token(')');
6254 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6256 statement_t *statement = parse_compound_statement(true);
6257 expression->statement.statement = statement;
6258 expression->base.source_position = statement->base.source_position;
6260 /* find last statement and use its type */
6261 type_t *type = type_void;
6262 const statement_t *stmt = statement->compound.statements;
6264 while (stmt->base.next != NULL)
6265 stmt = stmt->base.next;
6267 if (stmt->kind == STATEMENT_EXPRESSION) {
6268 type = stmt->expression.expression->base.type;
6271 warningf(&expression->base.source_position, "empty statement expression ({})");
6273 expression->base.type = type;
6275 rem_anchor_token(')');
6283 * Parse a parenthesized expression.
6285 static expression_t *parse_parenthesized_expression(void)
6289 switch(token.type) {
6291 /* gcc extension: a statement expression */
6292 return parse_statement_expression();
6296 return parse_cast();
6298 if (is_typedef_symbol(token.v.symbol)) {
6299 return parse_cast();
6303 add_anchor_token(')');
6304 expression_t *result = parse_expression();
6305 rem_anchor_token(')');
6312 static expression_t *parse_function_keyword(void)
6317 if (current_function == NULL) {
6318 errorf(HERE, "'__func__' used outside of a function");
6321 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6322 expression->base.type = type_char_ptr;
6323 expression->funcname.kind = FUNCNAME_FUNCTION;
6328 static expression_t *parse_pretty_function_keyword(void)
6330 eat(T___PRETTY_FUNCTION__);
6332 if (current_function == NULL) {
6333 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6336 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6337 expression->base.type = type_char_ptr;
6338 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6343 static expression_t *parse_funcsig_keyword(void)
6347 if (current_function == NULL) {
6348 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6351 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6352 expression->base.type = type_char_ptr;
6353 expression->funcname.kind = FUNCNAME_FUNCSIG;
6358 static expression_t *parse_funcdname_keyword(void)
6360 eat(T___FUNCDNAME__);
6362 if (current_function == NULL) {
6363 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6366 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6367 expression->base.type = type_char_ptr;
6368 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6373 static designator_t *parse_designator(void)
6375 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6376 result->source_position = *HERE;
6378 if (token.type != T_IDENTIFIER) {
6379 parse_error_expected("while parsing member designator",
6380 T_IDENTIFIER, NULL);
6383 result->symbol = token.v.symbol;
6386 designator_t *last_designator = result;
6388 if (token.type == '.') {
6390 if (token.type != T_IDENTIFIER) {
6391 parse_error_expected("while parsing member designator",
6392 T_IDENTIFIER, NULL);
6395 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6396 designator->source_position = *HERE;
6397 designator->symbol = token.v.symbol;
6400 last_designator->next = designator;
6401 last_designator = designator;
6404 if (token.type == '[') {
6406 add_anchor_token(']');
6407 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6408 designator->source_position = *HERE;
6409 designator->array_index = parse_expression();
6410 rem_anchor_token(']');
6412 if (designator->array_index == NULL) {
6416 last_designator->next = designator;
6417 last_designator = designator;
6429 * Parse the __builtin_offsetof() expression.
6431 static expression_t *parse_offsetof(void)
6433 eat(T___builtin_offsetof);
6435 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6436 expression->base.type = type_size_t;
6439 add_anchor_token(',');
6440 type_t *type = parse_typename();
6441 rem_anchor_token(',');
6443 add_anchor_token(')');
6444 designator_t *designator = parse_designator();
6445 rem_anchor_token(')');
6448 expression->offsetofe.type = type;
6449 expression->offsetofe.designator = designator;
6452 memset(&path, 0, sizeof(path));
6453 path.top_type = type;
6454 path.path = NEW_ARR_F(type_path_entry_t, 0);
6456 descend_into_subtype(&path);
6458 if (!walk_designator(&path, designator, true)) {
6459 return create_invalid_expression();
6462 DEL_ARR_F(path.path);
6466 return create_invalid_expression();
6470 * Parses a _builtin_va_start() expression.
6472 static expression_t *parse_va_start(void)
6474 eat(T___builtin_va_start);
6476 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6479 add_anchor_token(',');
6480 expression->va_starte.ap = parse_assignment_expression();
6481 rem_anchor_token(',');
6483 expression_t *const expr = parse_assignment_expression();
6484 if (expr->kind == EXPR_REFERENCE) {
6485 declaration_t *const decl = expr->reference.declaration;
6486 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6487 errorf(&expr->base.source_position,
6488 "second argument of 'va_start' must be last parameter of the current function");
6490 expression->va_starte.parameter = decl;
6496 return create_invalid_expression();
6500 * Parses a _builtin_va_arg() expression.
6502 static expression_t *parse_va_arg(void)
6504 eat(T___builtin_va_arg);
6506 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6509 expression->va_arge.ap = parse_assignment_expression();
6511 expression->base.type = parse_typename();
6516 return create_invalid_expression();
6519 static expression_t *parse_builtin_symbol(void)
6521 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6523 symbol_t *symbol = token.v.symbol;
6525 expression->builtin_symbol.symbol = symbol;
6528 type_t *type = get_builtin_symbol_type(symbol);
6529 type = automatic_type_conversion(type);
6531 expression->base.type = type;
6536 * Parses a __builtin_constant() expression.
6538 static expression_t *parse_builtin_constant(void)
6540 eat(T___builtin_constant_p);
6542 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6545 add_anchor_token(')');
6546 expression->builtin_constant.value = parse_assignment_expression();
6547 rem_anchor_token(')');
6549 expression->base.type = type_int;
6553 return create_invalid_expression();
6557 * Parses a __builtin_prefetch() expression.
6559 static expression_t *parse_builtin_prefetch(void)
6561 eat(T___builtin_prefetch);
6563 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6566 add_anchor_token(')');
6567 expression->builtin_prefetch.adr = parse_assignment_expression();
6568 if (token.type == ',') {
6570 expression->builtin_prefetch.rw = parse_assignment_expression();
6572 if (token.type == ',') {
6574 expression->builtin_prefetch.locality = parse_assignment_expression();
6576 rem_anchor_token(')');
6578 expression->base.type = type_void;
6582 return create_invalid_expression();
6586 * Parses a __builtin_is_*() compare expression.
6588 static expression_t *parse_compare_builtin(void)
6590 expression_t *expression;
6592 switch(token.type) {
6593 case T___builtin_isgreater:
6594 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6596 case T___builtin_isgreaterequal:
6597 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6599 case T___builtin_isless:
6600 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6602 case T___builtin_islessequal:
6603 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6605 case T___builtin_islessgreater:
6606 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6608 case T___builtin_isunordered:
6609 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6612 internal_errorf(HERE, "invalid compare builtin found");
6615 expression->base.source_position = *HERE;
6619 expression->binary.left = parse_assignment_expression();
6621 expression->binary.right = parse_assignment_expression();
6624 type_t *const orig_type_left = expression->binary.left->base.type;
6625 type_t *const orig_type_right = expression->binary.right->base.type;
6627 type_t *const type_left = skip_typeref(orig_type_left);
6628 type_t *const type_right = skip_typeref(orig_type_right);
6629 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6630 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6631 type_error_incompatible("invalid operands in comparison",
6632 &expression->base.source_position, orig_type_left, orig_type_right);
6635 semantic_comparison(&expression->binary);
6640 return create_invalid_expression();
6645 * Parses a __builtin_expect() expression.
6647 static expression_t *parse_builtin_expect(void)
6649 eat(T___builtin_expect);
6651 expression_t *expression
6652 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6655 expression->binary.left = parse_assignment_expression();
6657 expression->binary.right = parse_constant_expression();
6660 expression->base.type = expression->binary.left->base.type;
6664 return create_invalid_expression();
6669 * Parses a MS assume() expression.
6671 static expression_t *parse_assume(void)
6675 expression_t *expression
6676 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6679 add_anchor_token(')');
6680 expression->unary.value = parse_assignment_expression();
6681 rem_anchor_token(')');
6684 expression->base.type = type_void;
6687 return create_invalid_expression();
6691 * Return the declaration for a given label symbol or create a new one.
6693 * @param symbol the symbol of the label
6695 static declaration_t *get_label(symbol_t *symbol)
6697 declaration_t *candidate;
6698 assert(current_function != NULL);
6700 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6701 /* if we found a local label, we already created the declaration */
6702 if (candidate != NULL) {
6703 assert(candidate->parent_scope == scope);
6707 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6708 /* if we found a label in the same function, then we already created the
6710 if (candidate != NULL
6711 && candidate->parent_scope == ¤t_function->scope) {
6715 /* otherwise we need to create a new one */
6716 declaration_t *const declaration = allocate_declaration_zero();
6717 declaration->namespc = NAMESPACE_LABEL;
6718 declaration->symbol = symbol;
6720 label_push(declaration);
6726 * Parses a GNU && label address expression.
6728 static expression_t *parse_label_address(void)
6730 source_position_t source_position = token.source_position;
6732 if (token.type != T_IDENTIFIER) {
6733 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6736 symbol_t *symbol = token.v.symbol;
6739 declaration_t *label = get_label(symbol);
6742 label->address_taken = true;
6744 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6745 expression->base.source_position = source_position;
6747 /* label address is threaten as a void pointer */
6748 expression->base.type = type_void_ptr;
6749 expression->label_address.declaration = label;
6752 return create_invalid_expression();
6756 * Parse a microsoft __noop expression.
6758 static expression_t *parse_noop_expression(void)
6760 source_position_t source_position = *HERE;
6763 if (token.type == '(') {
6764 /* parse arguments */
6766 add_anchor_token(')');
6767 add_anchor_token(',');
6769 if (token.type != ')') {
6771 (void)parse_assignment_expression();
6772 if (token.type != ',')
6778 rem_anchor_token(',');
6779 rem_anchor_token(')');
6782 /* the result is a (int)0 */
6783 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6784 cnst->base.source_position = source_position;
6785 cnst->base.type = type_int;
6786 cnst->conste.v.int_value = 0;
6787 cnst->conste.is_ms_noop = true;
6792 return create_invalid_expression();
6796 * Parses a primary expression.
6798 static expression_t *parse_primary_expression(void)
6800 switch (token.type) {
6801 case T_INTEGER: return parse_int_const();
6802 case T_CHARACTER_CONSTANT: return parse_character_constant();
6803 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6804 case T_FLOATINGPOINT: return parse_float_const();
6805 case T_STRING_LITERAL:
6806 case T_WIDE_STRING_LITERAL: return parse_string_const();
6807 case T_IDENTIFIER: return parse_reference();
6808 case T___FUNCTION__:
6809 case T___func__: return parse_function_keyword();
6810 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6811 case T___FUNCSIG__: return parse_funcsig_keyword();
6812 case T___FUNCDNAME__: return parse_funcdname_keyword();
6813 case T___builtin_offsetof: return parse_offsetof();
6814 case T___builtin_va_start: return parse_va_start();
6815 case T___builtin_va_arg: return parse_va_arg();
6816 case T___builtin_expect:
6817 case T___builtin_alloca:
6818 case T___builtin_nan:
6819 case T___builtin_nand:
6820 case T___builtin_nanf:
6821 case T___builtin_huge_val:
6822 case T___builtin_va_end: return parse_builtin_symbol();
6823 case T___builtin_isgreater:
6824 case T___builtin_isgreaterequal:
6825 case T___builtin_isless:
6826 case T___builtin_islessequal:
6827 case T___builtin_islessgreater:
6828 case T___builtin_isunordered: return parse_compare_builtin();
6829 case T___builtin_constant_p: return parse_builtin_constant();
6830 case T___builtin_prefetch: return parse_builtin_prefetch();
6831 case T__assume: return parse_assume();
6834 return parse_label_address();
6837 case '(': return parse_parenthesized_expression();
6838 case T___noop: return parse_noop_expression();
6841 errorf(HERE, "unexpected token %K, expected an expression", &token);
6842 return create_invalid_expression();
6846 * Check if the expression has the character type and issue a warning then.
6848 static void check_for_char_index_type(const expression_t *expression)
6850 type_t *const type = expression->base.type;
6851 const type_t *const base_type = skip_typeref(type);
6853 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6854 warning.char_subscripts) {
6855 warningf(&expression->base.source_position,
6856 "array subscript has type '%T'", type);
6860 static expression_t *parse_array_expression(unsigned precedence,
6866 add_anchor_token(']');
6868 expression_t *inside = parse_expression();
6870 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6872 array_access_expression_t *array_access = &expression->array_access;
6874 type_t *const orig_type_left = left->base.type;
6875 type_t *const orig_type_inside = inside->base.type;
6877 type_t *const type_left = skip_typeref(orig_type_left);
6878 type_t *const type_inside = skip_typeref(orig_type_inside);
6880 type_t *return_type;
6881 if (is_type_pointer(type_left)) {
6882 return_type = type_left->pointer.points_to;
6883 array_access->array_ref = left;
6884 array_access->index = inside;
6885 check_for_char_index_type(inside);
6886 } else if (is_type_pointer(type_inside)) {
6887 return_type = type_inside->pointer.points_to;
6888 array_access->array_ref = inside;
6889 array_access->index = left;
6890 array_access->flipped = true;
6891 check_for_char_index_type(left);
6893 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6895 "array access on object with non-pointer types '%T', '%T'",
6896 orig_type_left, orig_type_inside);
6898 return_type = type_error_type;
6899 array_access->array_ref = left;
6900 array_access->index = inside;
6903 expression->base.type = automatic_type_conversion(return_type);
6905 rem_anchor_token(']');
6906 if (token.type == ']') {
6909 parse_error_expected("Problem while parsing array access", ']', NULL);
6914 static expression_t *parse_typeprop(expression_kind_t const kind,
6915 source_position_t const pos,
6916 unsigned const precedence)
6918 expression_t *tp_expression = allocate_expression_zero(kind);
6919 tp_expression->base.type = type_size_t;
6920 tp_expression->base.source_position = pos;
6922 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6924 /* we only refer to a type property, mark this case */
6925 bool old = in_type_prop;
6926 in_type_prop = true;
6927 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6929 add_anchor_token(')');
6930 type_t* const orig_type = parse_typename();
6931 tp_expression->typeprop.type = orig_type;
6933 type_t const* const type = skip_typeref(orig_type);
6934 char const* const wrong_type =
6935 is_type_incomplete(type) ? "incomplete" :
6936 type->kind == TYPE_FUNCTION ? "function designator" :
6937 type->kind == TYPE_BITFIELD ? "bitfield" :
6939 if (wrong_type != NULL) {
6940 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6941 what, wrong_type, type);
6944 rem_anchor_token(')');
6947 expression_t *expression = parse_sub_expression(precedence);
6949 type_t* const orig_type = revert_automatic_type_conversion(expression);
6950 expression->base.type = orig_type;
6952 type_t const* const type = skip_typeref(orig_type);
6953 char const* const wrong_type =
6954 is_type_incomplete(type) ? "incomplete" :
6955 type->kind == TYPE_FUNCTION ? "function designator" :
6956 type->kind == TYPE_BITFIELD ? "bitfield" :
6958 if (wrong_type != NULL) {
6959 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6962 tp_expression->typeprop.type = expression->base.type;
6963 tp_expression->typeprop.tp_expression = expression;
6968 return tp_expression;
6971 static expression_t *parse_sizeof(unsigned precedence)
6973 source_position_t pos = *HERE;
6975 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6978 static expression_t *parse_alignof(unsigned precedence)
6980 source_position_t pos = *HERE;
6982 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6985 static expression_t *parse_select_expression(unsigned precedence,
6986 expression_t *compound)
6989 assert(token.type == '.' || token.type == T_MINUSGREATER);
6991 bool is_pointer = (token.type == T_MINUSGREATER);
6994 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6995 select->select.compound = compound;
6997 if (token.type != T_IDENTIFIER) {
6998 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7001 symbol_t *symbol = token.v.symbol;
7004 type_t *const orig_type = compound->base.type;
7005 type_t *const type = skip_typeref(orig_type);
7008 bool saw_error = false;
7009 if (is_type_pointer(type)) {
7012 "request for member '%Y' in something not a struct or union, but '%T'",
7016 type_left = skip_typeref(type->pointer.points_to);
7018 if (is_pointer && is_type_valid(type)) {
7019 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7025 declaration_t *entry;
7026 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7027 type_left->kind == TYPE_COMPOUND_UNION) {
7028 declaration_t *const declaration = type_left->compound.declaration;
7030 if (!declaration->init.complete) {
7031 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7033 goto create_error_entry;
7036 entry = find_compound_entry(declaration, symbol);
7037 if (entry == NULL) {
7038 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7039 goto create_error_entry;
7042 if (is_type_valid(type_left) && !saw_error) {
7044 "request for member '%Y' in something not a struct or union, but '%T'",
7048 entry = allocate_declaration_zero();
7049 entry->symbol = symbol;
7052 select->select.compound_entry = entry;
7054 type_t *const res_type =
7055 get_qualified_type(entry->type, type_left->base.qualifiers);
7057 /* we always do the auto-type conversions; the & and sizeof parser contains
7058 * code to revert this! */
7059 select->base.type = automatic_type_conversion(res_type);
7061 type_t *skipped = skip_typeref(res_type);
7062 if (skipped->kind == TYPE_BITFIELD) {
7063 select->base.type = skipped->bitfield.base_type;
7069 static void check_call_argument(const function_parameter_t *parameter,
7070 call_argument_t *argument, unsigned pos)
7072 type_t *expected_type = parameter->type;
7073 type_t *expected_type_skip = skip_typeref(expected_type);
7074 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7075 expression_t *arg_expr = argument->expression;
7076 type_t *arg_type = skip_typeref(arg_expr->base.type);
7078 /* handle transparent union gnu extension */
7079 if (is_type_union(expected_type_skip)
7080 && (expected_type_skip->base.modifiers
7081 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7082 declaration_t *union_decl = expected_type_skip->compound.declaration;
7084 declaration_t *declaration = union_decl->scope.declarations;
7085 type_t *best_type = NULL;
7086 for ( ; declaration != NULL; declaration = declaration->next) {
7087 type_t *decl_type = declaration->type;
7088 error = semantic_assign(decl_type, arg_expr);
7089 if (error == ASSIGN_ERROR_INCOMPATIBLE
7090 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7093 if (error == ASSIGN_SUCCESS) {
7094 best_type = decl_type;
7095 } else if (best_type == NULL) {
7096 best_type = decl_type;
7100 if (best_type != NULL) {
7101 expected_type = best_type;
7105 error = semantic_assign(expected_type, arg_expr);
7106 argument->expression = create_implicit_cast(argument->expression,
7109 if (error != ASSIGN_SUCCESS) {
7110 /* report exact scope in error messages (like "in argument 3") */
7112 snprintf(buf, sizeof(buf), "call argument %u", pos);
7113 report_assign_error(error, expected_type, arg_expr, buf,
7114 &arg_expr->base.source_position);
7115 } else if (warning.traditional || warning.conversion) {
7116 type_t *const promoted_type = get_default_promoted_type(arg_type);
7117 if (!types_compatible(expected_type_skip, promoted_type) &&
7118 !types_compatible(expected_type_skip, type_void_ptr) &&
7119 !types_compatible(type_void_ptr, promoted_type)) {
7120 /* Deliberately show the skipped types in this warning */
7121 warningf(&arg_expr->base.source_position,
7122 "passing call argument %u as '%T' rather than '%T' due to prototype",
7123 pos, expected_type_skip, promoted_type);
7129 * Parse a call expression, ie. expression '( ... )'.
7131 * @param expression the function address
7133 static expression_t *parse_call_expression(unsigned precedence,
7134 expression_t *expression)
7137 expression_t *result = allocate_expression_zero(EXPR_CALL);
7138 result->base.source_position = expression->base.source_position;
7140 call_expression_t *call = &result->call;
7141 call->function = expression;
7143 type_t *const orig_type = expression->base.type;
7144 type_t *const type = skip_typeref(orig_type);
7146 function_type_t *function_type = NULL;
7147 if (is_type_pointer(type)) {
7148 type_t *const to_type = skip_typeref(type->pointer.points_to);
7150 if (is_type_function(to_type)) {
7151 function_type = &to_type->function;
7152 call->base.type = function_type->return_type;
7156 if (function_type == NULL && is_type_valid(type)) {
7157 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7160 /* parse arguments */
7162 add_anchor_token(')');
7163 add_anchor_token(',');
7165 if (token.type != ')') {
7166 call_argument_t *last_argument = NULL;
7169 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7171 argument->expression = parse_assignment_expression();
7172 if (last_argument == NULL) {
7173 call->arguments = argument;
7175 last_argument->next = argument;
7177 last_argument = argument;
7179 if (token.type != ',')
7184 rem_anchor_token(',');
7185 rem_anchor_token(')');
7188 if (function_type == NULL)
7191 function_parameter_t *parameter = function_type->parameters;
7192 call_argument_t *argument = call->arguments;
7193 if (!function_type->unspecified_parameters) {
7194 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7195 parameter = parameter->next, argument = argument->next) {
7196 check_call_argument(parameter, argument, ++pos);
7199 if (parameter != NULL) {
7200 errorf(HERE, "too few arguments to function '%E'", expression);
7201 } else if (argument != NULL && !function_type->variadic) {
7202 errorf(HERE, "too many arguments to function '%E'", expression);
7206 /* do default promotion */
7207 for( ; argument != NULL; argument = argument->next) {
7208 type_t *type = argument->expression->base.type;
7210 type = get_default_promoted_type(type);
7212 argument->expression
7213 = create_implicit_cast(argument->expression, type);
7216 check_format(&result->call);
7218 if (warning.aggregate_return &&
7219 is_type_compound(skip_typeref(function_type->return_type))) {
7220 warningf(&result->base.source_position,
7221 "function call has aggregate value");
7228 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7230 static bool same_compound_type(const type_t *type1, const type_t *type2)
7233 is_type_compound(type1) &&
7234 type1->kind == type2->kind &&
7235 type1->compound.declaration == type2->compound.declaration;
7239 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7241 * @param expression the conditional expression
7243 static expression_t *parse_conditional_expression(unsigned precedence,
7244 expression_t *expression)
7246 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7248 conditional_expression_t *conditional = &result->conditional;
7249 conditional->base.source_position = *HERE;
7250 conditional->condition = expression;
7253 add_anchor_token(':');
7256 type_t *const condition_type_orig = expression->base.type;
7257 type_t *const condition_type = skip_typeref(condition_type_orig);
7258 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7259 type_error("expected a scalar type in conditional condition",
7260 &expression->base.source_position, condition_type_orig);
7263 expression_t *true_expression = expression;
7264 bool gnu_cond = false;
7265 if (GNU_MODE && token.type == ':') {
7268 true_expression = parse_expression();
7269 rem_anchor_token(':');
7271 expression_t *false_expression = parse_sub_expression(precedence);
7273 type_t *const orig_true_type = true_expression->base.type;
7274 type_t *const orig_false_type = false_expression->base.type;
7275 type_t *const true_type = skip_typeref(orig_true_type);
7276 type_t *const false_type = skip_typeref(orig_false_type);
7279 type_t *result_type;
7280 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7281 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7282 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7283 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7284 warningf(&conditional->base.source_position,
7285 "ISO C forbids conditional expression with only one void side");
7287 result_type = type_void;
7288 } else if (is_type_arithmetic(true_type)
7289 && is_type_arithmetic(false_type)) {
7290 result_type = semantic_arithmetic(true_type, false_type);
7292 true_expression = create_implicit_cast(true_expression, result_type);
7293 false_expression = create_implicit_cast(false_expression, result_type);
7295 conditional->true_expression = true_expression;
7296 conditional->false_expression = false_expression;
7297 conditional->base.type = result_type;
7298 } else if (same_compound_type(true_type, false_type)) {
7299 /* just take 1 of the 2 types */
7300 result_type = true_type;
7301 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7302 type_t *pointer_type;
7304 expression_t *other_expression;
7305 if (is_type_pointer(true_type) &&
7306 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7307 pointer_type = true_type;
7308 other_type = false_type;
7309 other_expression = false_expression;
7311 pointer_type = false_type;
7312 other_type = true_type;
7313 other_expression = true_expression;
7316 if (is_null_pointer_constant(other_expression)) {
7317 result_type = pointer_type;
7318 } else if (is_type_pointer(other_type)) {
7319 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7320 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7323 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7324 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7326 } else if (types_compatible(get_unqualified_type(to1),
7327 get_unqualified_type(to2))) {
7330 warningf(&conditional->base.source_position,
7331 "pointer types '%T' and '%T' in conditional expression are incompatible",
7332 true_type, false_type);
7336 type_t *const type =
7337 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7338 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7339 } else if (is_type_integer(other_type)) {
7340 warningf(&conditional->base.source_position,
7341 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7342 result_type = pointer_type;
7344 type_error_incompatible("while parsing conditional",
7345 &expression->base.source_position, true_type, false_type);
7346 result_type = type_error_type;
7349 /* TODO: one pointer to void*, other some pointer */
7351 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7352 type_error_incompatible("while parsing conditional",
7353 &conditional->base.source_position, true_type,
7356 result_type = type_error_type;
7359 conditional->true_expression
7360 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7361 conditional->false_expression
7362 = create_implicit_cast(false_expression, result_type);
7363 conditional->base.type = result_type;
7366 return create_invalid_expression();
7370 * Parse an extension expression.
7372 static expression_t *parse_extension(unsigned precedence)
7374 eat(T___extension__);
7376 bool old_gcc_extension = in_gcc_extension;
7377 in_gcc_extension = true;
7378 expression_t *expression = parse_sub_expression(precedence);
7379 in_gcc_extension = old_gcc_extension;
7384 * Parse a __builtin_classify_type() expression.
7386 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7388 eat(T___builtin_classify_type);
7390 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7391 result->base.type = type_int;
7394 add_anchor_token(')');
7395 expression_t *expression = parse_sub_expression(precedence);
7396 rem_anchor_token(')');
7398 result->classify_type.type_expression = expression;
7402 return create_invalid_expression();
7405 static bool check_pointer_arithmetic(const source_position_t *source_position,
7406 type_t *pointer_type,
7407 type_t *orig_pointer_type)
7409 type_t *points_to = pointer_type->pointer.points_to;
7410 points_to = skip_typeref(points_to);
7412 if (is_type_incomplete(points_to)) {
7413 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7414 errorf(source_position,
7415 "arithmetic with pointer to incomplete type '%T' not allowed",
7418 } else if (warning.pointer_arith) {
7419 warningf(source_position,
7420 "pointer of type '%T' used in arithmetic",
7423 } else if (is_type_function(points_to)) {
7425 errorf(source_position,
7426 "arithmetic with pointer to function type '%T' not allowed",
7429 } else if (warning.pointer_arith) {
7430 warningf(source_position,
7431 "pointer to a function '%T' used in arithmetic",
7438 static bool is_lvalue(const expression_t *expression)
7440 switch (expression->kind) {
7441 case EXPR_REFERENCE:
7442 case EXPR_ARRAY_ACCESS:
7444 case EXPR_UNARY_DEREFERENCE:
7452 static void semantic_incdec(unary_expression_t *expression)
7454 type_t *const orig_type = expression->value->base.type;
7455 type_t *const type = skip_typeref(orig_type);
7456 if (is_type_pointer(type)) {
7457 if (!check_pointer_arithmetic(&expression->base.source_position,
7461 } else if (!is_type_real(type) && is_type_valid(type)) {
7462 /* TODO: improve error message */
7463 errorf(&expression->base.source_position,
7464 "operation needs an arithmetic or pointer type");
7467 if (!is_lvalue(expression->value)) {
7468 /* TODO: improve error message */
7469 errorf(&expression->base.source_position, "lvalue required as operand");
7471 expression->base.type = orig_type;
7474 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7476 type_t *const orig_type = expression->value->base.type;
7477 type_t *const type = skip_typeref(orig_type);
7478 if (!is_type_arithmetic(type)) {
7479 if (is_type_valid(type)) {
7480 /* TODO: improve error message */
7481 errorf(&expression->base.source_position,
7482 "operation needs an arithmetic type");
7487 expression->base.type = orig_type;
7490 static void semantic_unexpr_plus(unary_expression_t *expression)
7492 semantic_unexpr_arithmetic(expression);
7493 if (warning.traditional)
7494 warningf(&expression->base.source_position,
7495 "traditional C rejects the unary plus operator");
7498 static void semantic_not(unary_expression_t *expression)
7500 type_t *const orig_type = expression->value->base.type;
7501 type_t *const type = skip_typeref(orig_type);
7502 if (!is_type_scalar(type) && is_type_valid(type)) {
7503 errorf(&expression->base.source_position,
7504 "operand of ! must be of scalar type");
7507 expression->base.type = type_int;
7510 static void semantic_unexpr_integer(unary_expression_t *expression)
7512 type_t *const orig_type = expression->value->base.type;
7513 type_t *const type = skip_typeref(orig_type);
7514 if (!is_type_integer(type)) {
7515 if (is_type_valid(type)) {
7516 errorf(&expression->base.source_position,
7517 "operand of ~ must be of integer type");
7522 expression->base.type = orig_type;
7525 static void semantic_dereference(unary_expression_t *expression)
7527 type_t *const orig_type = expression->value->base.type;
7528 type_t *const type = skip_typeref(orig_type);
7529 if (!is_type_pointer(type)) {
7530 if (is_type_valid(type)) {
7531 errorf(&expression->base.source_position,
7532 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7537 type_t *result_type = type->pointer.points_to;
7538 result_type = automatic_type_conversion(result_type);
7539 expression->base.type = result_type;
7543 * Record that an address is taken (expression represents an lvalue).
7545 * @param expression the expression
7546 * @param may_be_register if true, the expression might be an register
7548 static void set_address_taken(expression_t *expression, bool may_be_register)
7550 if (expression->kind != EXPR_REFERENCE)
7553 declaration_t *const declaration = expression->reference.declaration;
7554 /* happens for parse errors */
7555 if (declaration == NULL)
7558 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7559 errorf(&expression->base.source_position,
7560 "address of register variable '%Y' requested",
7561 declaration->symbol);
7563 declaration->address_taken = 1;
7568 * Check the semantic of the address taken expression.
7570 static void semantic_take_addr(unary_expression_t *expression)
7572 expression_t *value = expression->value;
7573 value->base.type = revert_automatic_type_conversion(value);
7575 type_t *orig_type = value->base.type;
7576 if (!is_type_valid(orig_type))
7579 set_address_taken(value, false);
7581 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7584 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7585 static expression_t *parse_##unexpression_type(unsigned precedence) \
7587 expression_t *unary_expression \
7588 = allocate_expression_zero(unexpression_type); \
7589 unary_expression->base.source_position = *HERE; \
7591 unary_expression->unary.value = parse_sub_expression(precedence); \
7593 sfunc(&unary_expression->unary); \
7595 return unary_expression; \
7598 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7599 semantic_unexpr_arithmetic)
7600 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7601 semantic_unexpr_plus)
7602 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7604 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7605 semantic_dereference)
7606 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7608 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7609 semantic_unexpr_integer)
7610 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7612 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7615 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7617 static expression_t *parse_##unexpression_type(unsigned precedence, \
7618 expression_t *left) \
7620 (void) precedence; \
7622 expression_t *unary_expression \
7623 = allocate_expression_zero(unexpression_type); \
7624 unary_expression->base.source_position = *HERE; \
7626 unary_expression->unary.value = left; \
7628 sfunc(&unary_expression->unary); \
7630 return unary_expression; \
7633 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7634 EXPR_UNARY_POSTFIX_INCREMENT,
7636 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7637 EXPR_UNARY_POSTFIX_DECREMENT,
7640 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7642 /* TODO: handle complex + imaginary types */
7644 type_left = get_unqualified_type(type_left);
7645 type_right = get_unqualified_type(type_right);
7647 /* § 6.3.1.8 Usual arithmetic conversions */
7648 if (type_left == type_long_double || type_right == type_long_double) {
7649 return type_long_double;
7650 } else if (type_left == type_double || type_right == type_double) {
7652 } else if (type_left == type_float || type_right == type_float) {
7656 type_left = promote_integer(type_left);
7657 type_right = promote_integer(type_right);
7659 if (type_left == type_right)
7662 bool const signed_left = is_type_signed(type_left);
7663 bool const signed_right = is_type_signed(type_right);
7664 int const rank_left = get_rank(type_left);
7665 int const rank_right = get_rank(type_right);
7667 if (signed_left == signed_right)
7668 return rank_left >= rank_right ? type_left : type_right;
7677 u_rank = rank_right;
7678 u_type = type_right;
7680 s_rank = rank_right;
7681 s_type = type_right;
7686 if (u_rank >= s_rank)
7689 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7691 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7692 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7696 case ATOMIC_TYPE_INT: return type_unsigned_int;
7697 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7698 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7700 default: panic("invalid atomic type");
7705 * Check the semantic restrictions for a binary expression.
7707 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7709 expression_t *const left = expression->left;
7710 expression_t *const right = expression->right;
7711 type_t *const orig_type_left = left->base.type;
7712 type_t *const orig_type_right = right->base.type;
7713 type_t *const type_left = skip_typeref(orig_type_left);
7714 type_t *const type_right = skip_typeref(orig_type_right);
7716 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7717 /* TODO: improve error message */
7718 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7719 errorf(&expression->base.source_position,
7720 "operation needs arithmetic types");
7725 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7726 expression->left = create_implicit_cast(left, arithmetic_type);
7727 expression->right = create_implicit_cast(right, arithmetic_type);
7728 expression->base.type = arithmetic_type;
7731 static void warn_div_by_zero(binary_expression_t const *const expression)
7733 if (!warning.div_by_zero ||
7734 !is_type_integer(expression->base.type))
7737 expression_t const *const right = expression->right;
7738 /* The type of the right operand can be different for /= */
7739 if (is_type_integer(right->base.type) &&
7740 is_constant_expression(right) &&
7741 fold_constant(right) == 0) {
7742 warningf(&expression->base.source_position, "division by zero");
7747 * Check the semantic restrictions for a div/mod expression.
7749 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7750 semantic_binexpr_arithmetic(expression);
7751 warn_div_by_zero(expression);
7754 static void semantic_shift_op(binary_expression_t *expression)
7756 expression_t *const left = expression->left;
7757 expression_t *const right = expression->right;
7758 type_t *const orig_type_left = left->base.type;
7759 type_t *const orig_type_right = right->base.type;
7760 type_t * type_left = skip_typeref(orig_type_left);
7761 type_t * type_right = skip_typeref(orig_type_right);
7763 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7764 /* TODO: improve error message */
7765 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7766 errorf(&expression->base.source_position,
7767 "operands of shift operation must have integer types");
7772 type_left = promote_integer(type_left);
7773 type_right = promote_integer(type_right);
7775 expression->left = create_implicit_cast(left, type_left);
7776 expression->right = create_implicit_cast(right, type_right);
7777 expression->base.type = type_left;
7780 static void semantic_add(binary_expression_t *expression)
7782 expression_t *const left = expression->left;
7783 expression_t *const right = expression->right;
7784 type_t *const orig_type_left = left->base.type;
7785 type_t *const orig_type_right = right->base.type;
7786 type_t *const type_left = skip_typeref(orig_type_left);
7787 type_t *const type_right = skip_typeref(orig_type_right);
7790 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7791 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7792 expression->left = create_implicit_cast(left, arithmetic_type);
7793 expression->right = create_implicit_cast(right, arithmetic_type);
7794 expression->base.type = arithmetic_type;
7796 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7797 check_pointer_arithmetic(&expression->base.source_position,
7798 type_left, orig_type_left);
7799 expression->base.type = type_left;
7800 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7801 check_pointer_arithmetic(&expression->base.source_position,
7802 type_right, orig_type_right);
7803 expression->base.type = type_right;
7804 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7805 errorf(&expression->base.source_position,
7806 "invalid operands to binary + ('%T', '%T')",
7807 orig_type_left, orig_type_right);
7811 static void semantic_sub(binary_expression_t *expression)
7813 expression_t *const left = expression->left;
7814 expression_t *const right = expression->right;
7815 type_t *const orig_type_left = left->base.type;
7816 type_t *const orig_type_right = right->base.type;
7817 type_t *const type_left = skip_typeref(orig_type_left);
7818 type_t *const type_right = skip_typeref(orig_type_right);
7819 source_position_t const *const pos = &expression->base.source_position;
7822 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7823 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7824 expression->left = create_implicit_cast(left, arithmetic_type);
7825 expression->right = create_implicit_cast(right, arithmetic_type);
7826 expression->base.type = arithmetic_type;
7828 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7829 check_pointer_arithmetic(&expression->base.source_position,
7830 type_left, orig_type_left);
7831 expression->base.type = type_left;
7832 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7833 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7834 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7835 if (!types_compatible(unqual_left, unqual_right)) {
7837 "subtracting pointers to incompatible types '%T' and '%T'",
7838 orig_type_left, orig_type_right);
7839 } else if (!is_type_object(unqual_left)) {
7840 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7841 warningf(pos, "subtracting pointers to void");
7843 errorf(pos, "subtracting pointers to non-object types '%T'",
7847 expression->base.type = type_ptrdiff_t;
7848 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7849 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7850 orig_type_left, orig_type_right);
7855 * Check the semantics of comparison expressions.
7857 * @param expression The expression to check.
7859 static void semantic_comparison(binary_expression_t *expression)
7861 expression_t *left = expression->left;
7862 expression_t *right = expression->right;
7863 type_t *orig_type_left = left->base.type;
7864 type_t *orig_type_right = right->base.type;
7866 type_t *type_left = skip_typeref(orig_type_left);
7867 type_t *type_right = skip_typeref(orig_type_right);
7869 /* TODO non-arithmetic types */
7870 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7871 /* test for signed vs unsigned compares */
7872 if (warning.sign_compare &&
7873 (expression->base.kind != EXPR_BINARY_EQUAL &&
7874 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7875 (is_type_signed(type_left) != is_type_signed(type_right))) {
7877 /* check if 1 of the operands is a constant, in this case we just
7878 * check wether we can safely represent the resulting constant in
7879 * the type of the other operand. */
7880 expression_t *const_expr = NULL;
7881 expression_t *other_expr = NULL;
7883 if (is_constant_expression(left)) {
7886 } else if (is_constant_expression(right)) {
7891 if (const_expr != NULL) {
7892 type_t *other_type = skip_typeref(other_expr->base.type);
7893 long val = fold_constant(const_expr);
7894 /* TODO: check if val can be represented by other_type */
7898 warningf(&expression->base.source_position,
7899 "comparison between signed and unsigned");
7901 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7902 expression->left = create_implicit_cast(left, arithmetic_type);
7903 expression->right = create_implicit_cast(right, arithmetic_type);
7904 expression->base.type = arithmetic_type;
7905 if (warning.float_equal &&
7906 (expression->base.kind == EXPR_BINARY_EQUAL ||
7907 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7908 is_type_float(arithmetic_type)) {
7909 warningf(&expression->base.source_position,
7910 "comparing floating point with == or != is unsafe");
7912 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7913 /* TODO check compatibility */
7914 } else if (is_type_pointer(type_left)) {
7915 expression->right = create_implicit_cast(right, type_left);
7916 } else if (is_type_pointer(type_right)) {
7917 expression->left = create_implicit_cast(left, type_right);
7918 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7919 type_error_incompatible("invalid operands in comparison",
7920 &expression->base.source_position,
7921 type_left, type_right);
7923 expression->base.type = type_int;
7927 * Checks if a compound type has constant fields.
7929 static bool has_const_fields(const compound_type_t *type)
7931 const scope_t *scope = &type->declaration->scope;
7932 const declaration_t *declaration = scope->declarations;
7934 for (; declaration != NULL; declaration = declaration->next) {
7935 if (declaration->namespc != NAMESPACE_NORMAL)
7938 const type_t *decl_type = skip_typeref(declaration->type);
7939 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7946 static bool is_valid_assignment_lhs(expression_t const* const left)
7948 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7949 type_t *const type_left = skip_typeref(orig_type_left);
7951 if (!is_lvalue(left)) {
7952 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7957 if (is_type_array(type_left)) {
7958 errorf(HERE, "cannot assign to arrays ('%E')", left);
7961 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7962 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7966 if (is_type_incomplete(type_left)) {
7967 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7968 left, orig_type_left);
7971 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7972 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7973 left, orig_type_left);
7980 static void semantic_arithmetic_assign(binary_expression_t *expression)
7982 expression_t *left = expression->left;
7983 expression_t *right = expression->right;
7984 type_t *orig_type_left = left->base.type;
7985 type_t *orig_type_right = right->base.type;
7987 if (!is_valid_assignment_lhs(left))
7990 type_t *type_left = skip_typeref(orig_type_left);
7991 type_t *type_right = skip_typeref(orig_type_right);
7993 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7994 /* TODO: improve error message */
7995 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7996 errorf(&expression->base.source_position,
7997 "operation needs arithmetic types");
8002 /* combined instructions are tricky. We can't create an implicit cast on
8003 * the left side, because we need the uncasted form for the store.
8004 * The ast2firm pass has to know that left_type must be right_type
8005 * for the arithmetic operation and create a cast by itself */
8006 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8007 expression->right = create_implicit_cast(right, arithmetic_type);
8008 expression->base.type = type_left;
8011 static void semantic_divmod_assign(binary_expression_t *expression)
8013 semantic_arithmetic_assign(expression);
8014 warn_div_by_zero(expression);
8017 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8019 expression_t *const left = expression->left;
8020 expression_t *const right = expression->right;
8021 type_t *const orig_type_left = left->base.type;
8022 type_t *const orig_type_right = right->base.type;
8023 type_t *const type_left = skip_typeref(orig_type_left);
8024 type_t *const type_right = skip_typeref(orig_type_right);
8026 if (!is_valid_assignment_lhs(left))
8029 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8030 /* combined instructions are tricky. We can't create an implicit cast on
8031 * the left side, because we need the uncasted form for the store.
8032 * The ast2firm pass has to know that left_type must be right_type
8033 * for the arithmetic operation and create a cast by itself */
8034 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8035 expression->right = create_implicit_cast(right, arithmetic_type);
8036 expression->base.type = type_left;
8037 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8038 check_pointer_arithmetic(&expression->base.source_position,
8039 type_left, orig_type_left);
8040 expression->base.type = type_left;
8041 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8042 errorf(&expression->base.source_position,
8043 "incompatible types '%T' and '%T' in assignment",
8044 orig_type_left, orig_type_right);
8049 * Check the semantic restrictions of a logical expression.
8051 static void semantic_logical_op(binary_expression_t *expression)
8053 expression_t *const left = expression->left;
8054 expression_t *const right = expression->right;
8055 type_t *const orig_type_left = left->base.type;
8056 type_t *const orig_type_right = right->base.type;
8057 type_t *const type_left = skip_typeref(orig_type_left);
8058 type_t *const type_right = skip_typeref(orig_type_right);
8060 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8061 /* TODO: improve error message */
8062 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8063 errorf(&expression->base.source_position,
8064 "operation needs scalar types");
8069 expression->base.type = type_int;
8073 * Check the semantic restrictions of a binary assign expression.
8075 static void semantic_binexpr_assign(binary_expression_t *expression)
8077 expression_t *left = expression->left;
8078 type_t *orig_type_left = left->base.type;
8080 if (!is_valid_assignment_lhs(left))
8083 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8084 report_assign_error(error, orig_type_left, expression->right,
8085 "assignment", &left->base.source_position);
8086 expression->right = create_implicit_cast(expression->right, orig_type_left);
8087 expression->base.type = orig_type_left;
8091 * Determine if the outermost operation (or parts thereof) of the given
8092 * expression has no effect in order to generate a warning about this fact.
8093 * Therefore in some cases this only examines some of the operands of the
8094 * expression (see comments in the function and examples below).
8096 * f() + 23; // warning, because + has no effect
8097 * x || f(); // no warning, because x controls execution of f()
8098 * x ? y : f(); // warning, because y has no effect
8099 * (void)x; // no warning to be able to suppress the warning
8100 * This function can NOT be used for an "expression has definitely no effect"-
8102 static bool expression_has_effect(const expression_t *const expr)
8104 switch (expr->kind) {
8105 case EXPR_UNKNOWN: break;
8106 case EXPR_INVALID: return true; /* do NOT warn */
8107 case EXPR_REFERENCE: return false;
8108 /* suppress the warning for microsoft __noop operations */
8109 case EXPR_CONST: return expr->conste.is_ms_noop;
8110 case EXPR_CHARACTER_CONSTANT: return false;
8111 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8112 case EXPR_STRING_LITERAL: return false;
8113 case EXPR_WIDE_STRING_LITERAL: return false;
8114 case EXPR_LABEL_ADDRESS: return false;
8117 const call_expression_t *const call = &expr->call;
8118 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8121 switch (call->function->builtin_symbol.symbol->ID) {
8122 case T___builtin_va_end: return true;
8123 default: return false;
8127 /* Generate the warning if either the left or right hand side of a
8128 * conditional expression has no effect */
8129 case EXPR_CONDITIONAL: {
8130 const conditional_expression_t *const cond = &expr->conditional;
8132 expression_has_effect(cond->true_expression) &&
8133 expression_has_effect(cond->false_expression);
8136 case EXPR_SELECT: return false;
8137 case EXPR_ARRAY_ACCESS: return false;
8138 case EXPR_SIZEOF: return false;
8139 case EXPR_CLASSIFY_TYPE: return false;
8140 case EXPR_ALIGNOF: return false;
8142 case EXPR_FUNCNAME: return false;
8143 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8144 case EXPR_BUILTIN_CONSTANT_P: return false;
8145 case EXPR_BUILTIN_PREFETCH: return true;
8146 case EXPR_OFFSETOF: return false;
8147 case EXPR_VA_START: return true;
8148 case EXPR_VA_ARG: return true;
8149 case EXPR_STATEMENT: return true; // TODO
8150 case EXPR_COMPOUND_LITERAL: return false;
8152 case EXPR_UNARY_NEGATE: return false;
8153 case EXPR_UNARY_PLUS: return false;
8154 case EXPR_UNARY_BITWISE_NEGATE: return false;
8155 case EXPR_UNARY_NOT: return false;
8156 case EXPR_UNARY_DEREFERENCE: return false;
8157 case EXPR_UNARY_TAKE_ADDRESS: return false;
8158 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8159 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8160 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8161 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8163 /* Treat void casts as if they have an effect in order to being able to
8164 * suppress the warning */
8165 case EXPR_UNARY_CAST: {
8166 type_t *const type = skip_typeref(expr->base.type);
8167 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8170 case EXPR_UNARY_CAST_IMPLICIT: return true;
8171 case EXPR_UNARY_ASSUME: return true;
8173 case EXPR_BINARY_ADD: return false;
8174 case EXPR_BINARY_SUB: return false;
8175 case EXPR_BINARY_MUL: return false;
8176 case EXPR_BINARY_DIV: return false;
8177 case EXPR_BINARY_MOD: return false;
8178 case EXPR_BINARY_EQUAL: return false;
8179 case EXPR_BINARY_NOTEQUAL: return false;
8180 case EXPR_BINARY_LESS: return false;
8181 case EXPR_BINARY_LESSEQUAL: return false;
8182 case EXPR_BINARY_GREATER: return false;
8183 case EXPR_BINARY_GREATEREQUAL: return false;
8184 case EXPR_BINARY_BITWISE_AND: return false;
8185 case EXPR_BINARY_BITWISE_OR: return false;
8186 case EXPR_BINARY_BITWISE_XOR: return false;
8187 case EXPR_BINARY_SHIFTLEFT: return false;
8188 case EXPR_BINARY_SHIFTRIGHT: return false;
8189 case EXPR_BINARY_ASSIGN: return true;
8190 case EXPR_BINARY_MUL_ASSIGN: return true;
8191 case EXPR_BINARY_DIV_ASSIGN: return true;
8192 case EXPR_BINARY_MOD_ASSIGN: return true;
8193 case EXPR_BINARY_ADD_ASSIGN: return true;
8194 case EXPR_BINARY_SUB_ASSIGN: return true;
8195 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8196 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8197 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8198 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8199 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8201 /* Only examine the right hand side of && and ||, because the left hand
8202 * side already has the effect of controlling the execution of the right
8204 case EXPR_BINARY_LOGICAL_AND:
8205 case EXPR_BINARY_LOGICAL_OR:
8206 /* Only examine the right hand side of a comma expression, because the left
8207 * hand side has a separate warning */
8208 case EXPR_BINARY_COMMA:
8209 return expression_has_effect(expr->binary.right);
8211 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8212 case EXPR_BINARY_ISGREATER: return false;
8213 case EXPR_BINARY_ISGREATEREQUAL: return false;
8214 case EXPR_BINARY_ISLESS: return false;
8215 case EXPR_BINARY_ISLESSEQUAL: return false;
8216 case EXPR_BINARY_ISLESSGREATER: return false;
8217 case EXPR_BINARY_ISUNORDERED: return false;
8220 internal_errorf(HERE, "unexpected expression");
8223 static void semantic_comma(binary_expression_t *expression)
8225 if (warning.unused_value) {
8226 const expression_t *const left = expression->left;
8227 if (!expression_has_effect(left)) {
8228 warningf(&left->base.source_position,
8229 "left-hand operand of comma expression has no effect");
8232 expression->base.type = expression->right->base.type;
8235 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8236 static expression_t *parse_##binexpression_type(unsigned precedence, \
8237 expression_t *left) \
8239 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8240 binexpr->base.source_position = *HERE; \
8241 binexpr->binary.left = left; \
8244 expression_t *right = parse_sub_expression(precedence + lr); \
8246 binexpr->binary.right = right; \
8247 sfunc(&binexpr->binary); \
8252 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8253 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8254 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8255 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8256 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8257 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8258 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8259 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8260 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8262 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8263 semantic_comparison, 1)
8264 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8265 semantic_comparison, 1)
8266 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8267 semantic_comparison, 1)
8268 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8269 semantic_comparison, 1)
8271 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8272 semantic_binexpr_arithmetic, 1)
8273 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8274 semantic_binexpr_arithmetic, 1)
8275 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8276 semantic_binexpr_arithmetic, 1)
8277 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8278 semantic_logical_op, 1)
8279 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8280 semantic_logical_op, 1)
8281 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8282 semantic_shift_op, 1)
8283 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8284 semantic_shift_op, 1)
8285 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8286 semantic_arithmetic_addsubb_assign, 0)
8287 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8288 semantic_arithmetic_addsubb_assign, 0)
8289 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8290 semantic_arithmetic_assign, 0)
8291 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8292 semantic_divmod_assign, 0)
8293 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8294 semantic_divmod_assign, 0)
8295 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8296 semantic_arithmetic_assign, 0)
8297 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8298 semantic_arithmetic_assign, 0)
8299 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8300 semantic_arithmetic_assign, 0)
8301 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8302 semantic_arithmetic_assign, 0)
8303 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8304 semantic_arithmetic_assign, 0)
8306 static expression_t *parse_sub_expression(unsigned precedence)
8308 if (token.type < 0) {
8309 return expected_expression_error();
8312 expression_parser_function_t *parser
8313 = &expression_parsers[token.type];
8314 source_position_t source_position = token.source_position;
8317 if (parser->parser != NULL) {
8318 left = parser->parser(parser->precedence);
8320 left = parse_primary_expression();
8322 assert(left != NULL);
8323 left->base.source_position = source_position;
8326 if (token.type < 0) {
8327 return expected_expression_error();
8330 parser = &expression_parsers[token.type];
8331 if (parser->infix_parser == NULL)
8333 if (parser->infix_precedence < precedence)
8336 left = parser->infix_parser(parser->infix_precedence, left);
8338 assert(left != NULL);
8339 assert(left->kind != EXPR_UNKNOWN);
8340 left->base.source_position = source_position;
8347 * Parse an expression.
8349 static expression_t *parse_expression(void)
8351 return parse_sub_expression(1);
8355 * Register a parser for a prefix-like operator with given precedence.
8357 * @param parser the parser function
8358 * @param token_type the token type of the prefix token
8359 * @param precedence the precedence of the operator
8361 static void register_expression_parser(parse_expression_function parser,
8362 int token_type, unsigned precedence)
8364 expression_parser_function_t *entry = &expression_parsers[token_type];
8366 if (entry->parser != NULL) {
8367 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8368 panic("trying to register multiple expression parsers for a token");
8370 entry->parser = parser;
8371 entry->precedence = precedence;
8375 * Register a parser for an infix operator with given precedence.
8377 * @param parser the parser function
8378 * @param token_type the token type of the infix operator
8379 * @param precedence the precedence of the operator
8381 static void register_infix_parser(parse_expression_infix_function parser,
8382 int token_type, unsigned precedence)
8384 expression_parser_function_t *entry = &expression_parsers[token_type];
8386 if (entry->infix_parser != NULL) {
8387 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8388 panic("trying to register multiple infix expression parsers for a "
8391 entry->infix_parser = parser;
8392 entry->infix_precedence = precedence;
8396 * Initialize the expression parsers.
8398 static void init_expression_parsers(void)
8400 memset(&expression_parsers, 0, sizeof(expression_parsers));
8402 register_infix_parser(parse_array_expression, '[', 30);
8403 register_infix_parser(parse_call_expression, '(', 30);
8404 register_infix_parser(parse_select_expression, '.', 30);
8405 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8406 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8408 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8411 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8412 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8413 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8414 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8415 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8416 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8417 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8418 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8419 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8420 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8421 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8422 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8423 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8424 T_EXCLAMATIONMARKEQUAL, 13);
8425 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8426 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8427 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8428 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8429 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8430 register_infix_parser(parse_conditional_expression, '?', 7);
8431 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8432 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8433 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8434 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8435 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8436 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8437 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8438 T_LESSLESSEQUAL, 2);
8439 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8440 T_GREATERGREATEREQUAL, 2);
8441 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8443 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8445 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8448 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8450 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8451 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8452 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8453 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8454 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8455 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8456 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8458 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8460 register_expression_parser(parse_sizeof, T_sizeof, 25);
8461 register_expression_parser(parse_alignof, T___alignof__, 25);
8462 register_expression_parser(parse_extension, T___extension__, 25);
8463 register_expression_parser(parse_builtin_classify_type,
8464 T___builtin_classify_type, 25);
8468 * Parse a asm statement arguments specification.
8470 static asm_argument_t *parse_asm_arguments(bool is_out)
8472 asm_argument_t *result = NULL;
8473 asm_argument_t *last = NULL;
8475 while (token.type == T_STRING_LITERAL || token.type == '[') {
8476 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8477 memset(argument, 0, sizeof(argument[0]));
8479 if (token.type == '[') {
8481 if (token.type != T_IDENTIFIER) {
8482 parse_error_expected("while parsing asm argument",
8483 T_IDENTIFIER, NULL);
8486 argument->symbol = token.v.symbol;
8491 argument->constraints = parse_string_literals();
8493 add_anchor_token(')');
8494 expression_t *expression = parse_expression();
8495 rem_anchor_token(')');
8497 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8498 * change size or type representation (e.g. int -> long is ok, but
8499 * int -> float is not) */
8500 if (expression->kind == EXPR_UNARY_CAST) {
8501 type_t *const type = expression->base.type;
8502 type_kind_t const kind = type->kind;
8503 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8506 if (kind == TYPE_ATOMIC) {
8507 atomic_type_kind_t const akind = type->atomic.akind;
8508 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8509 size = get_atomic_type_size(akind);
8511 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8512 size = get_atomic_type_size(get_intptr_kind());
8516 expression_t *const value = expression->unary.value;
8517 type_t *const value_type = value->base.type;
8518 type_kind_t const value_kind = value_type->kind;
8520 unsigned value_flags;
8521 unsigned value_size;
8522 if (value_kind == TYPE_ATOMIC) {
8523 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8524 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8525 value_size = get_atomic_type_size(value_akind);
8526 } else if (value_kind == TYPE_POINTER) {
8527 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8528 value_size = get_atomic_type_size(get_intptr_kind());
8533 if (value_flags != flags || value_size != size)
8537 } while (expression->kind == EXPR_UNARY_CAST);
8541 if (!is_lvalue(expression)) {
8542 errorf(&expression->base.source_position,
8543 "asm output argument is not an lvalue");
8546 argument->expression = expression;
8549 set_address_taken(expression, true);
8552 last->next = argument;
8558 if (token.type != ',')
8569 * Parse a asm statement clobber specification.
8571 static asm_clobber_t *parse_asm_clobbers(void)
8573 asm_clobber_t *result = NULL;
8574 asm_clobber_t *last = NULL;
8576 while(token.type == T_STRING_LITERAL) {
8577 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8578 clobber->clobber = parse_string_literals();
8581 last->next = clobber;
8587 if (token.type != ',')
8596 * Parse an asm statement.
8598 static statement_t *parse_asm_statement(void)
8602 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8603 statement->base.source_position = token.source_position;
8605 asm_statement_t *asm_statement = &statement->asms;
8607 if (token.type == T_volatile) {
8609 asm_statement->is_volatile = true;
8613 add_anchor_token(')');
8614 add_anchor_token(':');
8615 asm_statement->asm_text = parse_string_literals();
8617 if (token.type != ':') {
8618 rem_anchor_token(':');
8623 asm_statement->outputs = parse_asm_arguments(true);
8624 if (token.type != ':') {
8625 rem_anchor_token(':');
8630 asm_statement->inputs = parse_asm_arguments(false);
8631 if (token.type != ':') {
8632 rem_anchor_token(':');
8635 rem_anchor_token(':');
8638 asm_statement->clobbers = parse_asm_clobbers();
8641 rem_anchor_token(')');
8645 if (asm_statement->outputs == NULL) {
8646 /* GCC: An 'asm' instruction without any output operands will be treated
8647 * identically to a volatile 'asm' instruction. */
8648 asm_statement->is_volatile = true;
8653 return create_invalid_statement();
8657 * Parse a case statement.
8659 static statement_t *parse_case_statement(void)
8663 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8664 source_position_t *const pos = &statement->base.source_position;
8666 *pos = token.source_position;
8667 expression_t *const expression = parse_expression();
8668 statement->case_label.expression = expression;
8669 if (!is_constant_expression(expression)) {
8670 /* This check does not prevent the error message in all cases of an
8671 * prior error while parsing the expression. At least it catches the
8672 * common case of a mistyped enum entry. */
8673 if (is_type_valid(expression->base.type)) {
8674 errorf(pos, "case label does not reduce to an integer constant");
8676 statement->case_label.is_bad = true;
8678 long const val = fold_constant(expression);
8679 statement->case_label.first_case = val;
8680 statement->case_label.last_case = val;
8684 if (token.type == T_DOTDOTDOT) {
8686 expression_t *const end_range = parse_expression();
8687 statement->case_label.end_range = end_range;
8688 if (!is_constant_expression(end_range)) {
8689 /* This check does not prevent the error message in all cases of an
8690 * prior error while parsing the expression. At least it catches the
8691 * common case of a mistyped enum entry. */
8692 if (is_type_valid(end_range->base.type)) {
8693 errorf(pos, "case range does not reduce to an integer constant");
8695 statement->case_label.is_bad = true;
8697 long const val = fold_constant(end_range);
8698 statement->case_label.last_case = val;
8700 if (val < statement->case_label.first_case) {
8701 statement->case_label.is_empty_range = true;
8702 warningf(pos, "empty range specified");
8708 PUSH_PARENT(statement);
8712 if (current_switch != NULL) {
8713 if (! statement->case_label.is_bad) {
8714 /* Check for duplicate case values */
8715 case_label_statement_t *c = &statement->case_label;
8716 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8717 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8720 if (c->last_case < l->first_case || c->first_case > l->last_case)
8723 errorf(pos, "duplicate case value (previously used %P)",
8724 &l->base.source_position);
8728 /* link all cases into the switch statement */
8729 if (current_switch->last_case == NULL) {
8730 current_switch->first_case = &statement->case_label;
8732 current_switch->last_case->next = &statement->case_label;
8734 current_switch->last_case = &statement->case_label;
8736 errorf(pos, "case label not within a switch statement");
8739 statement_t *const inner_stmt = parse_statement();
8740 statement->case_label.statement = inner_stmt;
8741 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8742 errorf(&inner_stmt->base.source_position, "declaration after case label");
8749 return create_invalid_statement();
8753 * Parse a default statement.
8755 static statement_t *parse_default_statement(void)
8759 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8760 statement->base.source_position = token.source_position;
8762 PUSH_PARENT(statement);
8765 if (current_switch != NULL) {
8766 const case_label_statement_t *def_label = current_switch->default_label;
8767 if (def_label != NULL) {
8768 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8769 &def_label->base.source_position);
8771 current_switch->default_label = &statement->case_label;
8773 /* link all cases into the switch statement */
8774 if (current_switch->last_case == NULL) {
8775 current_switch->first_case = &statement->case_label;
8777 current_switch->last_case->next = &statement->case_label;
8779 current_switch->last_case = &statement->case_label;
8782 errorf(&statement->base.source_position,
8783 "'default' label not within a switch statement");
8786 statement_t *const inner_stmt = parse_statement();
8787 statement->case_label.statement = inner_stmt;
8788 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8789 errorf(&inner_stmt->base.source_position, "declaration after default label");
8796 return create_invalid_statement();
8800 * Parse a label statement.
8802 static statement_t *parse_label_statement(void)
8804 assert(token.type == T_IDENTIFIER);
8805 symbol_t *symbol = token.v.symbol;
8808 declaration_t *label = get_label(symbol);
8810 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8811 statement->base.source_position = token.source_position;
8812 statement->label.label = label;
8814 PUSH_PARENT(statement);
8816 /* if statement is already set then the label is defined twice,
8817 * otherwise it was just mentioned in a goto/local label declaration so far */
8818 if (label->init.statement != NULL) {
8819 errorf(HERE, "duplicate label '%Y' (declared %P)",
8820 symbol, &label->source_position);
8822 label->source_position = token.source_position;
8823 label->init.statement = statement;
8828 if (token.type == '}') {
8829 /* TODO only warn? */
8831 warningf(HERE, "label at end of compound statement");
8832 statement->label.statement = create_empty_statement();
8834 errorf(HERE, "label at end of compound statement");
8835 statement->label.statement = create_invalid_statement();
8837 } else if (token.type == ';') {
8838 /* Eat an empty statement here, to avoid the warning about an empty
8839 * statement after a label. label:; is commonly used to have a label
8840 * before a closing brace. */
8841 statement->label.statement = create_empty_statement();
8844 statement_t *const inner_stmt = parse_statement();
8845 statement->label.statement = inner_stmt;
8846 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8847 errorf(&inner_stmt->base.source_position, "declaration after label");
8851 /* remember the labels in a list for later checking */
8852 if (label_last == NULL) {
8853 label_first = &statement->label;
8855 label_last->next = &statement->label;
8857 label_last = &statement->label;
8864 * Parse an if statement.
8866 static statement_t *parse_if(void)
8870 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8871 statement->base.source_position = token.source_position;
8873 PUSH_PARENT(statement);
8876 add_anchor_token(')');
8877 statement->ifs.condition = parse_expression();
8878 rem_anchor_token(')');
8881 add_anchor_token(T_else);
8882 statement->ifs.true_statement = parse_statement();
8883 rem_anchor_token(T_else);
8885 if (token.type == T_else) {
8887 statement->ifs.false_statement = parse_statement();
8894 return create_invalid_statement();
8898 * Check that all enums are handled in a switch.
8900 * @param statement the switch statement to check
8902 static void check_enum_cases(const switch_statement_t *statement) {
8903 const type_t *type = skip_typeref(statement->expression->base.type);
8904 if (! is_type_enum(type))
8906 const enum_type_t *enumt = &type->enumt;
8908 /* if we have a default, no warnings */
8909 if (statement->default_label != NULL)
8912 /* FIXME: calculation of value should be done while parsing */
8913 const declaration_t *declaration;
8914 long last_value = -1;
8915 for (declaration = enumt->declaration->next;
8916 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8917 declaration = declaration->next) {
8918 const expression_t *expression = declaration->init.enum_value;
8919 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8921 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8922 if (l->expression == NULL)
8924 if (l->first_case <= value && value <= l->last_case) {
8930 warningf(&statement->base.source_position,
8931 "enumeration value '%Y' not handled in switch", declaration->symbol);
8938 * Parse a switch statement.
8940 static statement_t *parse_switch(void)
8944 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8945 statement->base.source_position = token.source_position;
8947 PUSH_PARENT(statement);
8950 add_anchor_token(')');
8951 expression_t *const expr = parse_expression();
8952 type_t * type = skip_typeref(expr->base.type);
8953 if (is_type_integer(type)) {
8954 type = promote_integer(type);
8955 if (warning.traditional) {
8956 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8957 warningf(&expr->base.source_position,
8958 "'%T' switch expression not converted to '%T' in ISO C",
8962 } else if (is_type_valid(type)) {
8963 errorf(&expr->base.source_position,
8964 "switch quantity is not an integer, but '%T'", type);
8965 type = type_error_type;
8967 statement->switchs.expression = create_implicit_cast(expr, type);
8969 rem_anchor_token(')');
8971 switch_statement_t *rem = current_switch;
8972 current_switch = &statement->switchs;
8973 statement->switchs.body = parse_statement();
8974 current_switch = rem;
8976 if (warning.switch_default &&
8977 statement->switchs.default_label == NULL) {
8978 warningf(&statement->base.source_position, "switch has no default case");
8980 if (warning.switch_enum)
8981 check_enum_cases(&statement->switchs);
8987 return create_invalid_statement();
8990 static statement_t *parse_loop_body(statement_t *const loop)
8992 statement_t *const rem = current_loop;
8993 current_loop = loop;
8995 statement_t *const body = parse_statement();
9002 * Parse a while statement.
9004 static statement_t *parse_while(void)
9008 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9009 statement->base.source_position = token.source_position;
9011 PUSH_PARENT(statement);
9014 add_anchor_token(')');
9015 statement->whiles.condition = parse_expression();
9016 rem_anchor_token(')');
9019 statement->whiles.body = parse_loop_body(statement);
9025 return create_invalid_statement();
9029 * Parse a do statement.
9031 static statement_t *parse_do(void)
9035 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9036 statement->base.source_position = token.source_position;
9038 PUSH_PARENT(statement)
9040 add_anchor_token(T_while);
9041 statement->do_while.body = parse_loop_body(statement);
9042 rem_anchor_token(T_while);
9046 add_anchor_token(')');
9047 statement->do_while.condition = parse_expression();
9048 rem_anchor_token(')');
9056 return create_invalid_statement();
9060 * Parse a for statement.
9062 static statement_t *parse_for(void)
9066 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9067 statement->base.source_position = token.source_position;
9069 PUSH_PARENT(statement);
9071 int top = environment_top();
9072 scope_t *last_scope = scope;
9073 set_scope(&statement->fors.scope);
9076 add_anchor_token(')');
9078 if (token.type != ';') {
9079 if (is_declaration_specifier(&token, false)) {
9080 parse_declaration(record_declaration);
9082 add_anchor_token(';');
9083 expression_t *const init = parse_expression();
9084 statement->fors.initialisation = init;
9085 if (warning.unused_value && !expression_has_effect(init)) {
9086 warningf(&init->base.source_position,
9087 "initialisation of 'for'-statement has no effect");
9089 rem_anchor_token(';');
9096 if (token.type != ';') {
9097 add_anchor_token(';');
9098 statement->fors.condition = parse_expression();
9099 rem_anchor_token(';');
9102 if (token.type != ')') {
9103 expression_t *const step = parse_expression();
9104 statement->fors.step = step;
9105 if (warning.unused_value && !expression_has_effect(step)) {
9106 warningf(&step->base.source_position,
9107 "step of 'for'-statement has no effect");
9110 rem_anchor_token(')');
9112 statement->fors.body = parse_loop_body(statement);
9114 assert(scope == &statement->fors.scope);
9115 set_scope(last_scope);
9116 environment_pop_to(top);
9123 rem_anchor_token(')');
9124 assert(scope == &statement->fors.scope);
9125 set_scope(last_scope);
9126 environment_pop_to(top);
9128 return create_invalid_statement();
9132 * Parse a goto statement.
9134 static statement_t *parse_goto(void)
9136 source_position_t source_position = token.source_position;
9139 statement_t *statement;
9140 if (GNU_MODE && token.type == '*') {
9142 expression_t *expression = parse_expression();
9144 /* Argh: although documentation say the expression must be of type void *,
9145 * gcc excepts anything that can be casted into void * without error */
9146 type_t *type = expression->base.type;
9148 if (type != type_error_type) {
9149 if (!is_type_pointer(type) && !is_type_integer(type)) {
9150 errorf(&source_position, "cannot convert to a pointer type");
9151 } else if (type != type_void_ptr) {
9152 warningf(&source_position,
9153 "type of computed goto expression should be 'void*' not '%T'", type);
9155 expression = create_implicit_cast(expression, type_void_ptr);
9158 statement = allocate_statement_zero(STATEMENT_GOTO);
9159 statement->base.source_position = source_position;
9160 statement->gotos.expression = expression;
9162 if (token.type != T_IDENTIFIER) {
9164 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9166 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9170 symbol_t *symbol = token.v.symbol;
9173 statement = allocate_statement_zero(STATEMENT_GOTO);
9174 statement->base.source_position = source_position;
9175 statement->gotos.label = get_label(symbol);
9178 /* remember the goto's in a list for later checking */
9179 if (goto_last == NULL) {
9180 goto_first = &statement->gotos;
9182 goto_last->next = &statement->gotos;
9184 goto_last = &statement->gotos;
9190 return create_invalid_statement();
9194 * Parse a continue statement.
9196 static statement_t *parse_continue(void)
9198 if (current_loop == NULL) {
9199 errorf(HERE, "continue statement not within loop");
9202 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9203 statement->base.source_position = token.source_position;
9213 * Parse a break statement.
9215 static statement_t *parse_break(void)
9217 if (current_switch == NULL && current_loop == NULL) {
9218 errorf(HERE, "break statement not within loop or switch");
9221 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9222 statement->base.source_position = token.source_position;
9232 * Parse a __leave statement.
9234 static statement_t *parse_leave_statement(void)
9236 if (current_try == NULL) {
9237 errorf(HERE, "__leave statement not within __try");
9240 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9241 statement->base.source_position = token.source_position;
9251 * Check if a given declaration represents a local variable.
9253 static bool is_local_var_declaration(const declaration_t *declaration)
9255 switch ((storage_class_tag_t) declaration->storage_class) {
9256 case STORAGE_CLASS_AUTO:
9257 case STORAGE_CLASS_REGISTER: {
9258 const type_t *type = skip_typeref(declaration->type);
9259 if (is_type_function(type)) {
9271 * Check if a given declaration represents a variable.
9273 static bool is_var_declaration(const declaration_t *declaration)
9275 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9278 const type_t *type = skip_typeref(declaration->type);
9279 return !is_type_function(type);
9283 * Check if a given expression represents a local variable.
9285 static bool is_local_variable(const expression_t *expression)
9287 if (expression->base.kind != EXPR_REFERENCE) {
9290 const declaration_t *declaration = expression->reference.declaration;
9291 return is_local_var_declaration(declaration);
9295 * Check if a given expression represents a local variable and
9296 * return its declaration then, else return NULL.
9298 declaration_t *expr_is_variable(const expression_t *expression)
9300 if (expression->base.kind != EXPR_REFERENCE) {
9303 declaration_t *declaration = expression->reference.declaration;
9304 if (is_var_declaration(declaration))
9310 * Parse a return statement.
9312 static statement_t *parse_return(void)
9314 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9315 statement->base.source_position = token.source_position;
9319 expression_t *return_value = NULL;
9320 if (token.type != ';') {
9321 return_value = parse_expression();
9324 const type_t *const func_type = current_function->type;
9325 assert(is_type_function(func_type));
9326 type_t *const return_type = skip_typeref(func_type->function.return_type);
9328 if (return_value != NULL) {
9329 type_t *return_value_type = skip_typeref(return_value->base.type);
9331 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9332 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9333 warningf(&statement->base.source_position,
9334 "'return' with a value, in function returning void");
9335 return_value = NULL;
9337 assign_error_t error = semantic_assign(return_type, return_value);
9338 report_assign_error(error, return_type, return_value, "'return'",
9339 &statement->base.source_position);
9340 return_value = create_implicit_cast(return_value, return_type);
9342 /* check for returning address of a local var */
9343 if (return_value != NULL &&
9344 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9345 const expression_t *expression = return_value->unary.value;
9346 if (is_local_variable(expression)) {
9347 warningf(&statement->base.source_position,
9348 "function returns address of local variable");
9352 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9353 warningf(&statement->base.source_position,
9354 "'return' without value, in function returning non-void");
9357 statement->returns.value = return_value;
9366 * Parse a declaration statement.
9368 static statement_t *parse_declaration_statement(void)
9370 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9372 statement->base.source_position = token.source_position;
9374 declaration_t *before = last_declaration;
9376 parse_external_declaration();
9378 parse_declaration(record_declaration);
9380 if (before == NULL) {
9381 statement->declaration.declarations_begin = scope->declarations;
9383 statement->declaration.declarations_begin = before->next;
9385 statement->declaration.declarations_end = last_declaration;
9391 * Parse an expression statement, ie. expr ';'.
9393 static statement_t *parse_expression_statement(void)
9395 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9397 statement->base.source_position = token.source_position;
9398 expression_t *const expr = parse_expression();
9399 statement->expression.expression = expr;
9408 * Parse a microsoft __try { } __finally { } or
9409 * __try{ } __except() { }
9411 static statement_t *parse_ms_try_statment(void)
9413 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9414 statement->base.source_position = token.source_position;
9417 PUSH_PARENT(statement);
9419 ms_try_statement_t *rem = current_try;
9420 current_try = &statement->ms_try;
9421 statement->ms_try.try_statement = parse_compound_statement(false);
9426 if (token.type == T___except) {
9429 add_anchor_token(')');
9430 expression_t *const expr = parse_expression();
9431 type_t * type = skip_typeref(expr->base.type);
9432 if (is_type_integer(type)) {
9433 type = promote_integer(type);
9434 } else if (is_type_valid(type)) {
9435 errorf(&expr->base.source_position,
9436 "__expect expression is not an integer, but '%T'", type);
9437 type = type_error_type;
9439 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9440 rem_anchor_token(')');
9442 statement->ms_try.final_statement = parse_compound_statement(false);
9443 } else if (token.type == T__finally) {
9445 statement->ms_try.final_statement = parse_compound_statement(false);
9447 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9448 return create_invalid_statement();
9452 return create_invalid_statement();
9455 static statement_t *parse_empty_statement(void)
9457 if (warning.empty_statement) {
9458 warningf(HERE, "statement is empty");
9460 statement_t *const statement = create_empty_statement();
9465 static statement_t *parse_local_label_declaration(void) {
9466 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9467 statement->base.source_position = token.source_position;
9471 declaration_t *begin = NULL, *end = NULL;
9474 if (token.type != T_IDENTIFIER) {
9475 parse_error_expected("while parsing local label declaration",
9476 T_IDENTIFIER, NULL);
9479 symbol_t *symbol = token.v.symbol;
9480 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9481 if (declaration != NULL) {
9482 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9483 symbol, &declaration->source_position);
9485 declaration = allocate_declaration_zero();
9486 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9487 declaration->source_position = token.source_position;
9488 declaration->symbol = symbol;
9489 declaration->parent_scope = scope;
9490 declaration->init.statement = NULL;
9493 end->next = declaration;
9496 begin = declaration;
9498 local_label_push(declaration);
9502 if (token.type != ',')
9508 statement->declaration.declarations_begin = begin;
9509 statement->declaration.declarations_end = end;
9514 * Parse a statement.
9515 * There's also parse_statement() which additionally checks for
9516 * "statement has no effect" warnings
9518 static statement_t *intern_parse_statement(void)
9520 statement_t *statement = NULL;
9522 /* declaration or statement */
9523 add_anchor_token(';');
9524 switch (token.type) {
9525 case T_IDENTIFIER: {
9526 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9527 if (la1_type == ':') {
9528 statement = parse_label_statement();
9529 } else if (is_typedef_symbol(token.v.symbol)) {
9530 statement = parse_declaration_statement();
9531 } else switch (la1_type) {
9533 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9534 goto expression_statment;
9539 statement = parse_declaration_statement();
9543 expression_statment:
9544 statement = parse_expression_statement();
9550 case T___extension__:
9551 /* This can be a prefix to a declaration or an expression statement.
9552 * We simply eat it now and parse the rest with tail recursion. */
9555 } while (token.type == T___extension__);
9556 bool old_gcc_extension = in_gcc_extension;
9557 in_gcc_extension = true;
9558 statement = parse_statement();
9559 in_gcc_extension = false;
9563 statement = parse_declaration_statement();
9567 statement = parse_local_label_declaration();
9570 case ';': statement = parse_empty_statement(); break;
9571 case '{': statement = parse_compound_statement(false); break;
9572 case T___leave: statement = parse_leave_statement(); break;
9573 case T___try: statement = parse_ms_try_statment(); break;
9574 case T_asm: statement = parse_asm_statement(); break;
9575 case T_break: statement = parse_break(); break;
9576 case T_case: statement = parse_case_statement(); break;
9577 case T_continue: statement = parse_continue(); break;
9578 case T_default: statement = parse_default_statement(); break;
9579 case T_do: statement = parse_do(); break;
9580 case T_for: statement = parse_for(); break;
9581 case T_goto: statement = parse_goto(); break;
9582 case T_if: statement = parse_if (); break;
9583 case T_return: statement = parse_return(); break;
9584 case T_switch: statement = parse_switch(); break;
9585 case T_while: statement = parse_while(); break;
9595 case T_CHARACTER_CONSTANT:
9596 case T_FLOATINGPOINT:
9600 case T_STRING_LITERAL:
9601 case T_WIDE_CHARACTER_CONSTANT:
9602 case T_WIDE_STRING_LITERAL:
9603 case T___FUNCDNAME__:
9605 case T___FUNCTION__:
9606 case T___PRETTY_FUNCTION__:
9607 case T___builtin_alloca:
9608 case T___builtin_classify_type:
9609 case T___builtin_constant_p:
9610 case T___builtin_expect:
9611 case T___builtin_huge_val:
9612 case T___builtin_isgreater:
9613 case T___builtin_isgreaterequal:
9614 case T___builtin_isless:
9615 case T___builtin_islessequal:
9616 case T___builtin_islessgreater:
9617 case T___builtin_isunordered:
9618 case T___builtin_nan:
9619 case T___builtin_nand:
9620 case T___builtin_nanf:
9621 case T___builtin_offsetof:
9622 case T___builtin_prefetch:
9623 case T___builtin_va_arg:
9624 case T___builtin_va_end:
9625 case T___builtin_va_start:
9629 statement = parse_expression_statement();
9633 errorf(HERE, "unexpected token %K while parsing statement", &token);
9634 statement = create_invalid_statement();
9639 rem_anchor_token(';');
9641 assert(statement != NULL
9642 && statement->base.source_position.input_name != NULL);
9648 * parse a statement and emits "statement has no effect" warning if needed
9649 * (This is really a wrapper around intern_parse_statement with check for 1
9650 * single warning. It is needed, because for statement expressions we have
9651 * to avoid the warning on the last statement)
9653 static statement_t *parse_statement(void)
9655 statement_t *statement = intern_parse_statement();
9657 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9658 expression_t *expression = statement->expression.expression;
9659 if (!expression_has_effect(expression)) {
9660 warningf(&expression->base.source_position,
9661 "statement has no effect");
9669 * Parse a compound statement.
9671 static statement_t *parse_compound_statement(bool inside_expression_statement)
9673 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9674 statement->base.source_position = token.source_position;
9676 PUSH_PARENT(statement);
9679 add_anchor_token('}');
9681 int top = environment_top();
9682 int top_local = local_label_top();
9683 scope_t *last_scope = scope;
9684 set_scope(&statement->compound.scope);
9686 statement_t **anchor = &statement->compound.statements;
9687 bool only_decls_so_far = true;
9688 while (token.type != '}' && token.type != T_EOF) {
9689 statement_t *sub_statement = intern_parse_statement();
9690 if (is_invalid_statement(sub_statement)) {
9691 /* an error occurred. if we are at an anchor, return */
9697 if (warning.declaration_after_statement) {
9698 if (sub_statement->kind != STATEMENT_DECLARATION) {
9699 only_decls_so_far = false;
9700 } else if (!only_decls_so_far) {
9701 warningf(&sub_statement->base.source_position,
9702 "ISO C90 forbids mixed declarations and code");
9706 *anchor = sub_statement;
9708 while (sub_statement->base.next != NULL)
9709 sub_statement = sub_statement->base.next;
9711 anchor = &sub_statement->base.next;
9714 if (token.type == '}') {
9717 errorf(&statement->base.source_position,
9718 "end of file while looking for closing '}'");
9721 /* look over all statements again to produce no effect warnings */
9722 if (warning.unused_value) {
9723 statement_t *sub_statement = statement->compound.statements;
9724 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9725 if (sub_statement->kind != STATEMENT_EXPRESSION)
9727 /* don't emit a warning for the last expression in an expression
9728 * statement as it has always an effect */
9729 if (inside_expression_statement && sub_statement->base.next == NULL)
9732 expression_t *expression = sub_statement->expression.expression;
9733 if (!expression_has_effect(expression)) {
9734 warningf(&expression->base.source_position,
9735 "statement has no effect");
9741 rem_anchor_token('}');
9742 assert(scope == &statement->compound.scope);
9743 set_scope(last_scope);
9744 environment_pop_to(top);
9745 local_label_pop_to(top_local);
9752 * Initialize builtin types.
9754 static void initialize_builtin_types(void)
9756 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9757 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9758 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9759 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9760 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9761 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9762 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9763 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9765 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9766 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9767 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9768 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9770 /* const version of wchar_t */
9771 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9772 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9773 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9775 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9779 * Check for unused global static functions and variables
9781 static void check_unused_globals(void)
9783 if (!warning.unused_function && !warning.unused_variable)
9786 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9788 decl->modifiers & DM_UNUSED ||
9789 decl->modifiers & DM_USED ||
9790 decl->storage_class != STORAGE_CLASS_STATIC)
9793 type_t *const type = decl->type;
9795 if (is_type_function(skip_typeref(type))) {
9796 if (!warning.unused_function || decl->is_inline)
9799 s = (decl->init.statement != NULL ? "defined" : "declared");
9801 if (!warning.unused_variable)
9807 warningf(&decl->source_position, "'%#T' %s but not used",
9808 type, decl->symbol, s);
9812 static void parse_global_asm(void)
9817 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9818 statement->base.source_position = token.source_position;
9819 statement->asms.asm_text = parse_string_literals();
9820 statement->base.next = unit->global_asm;
9821 unit->global_asm = statement;
9830 * Parse a translation unit.
9832 static void parse_translation_unit(void)
9836 bool anchor_leak = false;
9837 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9838 unsigned char count = token_anchor_set[i];
9840 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9844 if (in_gcc_extension) {
9845 errorf(HERE, "Leaked __extension__");
9853 switch (token.type) {
9856 case T___extension__:
9857 parse_external_declaration();
9868 /* TODO error in strict mode */
9869 warningf(HERE, "stray ';' outside of function");
9874 errorf(HERE, "stray %K outside of function", &token);
9875 if (token.type == '(' || token.type == '{' || token.type == '[')
9876 eat_until_matching_token(token.type);
9886 * @return the translation unit or NULL if errors occurred.
9888 void start_parsing(void)
9890 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9891 label_stack = NEW_ARR_F(stack_entry_t, 0);
9892 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
9893 diagnostic_count = 0;
9897 type_set_output(stderr);
9898 ast_set_output(stderr);
9900 assert(unit == NULL);
9901 unit = allocate_ast_zero(sizeof(unit[0]));
9903 assert(global_scope == NULL);
9904 global_scope = &unit->scope;
9906 assert(scope == NULL);
9907 set_scope(&unit->scope);
9909 initialize_builtin_types();
9912 translation_unit_t *finish_parsing(void)
9914 assert(scope == &unit->scope);
9916 last_declaration = NULL;
9918 assert(global_scope == &unit->scope);
9919 check_unused_globals();
9920 global_scope = NULL;
9922 DEL_ARR_F(environment_stack);
9923 DEL_ARR_F(label_stack);
9924 DEL_ARR_F(local_label_stack);
9926 translation_unit_t *result = unit;
9933 lookahead_bufpos = 0;
9934 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9937 parse_translation_unit();
9941 * Initialize the parser.
9943 void init_parser(void)
9945 sym_anonymous = symbol_table_insert("<anonymous>");
9948 /* add predefined symbols for extended-decl-modifier */
9949 sym_align = symbol_table_insert("align");
9950 sym_allocate = symbol_table_insert("allocate");
9951 sym_dllimport = symbol_table_insert("dllimport");
9952 sym_dllexport = symbol_table_insert("dllexport");
9953 sym_naked = symbol_table_insert("naked");
9954 sym_noinline = symbol_table_insert("noinline");
9955 sym_noreturn = symbol_table_insert("noreturn");
9956 sym_nothrow = symbol_table_insert("nothrow");
9957 sym_novtable = symbol_table_insert("novtable");
9958 sym_property = symbol_table_insert("property");
9959 sym_get = symbol_table_insert("get");
9960 sym_put = symbol_table_insert("put");
9961 sym_selectany = symbol_table_insert("selectany");
9962 sym_thread = symbol_table_insert("thread");
9963 sym_uuid = symbol_table_insert("uuid");
9964 sym_deprecated = symbol_table_insert("deprecated");
9965 sym_restrict = symbol_table_insert("restrict");
9966 sym_noalias = symbol_table_insert("noalias");
9968 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9970 init_expression_parsers();
9971 obstack_init(&temp_obst);
9973 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9974 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9978 * Terminate the parser.
9980 void exit_parser(void)
9982 obstack_free(&temp_obst, NULL);