2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
108 /** The current token. */
109 static token_t token;
110 /** The lookahead ring-buffer. */
111 static token_t lookahead_buffer[MAX_LOOKAHEAD];
112 /** Position of the next token in the lookahead buffer. */
113 static int lookahead_bufpos;
114 static stack_entry_t *environment_stack = NULL;
115 static stack_entry_t *label_stack = NULL;
116 static stack_entry_t *local_label_stack = NULL;
117 /** The global file scope. */
118 static scope_t *file_scope = NULL;
119 /** The current scope. */
120 static scope_t *scope = NULL;
121 static declaration_t *last_declaration = NULL;
122 /** Point to the current function declaration if inside a function. */
123 static declaration_t *current_function = NULL;
124 static declaration_t *current_init_decl = NULL;
125 static switch_statement_t *current_switch = NULL;
126 static statement_t *current_loop = NULL;
127 static statement_t *current_parent = NULL;
128 static ms_try_statement_t *current_try = NULL;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t *goto_last = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t *label_last = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
142 #define PUSH_PARENT(stmt) \
143 statement_t *const prev_parent = current_parent; \
144 ((void)(current_parent = (stmt)))
145 #define POP_PARENT ((void)(current_parent = prev_parent))
147 static source_position_t null_position = { NULL, 0 };
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_noreturn = NULL;
160 static const symbol_t *sym_nothrow = NULL;
161 static const symbol_t *sym_novtable = NULL;
162 static const symbol_t *sym_property = NULL;
163 static const symbol_t *sym_get = NULL;
164 static const symbol_t *sym_put = NULL;
165 static const symbol_t *sym_selectany = NULL;
166 static const symbol_t *sym_thread = NULL;
167 static const symbol_t *sym_uuid = NULL;
168 static const symbol_t *sym_deprecated = NULL;
169 static const symbol_t *sym_restrict = NULL;
170 static const symbol_t *sym_noalias = NULL;
172 /** The token anchor set */
173 static unsigned char token_anchor_set[T_LAST_TOKEN];
175 /** The current source position. */
176 #define HERE (&token.source_position)
178 /** true if we are in GCC mode. */
179 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
181 static type_t *type_valist;
183 static statement_t *parse_compound_statement(bool inside_expression_statement);
184 static statement_t *parse_statement(void);
186 static expression_t *parse_sub_expression(unsigned precedence);
187 static expression_t *parse_expression(void);
188 static type_t *parse_typename(void);
190 static void parse_compound_type_entries(declaration_t *compound_declaration);
191 static declaration_t *parse_declarator(
192 const declaration_specifiers_t *specifiers, bool may_be_abstract);
193 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
195 static void semantic_comparison(binary_expression_t *expression);
197 #define STORAGE_CLASSES \
205 #define TYPE_QUALIFIERS \
210 case T__forceinline: \
211 case T___attribute__:
213 #ifdef PROVIDE_COMPLEX
214 #define COMPLEX_SPECIFIERS \
216 #define IMAGINARY_SPECIFIERS \
219 #define COMPLEX_SPECIFIERS
220 #define IMAGINARY_SPECIFIERS
223 #define TYPE_SPECIFIERS \
238 case T___builtin_va_list: \
243 #define DECLARATION_START \
248 #define TYPENAME_START \
253 * Allocate an AST node with given size and
254 * initialize all fields with zero.
256 static void *allocate_ast_zero(size_t size)
258 void *res = allocate_ast(size);
259 memset(res, 0, size);
263 static declaration_t *allocate_declaration_zero(void)
265 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
266 declaration->type = type_error_type;
267 declaration->alignment = 0;
272 * Returns the size of a statement node.
274 * @param kind the statement kind
276 static size_t get_statement_struct_size(statement_kind_t kind)
278 static const size_t sizes[] = {
279 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
280 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
281 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
282 [STATEMENT_RETURN] = sizeof(return_statement_t),
283 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
284 [STATEMENT_IF] = sizeof(if_statement_t),
285 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
286 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
287 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
288 [STATEMENT_BREAK] = sizeof(statement_base_t),
289 [STATEMENT_GOTO] = sizeof(goto_statement_t),
290 [STATEMENT_LABEL] = sizeof(label_statement_t),
291 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
292 [STATEMENT_WHILE] = sizeof(while_statement_t),
293 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
294 [STATEMENT_FOR] = sizeof(for_statement_t),
295 [STATEMENT_ASM] = sizeof(asm_statement_t),
296 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
297 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
299 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
300 assert(sizes[kind] != 0);
305 * Returns the size of an expression node.
307 * @param kind the expression kind
309 static size_t get_expression_struct_size(expression_kind_t kind)
311 static const size_t sizes[] = {
312 [EXPR_INVALID] = sizeof(expression_base_t),
313 [EXPR_REFERENCE] = sizeof(reference_expression_t),
314 [EXPR_CONST] = sizeof(const_expression_t),
315 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
316 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
317 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
318 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
319 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
320 [EXPR_CALL] = sizeof(call_expression_t),
321 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
322 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
323 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
324 [EXPR_SELECT] = sizeof(select_expression_t),
325 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
326 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
327 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
328 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
329 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
330 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
331 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
332 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
333 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
334 [EXPR_VA_START] = sizeof(va_start_expression_t),
335 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
336 [EXPR_STATEMENT] = sizeof(statement_expression_t),
337 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
339 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
340 return sizes[EXPR_UNARY_FIRST];
342 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
343 return sizes[EXPR_BINARY_FIRST];
345 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
346 assert(sizes[kind] != 0);
351 * Allocate a statement node of given kind and initialize all
354 static statement_t *allocate_statement_zero(statement_kind_t kind)
356 size_t size = get_statement_struct_size(kind);
357 statement_t *res = allocate_ast_zero(size);
359 res->base.kind = kind;
360 res->base.parent = current_parent;
361 res->base.source_position = token.source_position;
366 * Allocate an expression node of given kind and initialize all
369 static expression_t *allocate_expression_zero(expression_kind_t kind)
371 size_t size = get_expression_struct_size(kind);
372 expression_t *res = allocate_ast_zero(size);
374 res->base.kind = kind;
375 res->base.type = type_error_type;
380 * Creates a new invalid expression.
382 static expression_t *create_invalid_expression(void)
384 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
385 expression->base.source_position = token.source_position;
390 * Creates a new invalid statement.
392 static statement_t *create_invalid_statement(void)
394 return allocate_statement_zero(STATEMENT_INVALID);
398 * Allocate a new empty statement.
400 static statement_t *create_empty_statement(void)
402 return allocate_statement_zero(STATEMENT_EMPTY);
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 while (token_anchor_set[token.type] == 0) {
641 if (token.type == '(' || token.type == '{' || token.type == '[')
642 eat_until_matching_token(token.type);
647 static void eat_block(void)
649 eat_until_matching_token('{');
650 if (token.type == '}')
654 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
657 * Report a parse error because an expected token was not found.
660 #if defined __GNUC__ && __GNUC__ >= 4
661 __attribute__((sentinel))
663 void parse_error_expected(const char *message, ...)
665 if (message != NULL) {
666 errorf(HERE, "%s", message);
669 va_start(ap, message);
670 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
675 * Report a type error.
677 static void type_error(const char *msg, const source_position_t *source_position,
680 errorf(source_position, "%s, but found type '%T'", msg, type);
684 * Report an incompatible type.
686 static void type_error_incompatible(const char *msg,
687 const source_position_t *source_position, type_t *type1, type_t *type2)
689 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
694 * Expect the the current token is the expected token.
695 * If not, generate an error, eat the current statement,
696 * and goto the end_error label.
698 #define expect(expected) \
700 if (UNLIKELY(token.type != (expected))) { \
701 parse_error_expected(NULL, (expected), NULL); \
702 add_anchor_token(expected); \
703 eat_until_anchor(); \
704 if (token.type == expected) \
706 rem_anchor_token(expected); \
712 static void scope_push(scope_t *new_scope)
715 scope->last_declaration = last_declaration;
716 new_scope->depth = scope->depth + 1;
718 new_scope->parent = scope;
721 last_declaration = new_scope->last_declaration;
724 static void scope_pop(void)
726 scope->last_declaration = last_declaration;
727 scope = scope->parent;
728 last_declaration = scope->last_declaration;
732 * Search a symbol in a given namespace and returns its declaration or
733 * NULL if this symbol was not found.
735 static declaration_t *get_declaration(const symbol_t *const symbol,
736 const namespace_t namespc)
738 declaration_t *declaration = symbol->declaration;
739 for( ; declaration != NULL; declaration = declaration->symbol_next) {
740 if (declaration->namespc == namespc)
748 * pushs an environment_entry on the environment stack and links the
749 * corresponding symbol to the new entry
751 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
753 symbol_t *symbol = declaration->symbol;
754 namespace_t namespc = (namespace_t) declaration->namespc;
756 /* replace/add declaration into declaration list of the symbol */
757 declaration_t **anchor;
759 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
764 /* replace an entry? */
765 if (iter->namespc == namespc) {
766 declaration->symbol_next = iter->symbol_next;
770 *anchor = declaration;
772 /* remember old declaration */
774 entry.symbol = symbol;
775 entry.old_declaration = iter;
776 entry.namespc = (unsigned short) namespc;
777 ARR_APP1(stack_entry_t, *stack_ptr, entry);
781 * Push a declaration on the environment stack.
783 * @param declaration the declaration
785 static void environment_push(declaration_t *declaration)
787 assert(declaration->source_position.input_name != NULL);
788 assert(declaration->parent_scope != NULL);
789 stack_push(&environment_stack, declaration);
793 * Push a declaration on the global label stack.
795 * @param declaration the declaration
797 static void label_push(declaration_t *declaration)
799 declaration->parent_scope = ¤t_function->scope;
800 stack_push(&label_stack, declaration);
804 * Push a declaration of the local label stack.
806 * @param declaration the declaration
808 static void local_label_push(declaration_t *declaration)
810 assert(declaration->parent_scope != NULL);
811 stack_push(&local_label_stack, declaration);
815 * pops symbols from the environment stack until @p new_top is the top element
817 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
819 stack_entry_t *stack = *stack_ptr;
820 size_t top = ARR_LEN(stack);
823 assert(new_top <= top);
827 for(i = top; i > new_top; --i) {
828 stack_entry_t *entry = &stack[i - 1];
830 declaration_t *old_declaration = entry->old_declaration;
831 symbol_t *symbol = entry->symbol;
832 namespace_t namespc = (namespace_t)entry->namespc;
834 /* replace/remove declaration */
835 declaration_t **anchor;
837 for (anchor = &symbol->declaration;; anchor = &iter->symbol_next) {
839 assert(iter != NULL);
840 /* replace an entry? */
841 if (iter->namespc == namespc)
845 /* Not all declarations adhere scopes (e.g. jump labels), so this
846 * correction is necessary */
847 if (old_declaration != NULL) {
848 old_declaration->symbol_next = iter->symbol_next;
849 *anchor = old_declaration;
851 *anchor = iter->symbol_next;
855 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
859 * Pop all entries from the environment stack until the new_top
862 * @param new_top the new stack top
864 static void environment_pop_to(size_t new_top)
866 stack_pop_to(&environment_stack, new_top);
870 * Pop all entries from the global label stack until the new_top
873 * @param new_top the new stack top
875 static void label_pop_to(size_t new_top)
877 stack_pop_to(&label_stack, new_top);
881 * Pop all entries from the local label stack until the new_top
884 * @param new_top the new stack top
886 static void local_label_pop_to(size_t new_top)
888 stack_pop_to(&local_label_stack, new_top);
892 static int get_akind_rank(atomic_type_kind_t akind)
897 static int get_rank(const type_t *type)
899 assert(!is_typeref(type));
900 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
901 * and esp. footnote 108). However we can't fold constants (yet), so we
902 * can't decide whether unsigned int is possible, while int always works.
903 * (unsigned int would be preferable when possible... for stuff like
904 * struct { enum { ... } bla : 4; } ) */
905 if (type->kind == TYPE_ENUM)
906 return get_akind_rank(ATOMIC_TYPE_INT);
908 assert(type->kind == TYPE_ATOMIC);
909 return get_akind_rank(type->atomic.akind);
912 static type_t *promote_integer(type_t *type)
914 if (type->kind == TYPE_BITFIELD)
915 type = type->bitfield.base_type;
917 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
924 * Create a cast expression.
926 * @param expression the expression to cast
927 * @param dest_type the destination type
929 static expression_t *create_cast_expression(expression_t *expression,
932 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
934 cast->unary.value = expression;
935 cast->base.type = dest_type;
941 * Check if a given expression represents the 0 pointer constant.
943 static bool is_null_pointer_constant(const expression_t *expression)
945 /* skip void* cast */
946 if (expression->kind == EXPR_UNARY_CAST
947 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
948 expression = expression->unary.value;
951 /* TODO: not correct yet, should be any constant integer expression
952 * which evaluates to 0 */
953 if (expression->kind != EXPR_CONST)
956 type_t *const type = skip_typeref(expression->base.type);
957 if (!is_type_integer(type))
960 return expression->conste.v.int_value == 0;
964 * Create an implicit cast expression.
966 * @param expression the expression to cast
967 * @param dest_type the destination type
969 static expression_t *create_implicit_cast(expression_t *expression,
972 type_t *const source_type = expression->base.type;
974 if (source_type == dest_type)
977 return create_cast_expression(expression, dest_type);
980 typedef enum assign_error_t {
982 ASSIGN_ERROR_INCOMPATIBLE,
983 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
984 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
985 ASSIGN_WARNING_POINTER_FROM_INT,
986 ASSIGN_WARNING_INT_FROM_POINTER
989 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
990 const expression_t *const right,
992 const source_position_t *source_position)
994 type_t *const orig_type_right = right->base.type;
995 type_t *const type_left = skip_typeref(orig_type_left);
996 type_t *const type_right = skip_typeref(orig_type_right);
1001 case ASSIGN_ERROR_INCOMPATIBLE:
1002 errorf(source_position,
1003 "destination type '%T' in %s is incompatible with type '%T'",
1004 orig_type_left, context, orig_type_right);
1007 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1008 type_t *points_to_left
1009 = skip_typeref(type_left->pointer.points_to);
1010 type_t *points_to_right
1011 = skip_typeref(type_right->pointer.points_to);
1013 /* the left type has all qualifiers from the right type */
1014 unsigned missing_qualifiers
1015 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1016 warningf(source_position,
1017 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1018 orig_type_left, context, orig_type_right, missing_qualifiers);
1022 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1023 warningf(source_position,
1024 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1025 orig_type_left, context, right, orig_type_right);
1028 case ASSIGN_WARNING_POINTER_FROM_INT:
1029 warningf(source_position,
1030 "%s makes pointer '%T' from integer '%T' without a cast",
1031 context, orig_type_left, orig_type_right);
1034 case ASSIGN_WARNING_INT_FROM_POINTER:
1035 warningf(source_position,
1036 "%s makes integer '%T' from pointer '%T' without a cast",
1037 context, orig_type_left, orig_type_right);
1041 panic("invalid error value");
1045 /** Implements the rules from § 6.5.16.1 */
1046 static assign_error_t semantic_assign(type_t *orig_type_left,
1047 const expression_t *const right)
1049 type_t *const orig_type_right = right->base.type;
1050 type_t *const type_left = skip_typeref(orig_type_left);
1051 type_t *const type_right = skip_typeref(orig_type_right);
1053 if (is_type_pointer(type_left)) {
1054 if (is_null_pointer_constant(right)) {
1055 return ASSIGN_SUCCESS;
1056 } else if (is_type_pointer(type_right)) {
1057 type_t *points_to_left
1058 = skip_typeref(type_left->pointer.points_to);
1059 type_t *points_to_right
1060 = skip_typeref(type_right->pointer.points_to);
1061 assign_error_t res = ASSIGN_SUCCESS;
1063 /* the left type has all qualifiers from the right type */
1064 unsigned missing_qualifiers
1065 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1066 if (missing_qualifiers != 0) {
1067 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1070 points_to_left = get_unqualified_type(points_to_left);
1071 points_to_right = get_unqualified_type(points_to_right);
1073 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1074 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1078 if (!types_compatible(points_to_left, points_to_right)) {
1079 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1083 } else if (is_type_integer(type_right)) {
1084 return ASSIGN_WARNING_POINTER_FROM_INT;
1086 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1087 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1088 && is_type_pointer(type_right))) {
1089 return ASSIGN_SUCCESS;
1090 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1091 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1092 type_t *const unqual_type_left = get_unqualified_type(type_left);
1093 type_t *const unqual_type_right = get_unqualified_type(type_right);
1094 if (types_compatible(unqual_type_left, unqual_type_right)) {
1095 return ASSIGN_SUCCESS;
1097 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1098 return ASSIGN_WARNING_INT_FROM_POINTER;
1101 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1102 return ASSIGN_SUCCESS;
1104 return ASSIGN_ERROR_INCOMPATIBLE;
1107 static expression_t *parse_constant_expression(void)
1109 /* start parsing at precedence 7 (conditional expression) */
1110 expression_t *result = parse_sub_expression(7);
1112 if (!is_constant_expression(result)) {
1113 errorf(&result->base.source_position,
1114 "expression '%E' is not constant\n", result);
1120 static expression_t *parse_assignment_expression(void)
1122 /* start parsing at precedence 2 (assignment expression) */
1123 return parse_sub_expression(2);
1126 static type_t *make_global_typedef(const char *name, type_t *type)
1128 symbol_t *const symbol = symbol_table_insert(name);
1130 declaration_t *const declaration = allocate_declaration_zero();
1131 declaration->namespc = NAMESPACE_NORMAL;
1132 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1133 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1134 declaration->type = type;
1135 declaration->symbol = symbol;
1136 declaration->source_position = builtin_source_position;
1137 declaration->implicit = true;
1139 record_declaration(declaration, false);
1141 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1142 typedef_type->typedeft.declaration = declaration;
1144 return typedef_type;
1147 static string_t parse_string_literals(void)
1149 assert(token.type == T_STRING_LITERAL);
1150 string_t result = token.v.string;
1154 while (token.type == T_STRING_LITERAL) {
1155 result = concat_strings(&result, &token.v.string);
1162 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1163 [GNU_AK_CONST] = "const",
1164 [GNU_AK_VOLATILE] = "volatile",
1165 [GNU_AK_CDECL] = "cdecl",
1166 [GNU_AK_STDCALL] = "stdcall",
1167 [GNU_AK_FASTCALL] = "fastcall",
1168 [GNU_AK_DEPRECATED] = "deprecated",
1169 [GNU_AK_NOINLINE] = "noinline",
1170 [GNU_AK_NORETURN] = "noreturn",
1171 [GNU_AK_NAKED] = "naked",
1172 [GNU_AK_PURE] = "pure",
1173 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1174 [GNU_AK_MALLOC] = "malloc",
1175 [GNU_AK_WEAK] = "weak",
1176 [GNU_AK_CONSTRUCTOR] = "constructor",
1177 [GNU_AK_DESTRUCTOR] = "destructor",
1178 [GNU_AK_NOTHROW] = "nothrow",
1179 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1180 [GNU_AK_COMMON] = "common",
1181 [GNU_AK_NOCOMMON] = "nocommon",
1182 [GNU_AK_PACKED] = "packed",
1183 [GNU_AK_SHARED] = "shared",
1184 [GNU_AK_NOTSHARED] = "notshared",
1185 [GNU_AK_USED] = "used",
1186 [GNU_AK_UNUSED] = "unused",
1187 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1188 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1189 [GNU_AK_LONGCALL] = "longcall",
1190 [GNU_AK_SHORTCALL] = "shortcall",
1191 [GNU_AK_LONG_CALL] = "long_call",
1192 [GNU_AK_SHORT_CALL] = "short_call",
1193 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1194 [GNU_AK_INTERRUPT] = "interrupt",
1195 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1196 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1197 [GNU_AK_NESTING] = "nesting",
1198 [GNU_AK_NEAR] = "near",
1199 [GNU_AK_FAR] = "far",
1200 [GNU_AK_SIGNAL] = "signal",
1201 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1202 [GNU_AK_TINY_DATA] = "tiny_data",
1203 [GNU_AK_SAVEALL] = "saveall",
1204 [GNU_AK_FLATTEN] = "flatten",
1205 [GNU_AK_SSEREGPARM] = "sseregparm",
1206 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1207 [GNU_AK_RETURN_TWICE] = "return_twice",
1208 [GNU_AK_MAY_ALIAS] = "may_alias",
1209 [GNU_AK_MS_STRUCT] = "ms_struct",
1210 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1211 [GNU_AK_DLLIMPORT] = "dllimport",
1212 [GNU_AK_DLLEXPORT] = "dllexport",
1213 [GNU_AK_ALIGNED] = "aligned",
1214 [GNU_AK_ALIAS] = "alias",
1215 [GNU_AK_SECTION] = "section",
1216 [GNU_AK_FORMAT] = "format",
1217 [GNU_AK_FORMAT_ARG] = "format_arg",
1218 [GNU_AK_WEAKREF] = "weakref",
1219 [GNU_AK_NONNULL] = "nonnull",
1220 [GNU_AK_TLS_MODEL] = "tls_model",
1221 [GNU_AK_VISIBILITY] = "visibility",
1222 [GNU_AK_REGPARM] = "regparm",
1223 [GNU_AK_MODE] = "mode",
1224 [GNU_AK_MODEL] = "model",
1225 [GNU_AK_TRAP_EXIT] = "trap_exit",
1226 [GNU_AK_SP_SWITCH] = "sp_switch",
1227 [GNU_AK_SENTINEL] = "sentinel"
1231 * compare two string, ignoring double underscores on the second.
1233 static int strcmp_underscore(const char *s1, const char *s2)
1235 if (s2[0] == '_' && s2[1] == '_') {
1236 size_t len2 = strlen(s2);
1237 size_t len1 = strlen(s1);
1238 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1239 return strncmp(s1, s2+2, len2-4);
1243 return strcmp(s1, s2);
1247 * Allocate a new gnu temporal attribute.
1249 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1251 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1252 attribute->kind = kind;
1253 attribute->next = NULL;
1254 attribute->invalid = false;
1255 attribute->have_arguments = false;
1261 * parse one constant expression argument.
1263 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1265 expression_t *expression;
1266 add_anchor_token(')');
1267 expression = parse_constant_expression();
1268 rem_anchor_token(')');
1270 attribute->u.argument = fold_constant(expression);
1273 attribute->invalid = true;
1277 * parse a list of constant expressions arguments.
1279 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1281 argument_list_t **list = &attribute->u.arguments;
1282 argument_list_t *entry;
1283 expression_t *expression;
1284 add_anchor_token(')');
1285 add_anchor_token(',');
1287 expression = parse_constant_expression();
1288 entry = obstack_alloc(&temp_obst, sizeof(entry));
1289 entry->argument = fold_constant(expression);
1292 list = &entry->next;
1293 if (token.type != ',')
1297 rem_anchor_token(',');
1298 rem_anchor_token(')');
1302 attribute->invalid = true;
1306 * parse one string literal argument.
1308 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1311 add_anchor_token('(');
1312 if (token.type != T_STRING_LITERAL) {
1313 parse_error_expected("while parsing attribute directive",
1314 T_STRING_LITERAL, NULL);
1317 *string = parse_string_literals();
1318 rem_anchor_token('(');
1322 attribute->invalid = true;
1326 * parse one tls model.
1328 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1330 static const char *const tls_models[] = {
1336 string_t string = { NULL, 0 };
1337 parse_gnu_attribute_string_arg(attribute, &string);
1338 if (string.begin != NULL) {
1339 for(size_t i = 0; i < 4; ++i) {
1340 if (strcmp(tls_models[i], string.begin) == 0) {
1341 attribute->u.value = i;
1345 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1347 attribute->invalid = true;
1351 * parse one tls model.
1353 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1355 static const char *const visibilities[] = {
1361 string_t string = { NULL, 0 };
1362 parse_gnu_attribute_string_arg(attribute, &string);
1363 if (string.begin != NULL) {
1364 for(size_t i = 0; i < 4; ++i) {
1365 if (strcmp(visibilities[i], string.begin) == 0) {
1366 attribute->u.value = i;
1370 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1372 attribute->invalid = true;
1376 * parse one (code) model.
1378 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1380 static const char *const visibilities[] = {
1385 string_t string = { NULL, 0 };
1386 parse_gnu_attribute_string_arg(attribute, &string);
1387 if (string.begin != NULL) {
1388 for(int i = 0; i < 3; ++i) {
1389 if (strcmp(visibilities[i], string.begin) == 0) {
1390 attribute->u.value = i;
1394 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1396 attribute->invalid = true;
1399 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1401 /* TODO: find out what is allowed here... */
1403 /* at least: byte, word, pointer, list of machine modes
1404 * __XXX___ is interpreted as XXX */
1405 add_anchor_token(')');
1407 if (token.type != T_IDENTIFIER) {
1408 expect(T_IDENTIFIER);
1411 /* This isn't really correct, the backend should provide a list of machine
1412 * specific modes (according to gcc philosophy that is...) */
1413 const char *symbol_str = token.v.symbol->string;
1414 if (strcmp_underscore("QI", symbol_str) == 0 ||
1415 strcmp_underscore("byte", symbol_str) == 0) {
1416 attribute->u.akind = ATOMIC_TYPE_CHAR;
1417 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1418 attribute->u.akind = ATOMIC_TYPE_SHORT;
1419 } else if (strcmp_underscore("SI", symbol_str) == 0
1420 || strcmp_underscore("word", symbol_str) == 0
1421 || strcmp_underscore("pointer", symbol_str) == 0) {
1422 attribute->u.akind = ATOMIC_TYPE_INT;
1423 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1424 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1426 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1427 attribute->invalid = true;
1431 rem_anchor_token(')');
1435 attribute->invalid = true;
1439 * parse one interrupt argument.
1441 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1443 static const char *const interrupts[] = {
1450 string_t string = { NULL, 0 };
1451 parse_gnu_attribute_string_arg(attribute, &string);
1452 if (string.begin != NULL) {
1453 for(size_t i = 0; i < 5; ++i) {
1454 if (strcmp(interrupts[i], string.begin) == 0) {
1455 attribute->u.value = i;
1459 errorf(HERE, "'%s' is not an interrupt", string.begin);
1461 attribute->invalid = true;
1465 * parse ( identifier, const expression, const expression )
1467 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1469 static const char *const format_names[] = {
1477 if (token.type != T_IDENTIFIER) {
1478 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1481 const char *name = token.v.symbol->string;
1482 for(i = 0; i < 4; ++i) {
1483 if (strcmp_underscore(format_names[i], name) == 0)
1487 if (warning.attribute)
1488 warningf(HERE, "'%s' is an unrecognized format function type", name);
1493 add_anchor_token(')');
1494 add_anchor_token(',');
1495 parse_constant_expression();
1496 rem_anchor_token(',');
1497 rem_anchor_token(')');
1500 add_anchor_token(')');
1501 parse_constant_expression();
1502 rem_anchor_token(')');
1506 attribute->u.value = true;
1509 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1511 if (!attribute->have_arguments)
1514 /* should have no arguments */
1515 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1516 eat_until_matching_token('(');
1517 /* we have already consumed '(', so we stop before ')', eat it */
1519 attribute->invalid = true;
1523 * Parse one GNU attribute.
1525 * Note that attribute names can be specified WITH or WITHOUT
1526 * double underscores, ie const or __const__.
1528 * The following attributes are parsed without arguments
1553 * no_instrument_function
1554 * warn_unused_result
1571 * externally_visible
1579 * The following attributes are parsed with arguments
1580 * aligned( const expression )
1581 * alias( string literal )
1582 * section( string literal )
1583 * format( identifier, const expression, const expression )
1584 * format_arg( const expression )
1585 * tls_model( string literal )
1586 * visibility( string literal )
1587 * regparm( const expression )
1588 * model( string leteral )
1589 * trap_exit( const expression )
1590 * sp_switch( string literal )
1592 * The following attributes might have arguments
1593 * weak_ref( string literal )
1594 * non_null( const expression // ',' )
1595 * interrupt( string literal )
1596 * sentinel( constant expression )
1598 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1600 gnu_attribute_t *head = *attributes;
1601 gnu_attribute_t *last = *attributes;
1602 decl_modifiers_t modifiers = 0;
1603 gnu_attribute_t *attribute;
1605 eat(T___attribute__);
1609 if (token.type != ')') {
1610 /* find the end of the list */
1612 while (last->next != NULL)
1616 /* non-empty attribute list */
1619 if (token.type == T_const) {
1621 } else if (token.type == T_volatile) {
1623 } else if (token.type == T_cdecl) {
1624 /* __attribute__((cdecl)), WITH ms mode */
1626 } else if (token.type == T_IDENTIFIER) {
1627 const symbol_t *sym = token.v.symbol;
1630 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1637 for(i = 0; i < GNU_AK_LAST; ++i) {
1638 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1641 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1644 if (kind == GNU_AK_LAST) {
1645 if (warning.attribute)
1646 warningf(HERE, "'%s' attribute directive ignored", name);
1648 /* skip possible arguments */
1649 if (token.type == '(') {
1650 eat_until_matching_token(')');
1653 /* check for arguments */
1654 attribute = allocate_gnu_attribute(kind);
1655 if (token.type == '(') {
1657 if (token.type == ')') {
1658 /* empty args are allowed */
1661 attribute->have_arguments = true;
1665 case GNU_AK_VOLATILE:
1670 case GNU_AK_NOCOMMON:
1672 case GNU_AK_NOTSHARED:
1673 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1674 case GNU_AK_WARN_UNUSED_RESULT:
1675 case GNU_AK_LONGCALL:
1676 case GNU_AK_SHORTCALL:
1677 case GNU_AK_LONG_CALL:
1678 case GNU_AK_SHORT_CALL:
1679 case GNU_AK_FUNCTION_VECTOR:
1680 case GNU_AK_INTERRUPT_HANDLER:
1681 case GNU_AK_NMI_HANDLER:
1682 case GNU_AK_NESTING:
1686 case GNU_AK_EIGTHBIT_DATA:
1687 case GNU_AK_TINY_DATA:
1688 case GNU_AK_SAVEALL:
1689 case GNU_AK_FLATTEN:
1690 case GNU_AK_SSEREGPARM:
1691 case GNU_AK_EXTERNALLY_VISIBLE:
1692 case GNU_AK_RETURN_TWICE:
1693 case GNU_AK_MAY_ALIAS:
1694 case GNU_AK_MS_STRUCT:
1695 case GNU_AK_GCC_STRUCT:
1698 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1699 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1700 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1701 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1702 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1703 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1704 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1705 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1706 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1707 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1708 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1709 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1710 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1711 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1712 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1713 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1714 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1715 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1717 case GNU_AK_ALIGNED:
1718 /* __align__ may be used without an argument */
1719 if (attribute->have_arguments) {
1720 parse_gnu_attribute_const_arg(attribute);
1724 case GNU_AK_FORMAT_ARG:
1725 case GNU_AK_REGPARM:
1726 case GNU_AK_TRAP_EXIT:
1727 if (!attribute->have_arguments) {
1728 /* should have arguments */
1729 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1730 attribute->invalid = true;
1732 parse_gnu_attribute_const_arg(attribute);
1735 case GNU_AK_SECTION:
1736 case GNU_AK_SP_SWITCH:
1737 if (!attribute->have_arguments) {
1738 /* should have arguments */
1739 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1740 attribute->invalid = true;
1742 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1745 if (!attribute->have_arguments) {
1746 /* should have arguments */
1747 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1748 attribute->invalid = true;
1750 parse_gnu_attribute_format_args(attribute);
1752 case GNU_AK_WEAKREF:
1753 /* may have one string argument */
1754 if (attribute->have_arguments)
1755 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1757 case GNU_AK_NONNULL:
1758 if (attribute->have_arguments)
1759 parse_gnu_attribute_const_arg_list(attribute);
1761 case GNU_AK_TLS_MODEL:
1762 if (!attribute->have_arguments) {
1763 /* should have arguments */
1764 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1766 parse_gnu_attribute_tls_model_arg(attribute);
1768 case GNU_AK_VISIBILITY:
1769 if (!attribute->have_arguments) {
1770 /* should have arguments */
1771 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1773 parse_gnu_attribute_visibility_arg(attribute);
1776 if (!attribute->have_arguments) {
1777 /* should have arguments */
1778 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1780 parse_gnu_attribute_model_arg(attribute);
1784 if (!attribute->have_arguments) {
1785 /* should have arguments */
1786 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1788 parse_gnu_attribute_mode_arg(attribute);
1791 case GNU_AK_INTERRUPT:
1792 /* may have one string argument */
1793 if (attribute->have_arguments)
1794 parse_gnu_attribute_interrupt_arg(attribute);
1796 case GNU_AK_SENTINEL:
1797 /* may have one string argument */
1798 if (attribute->have_arguments)
1799 parse_gnu_attribute_const_arg(attribute);
1802 /* already handled */
1806 check_no_argument(attribute, name);
1809 if (attribute != NULL) {
1811 last->next = attribute;
1814 head = last = attribute;
1818 if (token.type != ',')
1832 * Parse GNU attributes.
1834 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1836 decl_modifiers_t modifiers = 0;
1839 switch(token.type) {
1840 case T___attribute__:
1841 modifiers |= parse_gnu_attribute(attributes);
1847 if (token.type != T_STRING_LITERAL) {
1848 parse_error_expected("while parsing assembler attribute",
1849 T_STRING_LITERAL, NULL);
1850 eat_until_matching_token('(');
1853 parse_string_literals();
1858 case T_cdecl: modifiers |= DM_CDECL; break;
1859 case T__fastcall: modifiers |= DM_FASTCALL; break;
1860 case T__stdcall: modifiers |= DM_STDCALL; break;
1863 /* TODO record modifier */
1864 warningf(HERE, "Ignoring declaration modifier %K", &token);
1868 default: return modifiers;
1875 static designator_t *parse_designation(void)
1877 designator_t *result = NULL;
1878 designator_t *last = NULL;
1881 designator_t *designator;
1882 switch(token.type) {
1884 designator = allocate_ast_zero(sizeof(designator[0]));
1885 designator->source_position = token.source_position;
1887 add_anchor_token(']');
1888 designator->array_index = parse_constant_expression();
1889 rem_anchor_token(']');
1893 designator = allocate_ast_zero(sizeof(designator[0]));
1894 designator->source_position = token.source_position;
1896 if (token.type != T_IDENTIFIER) {
1897 parse_error_expected("while parsing designator",
1898 T_IDENTIFIER, NULL);
1901 designator->symbol = token.v.symbol;
1909 assert(designator != NULL);
1911 last->next = designator;
1913 result = designator;
1921 static initializer_t *initializer_from_string(array_type_t *type,
1922 const string_t *const string)
1924 /* TODO: check len vs. size of array type */
1927 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1928 initializer->string.string = *string;
1933 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1934 wide_string_t *const string)
1936 /* TODO: check len vs. size of array type */
1939 initializer_t *const initializer =
1940 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1941 initializer->wide_string.string = *string;
1947 * Build an initializer from a given expression.
1949 static initializer_t *initializer_from_expression(type_t *orig_type,
1950 expression_t *expression)
1952 /* TODO check that expression is a constant expression */
1954 /* § 6.7.8.14/15 char array may be initialized by string literals */
1955 type_t *type = skip_typeref(orig_type);
1956 type_t *expr_type_orig = expression->base.type;
1957 type_t *expr_type = skip_typeref(expr_type_orig);
1958 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1959 array_type_t *const array_type = &type->array;
1960 type_t *const element_type = skip_typeref(array_type->element_type);
1962 if (element_type->kind == TYPE_ATOMIC) {
1963 atomic_type_kind_t akind = element_type->atomic.akind;
1964 switch (expression->kind) {
1965 case EXPR_STRING_LITERAL:
1966 if (akind == ATOMIC_TYPE_CHAR
1967 || akind == ATOMIC_TYPE_SCHAR
1968 || akind == ATOMIC_TYPE_UCHAR) {
1969 return initializer_from_string(array_type,
1970 &expression->string.value);
1973 case EXPR_WIDE_STRING_LITERAL: {
1974 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1975 if (get_unqualified_type(element_type) == bare_wchar_type) {
1976 return initializer_from_wide_string(array_type,
1977 &expression->wide_string.value);
1987 assign_error_t error = semantic_assign(type, expression);
1988 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1990 report_assign_error(error, type, expression, "initializer",
1991 &expression->base.source_position);
1993 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1995 if (type->kind == TYPE_BITFIELD) {
1996 type = type->bitfield.base_type;
1999 result->value.value = create_implicit_cast(expression, type);
2005 * Checks if a given expression can be used as an constant initializer.
2007 static bool is_initializer_constant(const expression_t *expression)
2009 return is_constant_expression(expression)
2010 || is_address_constant(expression);
2014 * Parses an scalar initializer.
2016 * § 6.7.8.11; eat {} without warning
2018 static initializer_t *parse_scalar_initializer(type_t *type,
2019 bool must_be_constant)
2021 /* there might be extra {} hierarchies */
2023 if (token.type == '{') {
2024 warningf(HERE, "extra curly braces around scalar initializer");
2028 } while (token.type == '{');
2031 expression_t *expression = parse_assignment_expression();
2032 if (must_be_constant && !is_initializer_constant(expression)) {
2033 errorf(&expression->base.source_position,
2034 "Initialisation expression '%E' is not constant\n",
2038 initializer_t *initializer = initializer_from_expression(type, expression);
2040 if (initializer == NULL) {
2041 errorf(&expression->base.source_position,
2042 "expression '%E' (type '%T') doesn't match expected type '%T'",
2043 expression, expression->base.type, type);
2048 bool additional_warning_displayed = false;
2049 while (braces > 0) {
2050 if (token.type == ',') {
2053 if (token.type != '}') {
2054 if (!additional_warning_displayed) {
2055 warningf(HERE, "additional elements in scalar initializer");
2056 additional_warning_displayed = true;
2067 * An entry in the type path.
2069 typedef struct type_path_entry_t type_path_entry_t;
2070 struct type_path_entry_t {
2071 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2073 size_t index; /**< For array types: the current index. */
2074 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2079 * A type path expression a position inside compound or array types.
2081 typedef struct type_path_t type_path_t;
2082 struct type_path_t {
2083 type_path_entry_t *path; /**< An flexible array containing the current path. */
2084 type_t *top_type; /**< type of the element the path points */
2085 size_t max_index; /**< largest index in outermost array */
2089 * Prints a type path for debugging.
2091 static __attribute__((unused)) void debug_print_type_path(
2092 const type_path_t *path)
2094 size_t len = ARR_LEN(path->path);
2096 for(size_t i = 0; i < len; ++i) {
2097 const type_path_entry_t *entry = & path->path[i];
2099 type_t *type = skip_typeref(entry->type);
2100 if (is_type_compound(type)) {
2101 /* in gcc mode structs can have no members */
2102 if (entry->v.compound_entry == NULL) {
2106 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2107 } else if (is_type_array(type)) {
2108 fprintf(stderr, "[%zu]", entry->v.index);
2110 fprintf(stderr, "-INVALID-");
2113 if (path->top_type != NULL) {
2114 fprintf(stderr, " (");
2115 print_type(path->top_type);
2116 fprintf(stderr, ")");
2121 * Return the top type path entry, ie. in a path
2122 * (type).a.b returns the b.
2124 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2126 size_t len = ARR_LEN(path->path);
2128 return &path->path[len-1];
2132 * Enlarge the type path by an (empty) element.
2134 static type_path_entry_t *append_to_type_path(type_path_t *path)
2136 size_t len = ARR_LEN(path->path);
2137 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2139 type_path_entry_t *result = & path->path[len];
2140 memset(result, 0, sizeof(result[0]));
2145 * Descending into a sub-type. Enter the scope of the current
2148 static void descend_into_subtype(type_path_t *path)
2150 type_t *orig_top_type = path->top_type;
2151 type_t *top_type = skip_typeref(orig_top_type);
2153 type_path_entry_t *top = append_to_type_path(path);
2154 top->type = top_type;
2156 if (is_type_compound(top_type)) {
2157 declaration_t *declaration = top_type->compound.declaration;
2158 declaration_t *entry = declaration->scope.declarations;
2159 top->v.compound_entry = entry;
2161 if (entry != NULL) {
2162 path->top_type = entry->type;
2164 path->top_type = NULL;
2166 } else if (is_type_array(top_type)) {
2168 path->top_type = top_type->array.element_type;
2170 assert(!is_type_valid(top_type));
2175 * Pop an entry from the given type path, ie. returning from
2176 * (type).a.b to (type).a
2178 static void ascend_from_subtype(type_path_t *path)
2180 type_path_entry_t *top = get_type_path_top(path);
2182 path->top_type = top->type;
2184 size_t len = ARR_LEN(path->path);
2185 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2189 * Pop entries from the given type path until the given
2190 * path level is reached.
2192 static void ascend_to(type_path_t *path, size_t top_path_level)
2194 size_t len = ARR_LEN(path->path);
2196 while (len > top_path_level) {
2197 ascend_from_subtype(path);
2198 len = ARR_LEN(path->path);
2202 static bool walk_designator(type_path_t *path, const designator_t *designator,
2203 bool used_in_offsetof)
2205 for( ; designator != NULL; designator = designator->next) {
2206 type_path_entry_t *top = get_type_path_top(path);
2207 type_t *orig_type = top->type;
2209 type_t *type = skip_typeref(orig_type);
2211 if (designator->symbol != NULL) {
2212 symbol_t *symbol = designator->symbol;
2213 if (!is_type_compound(type)) {
2214 if (is_type_valid(type)) {
2215 errorf(&designator->source_position,
2216 "'.%Y' designator used for non-compound type '%T'",
2220 top->type = type_error_type;
2221 top->v.compound_entry = NULL;
2222 orig_type = type_error_type;
2224 declaration_t *declaration = type->compound.declaration;
2225 declaration_t *iter = declaration->scope.declarations;
2226 for( ; iter != NULL; iter = iter->next) {
2227 if (iter->symbol == symbol) {
2232 errorf(&designator->source_position,
2233 "'%T' has no member named '%Y'", orig_type, symbol);
2236 if (used_in_offsetof) {
2237 type_t *real_type = skip_typeref(iter->type);
2238 if (real_type->kind == TYPE_BITFIELD) {
2239 errorf(&designator->source_position,
2240 "offsetof designator '%Y' may not specify bitfield",
2246 top->type = orig_type;
2247 top->v.compound_entry = iter;
2248 orig_type = iter->type;
2251 expression_t *array_index = designator->array_index;
2252 assert(designator->array_index != NULL);
2254 if (!is_type_array(type)) {
2255 if (is_type_valid(type)) {
2256 errorf(&designator->source_position,
2257 "[%E] designator used for non-array type '%T'",
2258 array_index, orig_type);
2263 long index = fold_constant(array_index);
2264 if (!used_in_offsetof) {
2266 errorf(&designator->source_position,
2267 "array index [%E] must be positive", array_index);
2268 } else if (type->array.size_constant) {
2269 long array_size = type->array.size;
2270 if (index >= array_size) {
2271 errorf(&designator->source_position,
2272 "designator [%E] (%d) exceeds array size %d",
2273 array_index, index, array_size);
2278 top->type = orig_type;
2279 top->v.index = (size_t) index;
2280 orig_type = type->array.element_type;
2282 path->top_type = orig_type;
2284 if (designator->next != NULL) {
2285 descend_into_subtype(path);
2294 static void advance_current_object(type_path_t *path, size_t top_path_level)
2296 type_path_entry_t *top = get_type_path_top(path);
2298 type_t *type = skip_typeref(top->type);
2299 if (is_type_union(type)) {
2300 /* in unions only the first element is initialized */
2301 top->v.compound_entry = NULL;
2302 } else if (is_type_struct(type)) {
2303 declaration_t *entry = top->v.compound_entry;
2305 entry = entry->next;
2306 top->v.compound_entry = entry;
2307 if (entry != NULL) {
2308 path->top_type = entry->type;
2311 } else if (is_type_array(type)) {
2312 assert(is_type_array(type));
2316 if (!type->array.size_constant || top->v.index < type->array.size) {
2320 assert(!is_type_valid(type));
2324 /* we're past the last member of the current sub-aggregate, try if we
2325 * can ascend in the type hierarchy and continue with another subobject */
2326 size_t len = ARR_LEN(path->path);
2328 if (len > top_path_level) {
2329 ascend_from_subtype(path);
2330 advance_current_object(path, top_path_level);
2332 path->top_type = NULL;
2337 * skip until token is found.
2339 static void skip_until(int type)
2341 while (token.type != type) {
2342 if (token.type == T_EOF)
2349 * skip any {...} blocks until a closing bracket is reached.
2351 static void skip_initializers(void)
2353 if (token.type == '{')
2356 while (token.type != '}') {
2357 if (token.type == T_EOF)
2359 if (token.type == '{') {
2367 static initializer_t *create_empty_initializer(void)
2369 static initializer_t empty_initializer
2370 = { .list = { { INITIALIZER_LIST }, 0 } };
2371 return &empty_initializer;
2375 * Parse a part of an initialiser for a struct or union,
2377 static initializer_t *parse_sub_initializer(type_path_t *path,
2378 type_t *outer_type, size_t top_path_level,
2379 parse_initializer_env_t *env)
2381 if (token.type == '}') {
2382 /* empty initializer */
2383 return create_empty_initializer();
2386 type_t *orig_type = path->top_type;
2387 type_t *type = NULL;
2389 if (orig_type == NULL) {
2390 /* We are initializing an empty compound. */
2392 type = skip_typeref(orig_type);
2395 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2398 designator_t *designator = NULL;
2399 if (token.type == '.' || token.type == '[') {
2400 designator = parse_designation();
2401 goto finish_designator;
2402 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2403 /* GNU-style designator ("identifier: value") */
2404 designator = allocate_ast_zero(sizeof(designator[0]));
2405 designator->source_position = token.source_position;
2406 designator->symbol = token.v.symbol;
2411 /* reset path to toplevel, evaluate designator from there */
2412 ascend_to(path, top_path_level);
2413 if (!walk_designator(path, designator, false)) {
2414 /* can't continue after designation error */
2418 initializer_t *designator_initializer
2419 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2420 designator_initializer->designator.designator = designator;
2421 ARR_APP1(initializer_t*, initializers, designator_initializer);
2423 orig_type = path->top_type;
2424 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2429 if (token.type == '{') {
2430 if (type != NULL && is_type_scalar(type)) {
2431 sub = parse_scalar_initializer(type, env->must_be_constant);
2435 if (env->declaration != NULL) {
2436 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2437 env->declaration->symbol);
2439 errorf(HERE, "extra brace group at end of initializer");
2442 descend_into_subtype(path);
2444 add_anchor_token('}');
2445 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2447 rem_anchor_token('}');
2450 ascend_from_subtype(path);
2454 goto error_parse_next;
2458 /* must be an expression */
2459 expression_t *expression = parse_assignment_expression();
2461 if (env->must_be_constant && !is_initializer_constant(expression)) {
2462 errorf(&expression->base.source_position,
2463 "Initialisation expression '%E' is not constant\n",
2468 /* we are already outside, ... */
2469 type_t *const outer_type_skip = skip_typeref(outer_type);
2470 if (is_type_compound(outer_type_skip) &&
2471 !outer_type_skip->compound.declaration->init.complete) {
2472 goto error_parse_next;
2477 /* handle { "string" } special case */
2478 if ((expression->kind == EXPR_STRING_LITERAL
2479 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2480 && outer_type != NULL) {
2481 sub = initializer_from_expression(outer_type, expression);
2483 if (token.type == ',') {
2486 if (token.type != '}') {
2487 warningf(HERE, "excessive elements in initializer for type '%T'",
2490 /* TODO: eat , ... */
2495 /* descend into subtypes until expression matches type */
2497 orig_type = path->top_type;
2498 type = skip_typeref(orig_type);
2500 sub = initializer_from_expression(orig_type, expression);
2504 if (!is_type_valid(type)) {
2507 if (is_type_scalar(type)) {
2508 errorf(&expression->base.source_position,
2509 "expression '%E' doesn't match expected type '%T'",
2510 expression, orig_type);
2514 descend_into_subtype(path);
2518 /* update largest index of top array */
2519 const type_path_entry_t *first = &path->path[0];
2520 type_t *first_type = first->type;
2521 first_type = skip_typeref(first_type);
2522 if (is_type_array(first_type)) {
2523 size_t index = first->v.index;
2524 if (index > path->max_index)
2525 path->max_index = index;
2529 /* append to initializers list */
2530 ARR_APP1(initializer_t*, initializers, sub);
2533 if (env->declaration != NULL)
2534 warningf(HERE, "excess elements in struct initializer for '%Y'",
2535 env->declaration->symbol);
2537 warningf(HERE, "excess elements in struct initializer");
2541 if (token.type == '}') {
2545 if (token.type == '}') {
2550 /* advance to the next declaration if we are not at the end */
2551 advance_current_object(path, top_path_level);
2552 orig_type = path->top_type;
2553 if (orig_type != NULL)
2554 type = skip_typeref(orig_type);
2560 size_t len = ARR_LEN(initializers);
2561 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2562 initializer_t *result = allocate_ast_zero(size);
2563 result->kind = INITIALIZER_LIST;
2564 result->list.len = len;
2565 memcpy(&result->list.initializers, initializers,
2566 len * sizeof(initializers[0]));
2568 DEL_ARR_F(initializers);
2569 ascend_to(path, top_path_level+1);
2574 skip_initializers();
2575 DEL_ARR_F(initializers);
2576 ascend_to(path, top_path_level+1);
2581 * Parses an initializer. Parsers either a compound literal
2582 * (env->declaration == NULL) or an initializer of a declaration.
2584 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2586 type_t *type = skip_typeref(env->type);
2587 initializer_t *result = NULL;
2590 if (is_type_scalar(type)) {
2591 result = parse_scalar_initializer(type, env->must_be_constant);
2592 } else if (token.type == '{') {
2596 memset(&path, 0, sizeof(path));
2597 path.top_type = env->type;
2598 path.path = NEW_ARR_F(type_path_entry_t, 0);
2600 descend_into_subtype(&path);
2602 add_anchor_token('}');
2603 result = parse_sub_initializer(&path, env->type, 1, env);
2604 rem_anchor_token('}');
2606 max_index = path.max_index;
2607 DEL_ARR_F(path.path);
2611 /* parse_scalar_initializer() also works in this case: we simply
2612 * have an expression without {} around it */
2613 result = parse_scalar_initializer(type, env->must_be_constant);
2616 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2617 * the array type size */
2618 if (is_type_array(type) && type->array.size_expression == NULL
2619 && result != NULL) {
2621 switch (result->kind) {
2622 case INITIALIZER_LIST:
2623 size = max_index + 1;
2626 case INITIALIZER_STRING:
2627 size = result->string.string.size;
2630 case INITIALIZER_WIDE_STRING:
2631 size = result->wide_string.string.size;
2634 case INITIALIZER_DESIGNATOR:
2635 case INITIALIZER_VALUE:
2636 /* can happen for parse errors */
2641 internal_errorf(HERE, "invalid initializer type");
2644 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2645 cnst->base.type = type_size_t;
2646 cnst->conste.v.int_value = size;
2648 type_t *new_type = duplicate_type(type);
2650 new_type->array.size_expression = cnst;
2651 new_type->array.size_constant = true;
2652 new_type->array.size = size;
2653 env->type = new_type;
2661 static declaration_t *append_declaration(declaration_t *declaration);
2663 static declaration_t *parse_compound_type_specifier(bool is_struct)
2665 gnu_attribute_t *attributes = NULL;
2666 decl_modifiers_t modifiers = 0;
2673 symbol_t *symbol = NULL;
2674 declaration_t *declaration = NULL;
2676 if (token.type == T___attribute__) {
2677 modifiers |= parse_attributes(&attributes);
2680 if (token.type == T_IDENTIFIER) {
2681 symbol = token.v.symbol;
2684 namespace_t const namespc =
2685 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2686 declaration = get_declaration(symbol, namespc);
2687 if (declaration != NULL) {
2688 if (declaration->parent_scope != scope &&
2689 (token.type == '{' || token.type == ';')) {
2691 } else if (declaration->init.complete &&
2692 token.type == '{') {
2693 assert(symbol != NULL);
2694 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2695 is_struct ? "struct" : "union", symbol,
2696 &declaration->source_position);
2697 declaration->scope.declarations = NULL;
2700 } else if (token.type != '{') {
2702 parse_error_expected("while parsing struct type specifier",
2703 T_IDENTIFIER, '{', NULL);
2705 parse_error_expected("while parsing union type specifier",
2706 T_IDENTIFIER, '{', NULL);
2712 if (declaration == NULL) {
2713 declaration = allocate_declaration_zero();
2714 declaration->namespc =
2715 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2716 declaration->source_position = token.source_position;
2717 declaration->symbol = symbol;
2718 declaration->parent_scope = scope;
2719 if (symbol != NULL) {
2720 environment_push(declaration);
2722 append_declaration(declaration);
2725 if (token.type == '{') {
2726 declaration->init.complete = true;
2728 parse_compound_type_entries(declaration);
2729 modifiers |= parse_attributes(&attributes);
2732 declaration->modifiers |= modifiers;
2736 static void parse_enum_entries(type_t *const enum_type)
2740 if (token.type == '}') {
2742 errorf(HERE, "empty enum not allowed");
2746 add_anchor_token('}');
2748 if (token.type != T_IDENTIFIER) {
2749 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2751 rem_anchor_token('}');
2755 declaration_t *const entry = allocate_declaration_zero();
2756 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2757 entry->type = enum_type;
2758 entry->symbol = token.v.symbol;
2759 entry->source_position = token.source_position;
2762 if (token.type == '=') {
2764 expression_t *value = parse_constant_expression();
2766 value = create_implicit_cast(value, enum_type);
2767 entry->init.enum_value = value;
2772 record_declaration(entry, false);
2774 if (token.type != ',')
2777 } while (token.type != '}');
2778 rem_anchor_token('}');
2786 static type_t *parse_enum_specifier(void)
2788 gnu_attribute_t *attributes = NULL;
2789 declaration_t *declaration;
2793 if (token.type == T_IDENTIFIER) {
2794 symbol = token.v.symbol;
2797 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2798 } else if (token.type != '{') {
2799 parse_error_expected("while parsing enum type specifier",
2800 T_IDENTIFIER, '{', NULL);
2807 if (declaration == NULL) {
2808 declaration = allocate_declaration_zero();
2809 declaration->namespc = NAMESPACE_ENUM;
2810 declaration->source_position = token.source_position;
2811 declaration->symbol = symbol;
2812 declaration->parent_scope = scope;
2815 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2816 type->enumt.declaration = declaration;
2818 if (token.type == '{') {
2819 if (declaration->init.complete) {
2820 errorf(HERE, "multiple definitions of enum %Y", symbol);
2822 if (symbol != NULL) {
2823 environment_push(declaration);
2825 append_declaration(declaration);
2826 declaration->init.complete = true;
2828 parse_enum_entries(type);
2829 parse_attributes(&attributes);
2836 * if a symbol is a typedef to another type, return true
2838 static bool is_typedef_symbol(symbol_t *symbol)
2840 const declaration_t *const declaration =
2841 get_declaration(symbol, NAMESPACE_NORMAL);
2843 declaration != NULL &&
2844 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2847 static type_t *parse_typeof(void)
2854 add_anchor_token(')');
2856 expression_t *expression = NULL;
2858 bool old_type_prop = in_type_prop;
2859 bool old_gcc_extension = in_gcc_extension;
2860 in_type_prop = true;
2862 while (token.type == T___extension__) {
2863 /* This can be a prefix to a typename or an expression. */
2865 in_gcc_extension = true;
2867 switch (token.type) {
2869 if (is_typedef_symbol(token.v.symbol)) {
2870 type = parse_typename();
2872 expression = parse_expression();
2873 type = expression->base.type;
2878 type = parse_typename();
2882 expression = parse_expression();
2883 type = expression->base.type;
2886 in_type_prop = old_type_prop;
2887 in_gcc_extension = old_gcc_extension;
2889 rem_anchor_token(')');
2892 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2893 typeof_type->typeoft.expression = expression;
2894 typeof_type->typeoft.typeof_type = type;
2901 typedef enum specifiers_t {
2902 SPECIFIER_SIGNED = 1 << 0,
2903 SPECIFIER_UNSIGNED = 1 << 1,
2904 SPECIFIER_LONG = 1 << 2,
2905 SPECIFIER_INT = 1 << 3,
2906 SPECIFIER_DOUBLE = 1 << 4,
2907 SPECIFIER_CHAR = 1 << 5,
2908 SPECIFIER_SHORT = 1 << 6,
2909 SPECIFIER_LONG_LONG = 1 << 7,
2910 SPECIFIER_FLOAT = 1 << 8,
2911 SPECIFIER_BOOL = 1 << 9,
2912 SPECIFIER_VOID = 1 << 10,
2913 SPECIFIER_INT8 = 1 << 11,
2914 SPECIFIER_INT16 = 1 << 12,
2915 SPECIFIER_INT32 = 1 << 13,
2916 SPECIFIER_INT64 = 1 << 14,
2917 SPECIFIER_INT128 = 1 << 15,
2918 SPECIFIER_COMPLEX = 1 << 16,
2919 SPECIFIER_IMAGINARY = 1 << 17,
2922 static type_t *create_builtin_type(symbol_t *const symbol,
2923 type_t *const real_type)
2925 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2926 type->builtin.symbol = symbol;
2927 type->builtin.real_type = real_type;
2929 type_t *result = typehash_insert(type);
2930 if (type != result) {
2937 static type_t *get_typedef_type(symbol_t *symbol)
2939 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2940 if (declaration == NULL ||
2941 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2944 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2945 type->typedeft.declaration = declaration;
2951 * check for the allowed MS alignment values.
2953 static bool check_alignment_value(long long intvalue)
2955 if (intvalue < 1 || intvalue > 8192) {
2956 errorf(HERE, "illegal alignment value");
2959 unsigned v = (unsigned)intvalue;
2960 for (unsigned i = 1; i <= 8192; i += i) {
2964 errorf(HERE, "alignment must be power of two");
2968 #define DET_MOD(name, tag) do { \
2969 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2970 *modifiers |= tag; \
2973 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2975 decl_modifiers_t *modifiers = &specifiers->modifiers;
2978 if (token.type == T_restrict) {
2980 DET_MOD(restrict, DM_RESTRICT);
2982 } else if (token.type != T_IDENTIFIER)
2984 symbol_t *symbol = token.v.symbol;
2985 if (symbol == sym_align) {
2988 if (token.type != T_INTEGER)
2990 if (check_alignment_value(token.v.intvalue)) {
2991 if (specifiers->alignment != 0)
2992 warningf(HERE, "align used more than once");
2993 specifiers->alignment = (unsigned char)token.v.intvalue;
2997 } else if (symbol == sym_allocate) {
3000 if (token.type != T_IDENTIFIER)
3002 (void)token.v.symbol;
3004 } else if (symbol == sym_dllimport) {
3006 DET_MOD(dllimport, DM_DLLIMPORT);
3007 } else if (symbol == sym_dllexport) {
3009 DET_MOD(dllexport, DM_DLLEXPORT);
3010 } else if (symbol == sym_thread) {
3012 DET_MOD(thread, DM_THREAD);
3013 } else if (symbol == sym_naked) {
3015 DET_MOD(naked, DM_NAKED);
3016 } else if (symbol == sym_noinline) {
3018 DET_MOD(noinline, DM_NOINLINE);
3019 } else if (symbol == sym_noreturn) {
3021 DET_MOD(noreturn, DM_NORETURN);
3022 } else if (symbol == sym_nothrow) {
3024 DET_MOD(nothrow, DM_NOTHROW);
3025 } else if (symbol == sym_novtable) {
3027 DET_MOD(novtable, DM_NOVTABLE);
3028 } else if (symbol == sym_property) {
3032 bool is_get = false;
3033 if (token.type != T_IDENTIFIER)
3035 if (token.v.symbol == sym_get) {
3037 } else if (token.v.symbol == sym_put) {
3039 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3044 if (token.type != T_IDENTIFIER)
3047 if (specifiers->get_property_sym != NULL) {
3048 errorf(HERE, "get property name already specified");
3050 specifiers->get_property_sym = token.v.symbol;
3053 if (specifiers->put_property_sym != NULL) {
3054 errorf(HERE, "put property name already specified");
3056 specifiers->put_property_sym = token.v.symbol;
3060 if (token.type == ',') {
3067 } else if (symbol == sym_selectany) {
3069 DET_MOD(selectany, DM_SELECTANY);
3070 } else if (symbol == sym_uuid) {
3073 if (token.type != T_STRING_LITERAL)
3077 } else if (symbol == sym_deprecated) {
3079 if (specifiers->deprecated != 0)
3080 warningf(HERE, "deprecated used more than once");
3081 specifiers->deprecated = 1;
3082 if (token.type == '(') {
3084 if (token.type == T_STRING_LITERAL) {
3085 specifiers->deprecated_string = token.v.string.begin;
3088 errorf(HERE, "string literal expected");
3092 } else if (symbol == sym_noalias) {
3094 DET_MOD(noalias, DM_NOALIAS);
3096 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3098 if (token.type == '(')
3102 if (token.type == ',')
3109 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3111 declaration_t *const decl = allocate_declaration_zero();
3112 decl->source_position = *HERE;
3113 decl->declared_storage_class = storage_class;
3114 decl->storage_class =
3115 storage_class != STORAGE_CLASS_NONE || scope == file_scope ?
3116 storage_class : STORAGE_CLASS_AUTO;
3117 decl->symbol = symbol;
3118 decl->implicit = true;
3119 record_declaration(decl, false);
3124 * Finish the construction of a struct type by calculating
3125 * its size, offsets, alignment.
3127 static void finish_struct_type(compound_type_t *type) {
3128 if (type->declaration == NULL)
3130 declaration_t *struct_decl = type->declaration;
3131 if (! struct_decl->init.complete)
3136 il_alignment_t alignment = 1;
3137 bool need_pad = false;
3139 declaration_t *entry = struct_decl->scope.declarations;
3140 for (; entry != NULL; entry = entry->next) {
3141 if (entry->namespc != NAMESPACE_NORMAL)
3144 type_t *m_type = skip_typeref(entry->type);
3145 if (! is_type_valid(m_type)) {
3146 /* simply ignore errors here */
3149 il_alignment_t m_alignment = m_type->base.alignment;
3150 if (m_alignment > alignment)
3151 alignment = m_alignment;
3153 offset = (size + m_alignment - 1) & -m_alignment;
3157 entry->offset = offset;
3158 size = offset + m_type->base.size;
3160 if (type->base.alignment != 0) {
3161 alignment = type->base.alignment;
3164 offset = (size + alignment - 1) & -alignment;
3168 if (warning.padded && need_pad) {
3169 warningf(&struct_decl->source_position,
3170 "'%#T' needs padding", type, struct_decl->symbol);
3172 if (warning.packed && !need_pad) {
3173 warningf(&struct_decl->source_position,
3174 "superfluous packed attribute on '%#T'",
3175 type, struct_decl->symbol);
3178 type->base.size = offset;
3179 type->base.alignment = alignment;
3183 * Finish the construction of an union type by calculating
3184 * its size and alignment.
3186 static void finish_union_type(compound_type_t *type) {
3187 if (type->declaration == NULL)
3189 declaration_t *union_decl = type->declaration;
3190 if (! union_decl->init.complete)
3194 il_alignment_t alignment = 1;
3196 declaration_t *entry = union_decl->scope.declarations;
3197 for (; entry != NULL; entry = entry->next) {
3198 if (entry->namespc != NAMESPACE_NORMAL)
3201 type_t *m_type = skip_typeref(entry->type);
3202 if (! is_type_valid(m_type))
3206 if (m_type->base.size > size)
3207 size = m_type->base.size;
3208 if (m_type->base.alignment > alignment)
3209 alignment = m_type->base.alignment;
3211 if (type->base.alignment != 0) {
3212 alignment = type->base.alignment;
3214 size = (size + alignment - 1) & -alignment;
3215 type->base.size = size;
3216 type->base.alignment = alignment;
3219 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3221 type_t *type = NULL;
3222 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3223 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3224 unsigned type_specifiers = 0;
3225 bool newtype = false;
3226 bool saw_error = false;
3227 bool old_gcc_extension = in_gcc_extension;
3229 specifiers->source_position = token.source_position;
3232 specifiers->modifiers
3233 |= parse_attributes(&specifiers->gnu_attributes);
3234 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3235 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3237 switch (token.type) {
3240 #define MATCH_STORAGE_CLASS(token, class) \
3242 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3243 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3245 specifiers->declared_storage_class = class; \
3249 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3250 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3251 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3252 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3253 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3258 add_anchor_token(')');
3259 parse_microsoft_extended_decl_modifier(specifiers);
3260 rem_anchor_token(')');
3265 switch (specifiers->declared_storage_class) {
3266 case STORAGE_CLASS_NONE:
3267 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3270 case STORAGE_CLASS_EXTERN:
3271 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3274 case STORAGE_CLASS_STATIC:
3275 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3279 errorf(HERE, "multiple storage classes in declaration specifiers");
3285 /* type qualifiers */
3286 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3288 qualifiers |= qualifier; \
3292 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3293 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3294 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3295 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3296 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3297 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3298 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3299 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3301 case T___extension__:
3303 in_gcc_extension = true;
3306 /* type specifiers */
3307 #define MATCH_SPECIFIER(token, specifier, name) \
3310 if (type_specifiers & specifier) { \
3311 errorf(HERE, "multiple " name " type specifiers given"); \
3313 type_specifiers |= specifier; \
3317 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3318 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3319 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3320 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3321 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3322 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3323 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3324 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3325 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3326 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3327 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3328 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3329 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3330 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3331 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3332 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3334 case T__forceinline:
3335 /* only in microsoft mode */
3336 specifiers->modifiers |= DM_FORCEINLINE;
3341 specifiers->is_inline = true;
3346 if (type_specifiers & SPECIFIER_LONG_LONG) {
3347 errorf(HERE, "multiple type specifiers given");
3348 } else if (type_specifiers & SPECIFIER_LONG) {
3349 type_specifiers |= SPECIFIER_LONG_LONG;
3351 type_specifiers |= SPECIFIER_LONG;
3356 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3358 type->compound.declaration = parse_compound_type_specifier(true);
3359 finish_struct_type(&type->compound);
3363 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3364 type->compound.declaration = parse_compound_type_specifier(false);
3365 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3366 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3367 finish_union_type(&type->compound);
3371 type = parse_enum_specifier();
3374 type = parse_typeof();
3376 case T___builtin_va_list:
3377 type = duplicate_type(type_valist);
3381 case T_IDENTIFIER: {
3382 /* only parse identifier if we haven't found a type yet */
3383 if (type != NULL || type_specifiers != 0) {
3384 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3385 * declaration, so it doesn't generate errors about expecting '(' or
3387 switch (look_ahead(1)->type) {
3394 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3397 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3402 goto finish_specifiers;
3406 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3407 if (typedef_type == NULL) {
3408 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3409 * declaration, so it doesn't generate 'implicit int' followed by more
3410 * errors later on. */
3411 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3416 errorf(HERE, "%K does not name a type", &token);
3418 declaration_t *const decl =
3419 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3421 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3422 type->typedeft.declaration = decl;
3426 if (la1_type == '*')
3427 goto finish_specifiers;
3432 goto finish_specifiers;
3437 type = typedef_type;
3441 /* function specifier */
3443 goto finish_specifiers;
3448 in_gcc_extension = old_gcc_extension;
3450 if (type == NULL || (saw_error && type_specifiers != 0)) {
3451 atomic_type_kind_t atomic_type;
3453 /* match valid basic types */
3454 switch(type_specifiers) {
3455 case SPECIFIER_VOID:
3456 atomic_type = ATOMIC_TYPE_VOID;
3458 case SPECIFIER_CHAR:
3459 atomic_type = ATOMIC_TYPE_CHAR;
3461 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3462 atomic_type = ATOMIC_TYPE_SCHAR;
3464 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3465 atomic_type = ATOMIC_TYPE_UCHAR;
3467 case SPECIFIER_SHORT:
3468 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3469 case SPECIFIER_SHORT | SPECIFIER_INT:
3470 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3471 atomic_type = ATOMIC_TYPE_SHORT;
3473 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3474 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3475 atomic_type = ATOMIC_TYPE_USHORT;
3478 case SPECIFIER_SIGNED:
3479 case SPECIFIER_SIGNED | SPECIFIER_INT:
3480 atomic_type = ATOMIC_TYPE_INT;
3482 case SPECIFIER_UNSIGNED:
3483 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3484 atomic_type = ATOMIC_TYPE_UINT;
3486 case SPECIFIER_LONG:
3487 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3488 case SPECIFIER_LONG | SPECIFIER_INT:
3489 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3490 atomic_type = ATOMIC_TYPE_LONG;
3492 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3493 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3494 atomic_type = ATOMIC_TYPE_ULONG;
3497 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3498 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3499 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3500 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3502 atomic_type = ATOMIC_TYPE_LONGLONG;
3503 goto warn_about_long_long;
3505 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3506 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3508 atomic_type = ATOMIC_TYPE_ULONGLONG;
3509 warn_about_long_long:
3510 if (warning.long_long) {
3511 warningf(&specifiers->source_position,
3512 "ISO C90 does not support 'long long'");
3516 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3517 atomic_type = unsigned_int8_type_kind;
3520 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3521 atomic_type = unsigned_int16_type_kind;
3524 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3525 atomic_type = unsigned_int32_type_kind;
3528 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3529 atomic_type = unsigned_int64_type_kind;
3532 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3533 atomic_type = unsigned_int128_type_kind;
3536 case SPECIFIER_INT8:
3537 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3538 atomic_type = int8_type_kind;
3541 case SPECIFIER_INT16:
3542 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3543 atomic_type = int16_type_kind;
3546 case SPECIFIER_INT32:
3547 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3548 atomic_type = int32_type_kind;
3551 case SPECIFIER_INT64:
3552 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3553 atomic_type = int64_type_kind;
3556 case SPECIFIER_INT128:
3557 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3558 atomic_type = int128_type_kind;
3561 case SPECIFIER_FLOAT:
3562 atomic_type = ATOMIC_TYPE_FLOAT;
3564 case SPECIFIER_DOUBLE:
3565 atomic_type = ATOMIC_TYPE_DOUBLE;
3567 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3568 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3570 case SPECIFIER_BOOL:
3571 atomic_type = ATOMIC_TYPE_BOOL;
3573 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3574 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3575 atomic_type = ATOMIC_TYPE_FLOAT;
3577 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3578 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3579 atomic_type = ATOMIC_TYPE_DOUBLE;
3581 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3582 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3583 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3586 /* invalid specifier combination, give an error message */
3587 if (type_specifiers == 0) {
3592 if (warning.implicit_int) {
3593 warningf(HERE, "no type specifiers in declaration, using 'int'");
3595 atomic_type = ATOMIC_TYPE_INT;
3598 errorf(HERE, "no type specifiers given in declaration");
3600 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3601 (type_specifiers & SPECIFIER_UNSIGNED)) {
3602 errorf(HERE, "signed and unsigned specifiers given");
3603 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3604 errorf(HERE, "only integer types can be signed or unsigned");
3606 errorf(HERE, "multiple datatypes in declaration");
3611 if (type_specifiers & SPECIFIER_COMPLEX) {
3612 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3613 type->complex.akind = atomic_type;
3614 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3615 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3616 type->imaginary.akind = atomic_type;
3618 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3619 type->atomic.akind = atomic_type;
3622 } else if (type_specifiers != 0) {
3623 errorf(HERE, "multiple datatypes in declaration");
3626 /* FIXME: check type qualifiers here */
3628 type->base.qualifiers = qualifiers;
3629 type->base.modifiers = modifiers;
3631 type_t *result = typehash_insert(type);
3632 if (newtype && result != type) {
3636 specifiers->type = result;
3640 specifiers->type = type_error_type;
3644 static type_qualifiers_t parse_type_qualifiers(void)
3646 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3649 switch(token.type) {
3650 /* type qualifiers */
3651 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3652 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3653 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3654 /* microsoft extended type modifiers */
3655 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3656 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3657 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3658 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3659 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3668 * Parses an K&R identifier list and return a list of declarations.
3670 * @param last points to the last declaration in the list
3671 * @return the list of declarations
3673 static declaration_t *parse_identifier_list(declaration_t **last)
3675 declaration_t *declarations = NULL;
3676 declaration_t *last_declaration = NULL;
3678 declaration_t *const declaration = allocate_declaration_zero();
3679 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3680 declaration->source_position = token.source_position;
3681 declaration->symbol = token.v.symbol;
3684 if (last_declaration != NULL) {
3685 last_declaration->next = declaration;
3687 declarations = declaration;
3689 last_declaration = declaration;
3691 if (token.type != ',') {
3695 } while (token.type == T_IDENTIFIER);
3697 *last = last_declaration;
3698 return declarations;
3701 static type_t *automatic_type_conversion(type_t *orig_type);
3703 static void semantic_parameter(declaration_t *declaration)
3705 /* TODO: improve error messages */
3706 source_position_t const* const pos = &declaration->source_position;
3708 switch (declaration->declared_storage_class) {
3709 case STORAGE_CLASS_TYPEDEF:
3710 errorf(pos, "typedef not allowed in parameter list");
3713 /* Allowed storage classes */
3714 case STORAGE_CLASS_NONE:
3715 case STORAGE_CLASS_REGISTER:
3719 errorf(pos, "parameter may only have none or register storage class");
3723 type_t *const orig_type = declaration->type;
3724 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3725 * sugar. Turn it into a pointer.
3726 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3727 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3729 type_t *const type = automatic_type_conversion(orig_type);
3730 declaration->type = type;
3732 if (is_type_incomplete(skip_typeref(type))) {
3733 errorf(pos, "parameter '%#T' is of incomplete type",
3734 orig_type, declaration->symbol);
3738 static declaration_t *parse_parameter(void)
3740 declaration_specifiers_t specifiers;
3741 memset(&specifiers, 0, sizeof(specifiers));
3743 parse_declaration_specifiers(&specifiers);
3745 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3751 * Parses a function type parameter list and return a list of declarations.
3753 * @param last point to the last element of the list
3754 * @return the parameter list
3756 static declaration_t *parse_parameters(function_type_t *type, declaration_t **last)
3758 declaration_t *declarations = NULL;
3761 add_anchor_token(')');
3762 int saved_comma_state = save_and_reset_anchor_state(',');
3764 if (token.type == T_IDENTIFIER &&
3765 !is_typedef_symbol(token.v.symbol)) {
3766 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3767 if (la1_type == ',' || la1_type == ')') {
3768 type->kr_style_parameters = true;
3769 declarations = parse_identifier_list(last);
3770 goto parameters_finished;
3774 if (token.type == ')') {
3775 type->unspecified_parameters = 1;
3776 goto parameters_finished;
3779 declaration_t *declaration;
3780 declaration_t *last_declaration = NULL;
3781 function_parameter_t *parameter;
3782 function_parameter_t *last_parameter = NULL;
3785 switch(token.type) {
3789 goto parameters_finished;
3792 case T___extension__:
3794 declaration = parse_parameter();
3796 /* func(void) is not a parameter */
3797 if (last_parameter == NULL
3798 && token.type == ')'
3799 && declaration->symbol == NULL
3800 && skip_typeref(declaration->type) == type_void) {
3801 goto parameters_finished;
3803 semantic_parameter(declaration);
3805 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3806 memset(parameter, 0, sizeof(parameter[0]));
3807 parameter->type = declaration->type;
3809 if (last_parameter != NULL) {
3810 last_declaration->next = declaration;
3811 last_parameter->next = parameter;
3813 type->parameters = parameter;
3814 declarations = declaration;
3816 last_parameter = parameter;
3817 last_declaration = declaration;
3821 goto parameters_finished;
3823 if (token.type != ',') {
3824 goto parameters_finished;
3830 parameters_finished:
3831 rem_anchor_token(')');
3834 restore_anchor_state(',', saved_comma_state);
3835 *last = last_declaration;
3836 return declarations;
3839 restore_anchor_state(',', saved_comma_state);
3844 typedef enum construct_type_kind_t {
3849 } construct_type_kind_t;
3851 typedef struct construct_type_t construct_type_t;
3852 struct construct_type_t {
3853 construct_type_kind_t kind;
3854 construct_type_t *next;
3857 typedef struct parsed_pointer_t parsed_pointer_t;
3858 struct parsed_pointer_t {
3859 construct_type_t construct_type;
3860 type_qualifiers_t type_qualifiers;
3863 typedef struct construct_function_type_t construct_function_type_t;
3864 struct construct_function_type_t {
3865 construct_type_t construct_type;
3866 type_t *function_type;
3869 typedef struct parsed_array_t parsed_array_t;
3870 struct parsed_array_t {
3871 construct_type_t construct_type;
3872 type_qualifiers_t type_qualifiers;
3878 typedef struct construct_base_type_t construct_base_type_t;
3879 struct construct_base_type_t {
3880 construct_type_t construct_type;
3884 static construct_type_t *parse_pointer_declarator(void)
3888 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3889 memset(pointer, 0, sizeof(pointer[0]));
3890 pointer->construct_type.kind = CONSTRUCT_POINTER;
3891 pointer->type_qualifiers = parse_type_qualifiers();
3893 return (construct_type_t*) pointer;
3896 static construct_type_t *parse_array_declarator(void)
3899 add_anchor_token(']');
3901 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3902 memset(array, 0, sizeof(array[0]));
3903 array->construct_type.kind = CONSTRUCT_ARRAY;
3905 if (token.type == T_static) {
3906 array->is_static = true;
3910 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3911 if (type_qualifiers != 0) {
3912 if (token.type == T_static) {
3913 array->is_static = true;
3917 array->type_qualifiers = type_qualifiers;
3919 if (token.type == '*' && look_ahead(1)->type == ']') {
3920 array->is_variable = true;
3922 } else if (token.type != ']') {
3923 array->size = parse_assignment_expression();
3926 rem_anchor_token(']');
3930 return (construct_type_t*) array;
3933 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3936 if (declaration != NULL) {
3937 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3939 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3941 if (mask & (mask-1)) {
3942 const char *first = NULL, *second = NULL;
3944 /* more than one calling convention set */
3945 if (declaration->modifiers & DM_CDECL) {
3946 if (first == NULL) first = "cdecl";
3947 else if (second == NULL) second = "cdecl";
3949 if (declaration->modifiers & DM_STDCALL) {
3950 if (first == NULL) first = "stdcall";
3951 else if (second == NULL) second = "stdcall";
3953 if (declaration->modifiers & DM_FASTCALL) {
3954 if (first == NULL) first = "fastcall";
3955 else if (second == NULL) second = "fastcall";
3957 if (declaration->modifiers & DM_THISCALL) {
3958 if (first == NULL) first = "thiscall";
3959 else if (second == NULL) second = "thiscall";
3961 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3964 if (declaration->modifiers & DM_CDECL)
3965 type->function.calling_convention = CC_CDECL;
3966 else if (declaration->modifiers & DM_STDCALL)
3967 type->function.calling_convention = CC_STDCALL;
3968 else if (declaration->modifiers & DM_FASTCALL)
3969 type->function.calling_convention = CC_FASTCALL;
3970 else if (declaration->modifiers & DM_THISCALL)
3971 type->function.calling_convention = CC_THISCALL;
3973 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3976 declaration_t *last;
3977 declaration_t *parameters = parse_parameters(&type->function, &last);
3978 if (declaration != NULL) {
3979 declaration->scope.declarations = parameters;
3980 declaration->scope.last_declaration = last;
3981 declaration->scope.is_parameter = true;
3984 construct_function_type_t *construct_function_type =
3985 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3986 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3987 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3988 construct_function_type->function_type = type;
3990 return &construct_function_type->construct_type;
3993 static void fix_declaration_type(declaration_t *declaration)
3995 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3996 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3998 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3999 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4001 if (declaration->type->base.modifiers == type_modifiers)
4004 type_t *copy = duplicate_type(declaration->type);
4005 copy->base.modifiers = type_modifiers;
4007 type_t *result = typehash_insert(copy);
4008 if (result != copy) {
4009 obstack_free(type_obst, copy);
4012 declaration->type = result;
4015 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
4016 bool may_be_abstract)
4018 /* construct a single linked list of construct_type_t's which describe
4019 * how to construct the final declarator type */
4020 construct_type_t *first = NULL;
4021 construct_type_t *last = NULL;
4022 gnu_attribute_t *attributes = NULL;
4024 decl_modifiers_t modifiers = parse_attributes(&attributes);
4027 while (token.type == '*') {
4028 construct_type_t *type = parse_pointer_declarator();
4038 /* TODO: find out if this is correct */
4039 modifiers |= parse_attributes(&attributes);
4042 if (declaration != NULL)
4043 declaration->modifiers |= modifiers;
4045 construct_type_t *inner_types = NULL;
4047 switch(token.type) {
4049 if (declaration == NULL) {
4050 errorf(HERE, "no identifier expected in typename");
4052 declaration->symbol = token.v.symbol;
4053 declaration->source_position = token.source_position;
4059 add_anchor_token(')');
4060 inner_types = parse_inner_declarator(declaration, may_be_abstract);
4061 if (inner_types != NULL) {
4062 /* All later declarators only modify the return type, not declaration */
4065 rem_anchor_token(')');
4069 if (may_be_abstract)
4071 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4076 construct_type_t *p = last;
4079 construct_type_t *type;
4080 switch(token.type) {
4082 type = parse_function_declarator(declaration);
4085 type = parse_array_declarator();
4088 goto declarator_finished;
4091 /* insert in the middle of the list (behind p) */
4093 type->next = p->next;
4104 declarator_finished:
4105 /* append inner_types at the end of the list, we don't to set last anymore
4106 * as it's not needed anymore */
4108 assert(first == NULL);
4109 first = inner_types;
4111 last->next = inner_types;
4119 static void parse_declaration_attributes(declaration_t *declaration)
4121 gnu_attribute_t *attributes = NULL;
4122 decl_modifiers_t modifiers = parse_attributes(&attributes);
4124 if (declaration == NULL)
4127 declaration->modifiers |= modifiers;
4128 /* check if we have these stupid mode attributes... */
4129 type_t *old_type = declaration->type;
4130 if (old_type == NULL)
4133 gnu_attribute_t *attribute = attributes;
4134 for ( ; attribute != NULL; attribute = attribute->next) {
4135 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4138 atomic_type_kind_t akind = attribute->u.akind;
4139 if (!is_type_signed(old_type)) {
4141 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4142 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4143 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4144 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4146 panic("invalid akind in mode attribute");
4150 = make_atomic_type(akind, old_type->base.qualifiers);
4154 static type_t *construct_declarator_type(construct_type_t *construct_list,
4157 construct_type_t *iter = construct_list;
4158 for( ; iter != NULL; iter = iter->next) {
4159 switch(iter->kind) {
4160 case CONSTRUCT_INVALID:
4161 internal_errorf(HERE, "invalid type construction found");
4162 case CONSTRUCT_FUNCTION: {
4163 construct_function_type_t *construct_function_type
4164 = (construct_function_type_t*) iter;
4166 type_t *function_type = construct_function_type->function_type;
4168 function_type->function.return_type = type;
4170 type_t *skipped_return_type = skip_typeref(type);
4172 if (is_type_function(skipped_return_type)) {
4173 errorf(HERE, "function returning function is not allowed");
4174 } else if (is_type_array(skipped_return_type)) {
4175 errorf(HERE, "function returning array is not allowed");
4177 if (skipped_return_type->base.qualifiers != 0) {
4179 "type qualifiers in return type of function type are meaningless");
4183 type = function_type;
4187 case CONSTRUCT_POINTER: {
4188 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4189 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4190 pointer_type->pointer.points_to = type;
4191 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4193 type = pointer_type;
4197 case CONSTRUCT_ARRAY: {
4198 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4199 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4201 expression_t *size_expression = parsed_array->size;
4202 if (size_expression != NULL) {
4204 = create_implicit_cast(size_expression, type_size_t);
4207 array_type->base.qualifiers = parsed_array->type_qualifiers;
4208 array_type->array.element_type = type;
4209 array_type->array.is_static = parsed_array->is_static;
4210 array_type->array.is_variable = parsed_array->is_variable;
4211 array_type->array.size_expression = size_expression;
4213 if (size_expression != NULL) {
4214 if (is_constant_expression(size_expression)) {
4215 array_type->array.size_constant = true;
4216 array_type->array.size
4217 = fold_constant(size_expression);
4219 array_type->array.is_vla = true;
4223 type_t *skipped_type = skip_typeref(type);
4225 if (is_type_incomplete(skipped_type)) {
4226 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4227 } else if (is_type_function(skipped_type)) {
4228 errorf(HERE, "array of functions is not allowed");
4235 type_t *hashed_type = typehash_insert(type);
4236 if (hashed_type != type) {
4237 /* the function type was constructed earlier freeing it here will
4238 * destroy other types... */
4239 if (iter->kind != CONSTRUCT_FUNCTION) {
4249 static declaration_t *parse_declarator(
4250 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4252 declaration_t *const declaration = allocate_declaration_zero();
4253 declaration->source_position = specifiers->source_position;
4254 declaration->declared_storage_class = specifiers->declared_storage_class;
4255 declaration->modifiers = specifiers->modifiers;
4256 declaration->deprecated_string = specifiers->deprecated_string;
4257 declaration->get_property_sym = specifiers->get_property_sym;
4258 declaration->put_property_sym = specifiers->put_property_sym;
4259 declaration->is_inline = specifiers->is_inline;
4261 declaration->storage_class = specifiers->declared_storage_class;
4262 if (declaration->storage_class == STORAGE_CLASS_NONE &&
4263 scope != file_scope) {
4264 declaration->storage_class = STORAGE_CLASS_AUTO;
4267 if (specifiers->alignment != 0) {
4268 /* TODO: add checks here */
4269 declaration->alignment = specifiers->alignment;
4272 construct_type_t *construct_type
4273 = parse_inner_declarator(declaration, may_be_abstract);
4274 type_t *const type = specifiers->type;
4275 declaration->type = construct_declarator_type(construct_type, type);
4277 parse_declaration_attributes(declaration);
4279 fix_declaration_type(declaration);
4281 if (construct_type != NULL) {
4282 obstack_free(&temp_obst, construct_type);
4288 static type_t *parse_abstract_declarator(type_t *base_type)
4290 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4292 type_t *result = construct_declarator_type(construct_type, base_type);
4293 if (construct_type != NULL) {
4294 obstack_free(&temp_obst, construct_type);
4300 static declaration_t *append_declaration(declaration_t* const declaration)
4302 if (last_declaration != NULL) {
4303 last_declaration->next = declaration;
4305 scope->declarations = declaration;
4307 last_declaration = declaration;
4312 * Check if the declaration of main is suspicious. main should be a
4313 * function with external linkage, returning int, taking either zero
4314 * arguments, two, or three arguments of appropriate types, ie.
4316 * int main([ int argc, char **argv [, char **env ] ]).
4318 * @param decl the declaration to check
4319 * @param type the function type of the declaration
4321 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4323 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4324 warningf(&decl->source_position,
4325 "'main' is normally a non-static function");
4327 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4328 warningf(&decl->source_position,
4329 "return type of 'main' should be 'int', but is '%T'",
4330 func_type->return_type);
4332 const function_parameter_t *parm = func_type->parameters;
4334 type_t *const first_type = parm->type;
4335 if (!types_compatible(skip_typeref(first_type), type_int)) {
4336 warningf(&decl->source_position,
4337 "first argument of 'main' should be 'int', but is '%T'", first_type);
4341 type_t *const second_type = parm->type;
4342 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4343 warningf(&decl->source_position,
4344 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4348 type_t *const third_type = parm->type;
4349 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4350 warningf(&decl->source_position,
4351 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4355 goto warn_arg_count;
4359 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4365 * Check if a symbol is the equal to "main".
4367 static bool is_sym_main(const symbol_t *const sym)
4369 return strcmp(sym->string, "main") == 0;
4372 static declaration_t *record_declaration(
4373 declaration_t *const declaration,
4374 const bool is_definition)
4376 const symbol_t *const symbol = declaration->symbol;
4377 const namespace_t namespc = (namespace_t)declaration->namespc;
4379 assert(symbol != NULL);
4380 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4382 type_t *const orig_type = declaration->type;
4383 type_t *const type = skip_typeref(orig_type);
4384 if (is_type_function(type) &&
4385 type->function.unspecified_parameters &&
4386 warning.strict_prototypes &&
4387 previous_declaration == NULL) {
4388 warningf(&declaration->source_position,
4389 "function declaration '%#T' is not a prototype",
4393 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4394 check_type_of_main(declaration, &type->function);
4397 if (warning.nested_externs &&
4398 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4399 scope != file_scope) {
4400 warningf(&declaration->source_position,
4401 "nested extern declaration of '%#T'", declaration->type, symbol);
4404 assert(declaration != previous_declaration);
4405 if (previous_declaration != NULL &&
4406 previous_declaration->parent_scope->is_parameter &&
4407 scope->depth == previous_declaration->parent_scope->depth + 1) {
4408 errorf(&declaration->source_position,
4409 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4410 orig_type, symbol, previous_declaration->type, symbol,
4411 &previous_declaration->source_position);
4414 if (previous_declaration != NULL &&
4415 previous_declaration->parent_scope == scope) {
4416 /* can happen for K&R style declarations */
4417 if (previous_declaration->type == NULL) {
4418 previous_declaration->type = declaration->type;
4421 const type_t *prev_type = skip_typeref(previous_declaration->type);
4422 if (!types_compatible(type, prev_type)) {
4423 errorf(&declaration->source_position,
4424 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4425 orig_type, symbol, previous_declaration->type, symbol,
4426 &previous_declaration->source_position);
4428 unsigned old_storage_class = previous_declaration->storage_class;
4429 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4430 errorf(&declaration->source_position,
4431 "redeclaration of enum entry '%Y' (declared %P)",
4432 symbol, &previous_declaration->source_position);
4433 return previous_declaration;
4436 if (warning.redundant_decls &&
4438 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4439 !(previous_declaration->modifiers & DM_USED) &&
4440 !previous_declaration->used) {
4441 warningf(&previous_declaration->source_position,
4442 "unnecessary static forward declaration for '%#T'",
4443 previous_declaration->type, symbol);
4446 unsigned new_storage_class = declaration->storage_class;
4448 if (is_type_incomplete(prev_type)) {
4449 previous_declaration->type = type;
4453 /* pretend no storage class means extern for function
4454 * declarations (except if the previous declaration is neither
4455 * none nor extern) */
4456 if (is_type_function(type)) {
4457 if (prev_type->function.unspecified_parameters) {
4458 previous_declaration->type = type;
4462 switch (old_storage_class) {
4463 case STORAGE_CLASS_NONE:
4464 old_storage_class = STORAGE_CLASS_EXTERN;
4467 case STORAGE_CLASS_EXTERN:
4468 if (is_definition) {
4469 if (warning.missing_prototypes &&
4470 prev_type->function.unspecified_parameters &&
4471 !is_sym_main(symbol)) {
4472 warningf(&declaration->source_position,
4473 "no previous prototype for '%#T'",
4476 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4477 new_storage_class = STORAGE_CLASS_EXTERN;
4486 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4487 new_storage_class == STORAGE_CLASS_EXTERN) {
4488 warn_redundant_declaration:
4489 if (!is_definition &&
4490 warning.redundant_decls &&
4491 is_type_valid(prev_type) &&
4492 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4493 warningf(&declaration->source_position,
4494 "redundant declaration for '%Y' (declared %P)",
4495 symbol, &previous_declaration->source_position);
4497 } else if (current_function == NULL) {
4498 if (old_storage_class != STORAGE_CLASS_STATIC &&
4499 new_storage_class == STORAGE_CLASS_STATIC) {
4500 errorf(&declaration->source_position,
4501 "static declaration of '%Y' follows non-static declaration (declared %P)",
4502 symbol, &previous_declaration->source_position);
4503 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4504 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4505 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4507 goto warn_redundant_declaration;
4509 } else if (is_type_valid(prev_type)) {
4510 if (old_storage_class == new_storage_class) {
4511 errorf(&declaration->source_position,
4512 "redeclaration of '%Y' (declared %P)",
4513 symbol, &previous_declaration->source_position);
4515 errorf(&declaration->source_position,
4516 "redeclaration of '%Y' with different linkage (declared %P)",
4517 symbol, &previous_declaration->source_position);
4522 previous_declaration->modifiers |= declaration->modifiers;
4523 previous_declaration->is_inline |= declaration->is_inline;
4524 return previous_declaration;
4525 } else if (is_type_function(type)) {
4526 if (is_definition &&
4527 declaration->storage_class != STORAGE_CLASS_STATIC) {
4528 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4529 warningf(&declaration->source_position,
4530 "no previous prototype for '%#T'", orig_type, symbol);
4531 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4532 warningf(&declaration->source_position,
4533 "no previous declaration for '%#T'", orig_type,
4538 if (warning.missing_declarations &&
4539 scope == file_scope && (
4540 declaration->storage_class == STORAGE_CLASS_NONE ||
4541 declaration->storage_class == STORAGE_CLASS_THREAD
4543 warningf(&declaration->source_position,
4544 "no previous declaration for '%#T'", orig_type, symbol);
4548 assert(declaration->parent_scope == NULL);
4549 assert(scope != NULL);
4551 declaration->parent_scope = scope;
4553 environment_push(declaration);
4554 return append_declaration(declaration);
4557 static void parser_error_multiple_definition(declaration_t *declaration,
4558 const source_position_t *source_position)
4560 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4561 declaration->symbol, &declaration->source_position);
4564 static bool is_declaration_specifier(const token_t *token,
4565 bool only_specifiers_qualifiers)
4567 switch (token->type) {
4572 return is_typedef_symbol(token->v.symbol);
4574 case T___extension__:
4576 return !only_specifiers_qualifiers;
4583 static void parse_init_declarator_rest(declaration_t *declaration)
4587 type_t *orig_type = declaration->type;
4588 type_t *type = skip_typeref(orig_type);
4590 if (declaration->init.initializer != NULL) {
4591 parser_error_multiple_definition(declaration, HERE);
4594 bool must_be_constant = false;
4595 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4596 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4597 declaration->parent_scope == file_scope) {
4598 must_be_constant = true;
4601 if (is_type_function(type)) {
4602 errorf(&declaration->source_position,
4603 "function '%#T' is initialized like a variable",
4604 orig_type, declaration->symbol);
4605 orig_type = type_error_type;
4608 parse_initializer_env_t env;
4609 env.type = orig_type;
4610 env.must_be_constant = must_be_constant;
4611 env.declaration = current_init_decl = declaration;
4613 initializer_t *initializer = parse_initializer(&env);
4614 current_init_decl = NULL;
4616 if (!is_type_function(type)) {
4617 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4618 * the array type size */
4619 declaration->type = env.type;
4620 declaration->init.initializer = initializer;
4624 /* parse rest of a declaration without any declarator */
4625 static void parse_anonymous_declaration_rest(
4626 const declaration_specifiers_t *specifiers)
4630 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) {
4631 warningf(&specifiers->source_position,
4632 "useless storage class in empty declaration");
4635 type_t *type = specifiers->type;
4636 switch (type->kind) {
4637 case TYPE_COMPOUND_STRUCT:
4638 case TYPE_COMPOUND_UNION: {
4639 if (type->compound.declaration->symbol == NULL) {
4640 warningf(&specifiers->source_position,
4641 "unnamed struct/union that defines no instances");
4650 warningf(&specifiers->source_position, "empty declaration");
4654 #ifdef RECORD_EMPTY_DECLARATIONS
4655 declaration_t *const declaration = allocate_declaration_zero();
4656 declaration->type = specifiers->type;
4657 declaration->declared_storage_class = specifiers->declared_storage_class;
4658 declaration->source_position = specifiers->source_position;
4659 declaration->modifiers = specifiers->modifiers;
4660 declaration->storage_class = STORAGE_CLASS_NONE;
4662 append_declaration(declaration);
4666 static void parse_declaration_rest(declaration_t *ndeclaration,
4667 const declaration_specifiers_t *specifiers,
4668 parsed_declaration_func finished_declaration)
4670 add_anchor_token(';');
4671 add_anchor_token(',');
4673 declaration_t *declaration =
4674 finished_declaration(ndeclaration, token.type == '=');
4676 type_t *orig_type = declaration->type;
4677 type_t *type = skip_typeref(orig_type);
4679 if (type->kind != TYPE_FUNCTION &&
4680 declaration->is_inline &&
4681 is_type_valid(type)) {
4682 warningf(&declaration->source_position,
4683 "variable '%Y' declared 'inline'\n", declaration->symbol);
4686 if (token.type == '=') {
4687 parse_init_declarator_rest(declaration);
4690 if (token.type != ',')
4694 add_anchor_token('=');
4695 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4696 rem_anchor_token('=');
4701 rem_anchor_token(';');
4702 rem_anchor_token(',');
4705 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4707 symbol_t *symbol = declaration->symbol;
4708 if (symbol == NULL) {
4709 errorf(HERE, "anonymous declaration not valid as function parameter");
4712 namespace_t namespc = (namespace_t) declaration->namespc;
4713 if (namespc != NAMESPACE_NORMAL) {
4714 return record_declaration(declaration, false);
4717 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4718 if (previous_declaration == NULL ||
4719 previous_declaration->parent_scope != scope) {
4720 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4725 if (is_definition) {
4726 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4729 if (previous_declaration->type == NULL) {
4730 previous_declaration->type = declaration->type;
4731 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4732 previous_declaration->storage_class = declaration->storage_class;
4733 previous_declaration->parent_scope = scope;
4734 return previous_declaration;
4736 return record_declaration(declaration, false);
4740 static void parse_declaration(parsed_declaration_func finished_declaration)
4742 declaration_specifiers_t specifiers;
4743 memset(&specifiers, 0, sizeof(specifiers));
4745 add_anchor_token(';');
4746 parse_declaration_specifiers(&specifiers);
4747 rem_anchor_token(';');
4749 if (token.type == ';') {
4750 parse_anonymous_declaration_rest(&specifiers);
4752 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4753 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4757 static type_t *get_default_promoted_type(type_t *orig_type)
4759 type_t *result = orig_type;
4761 type_t *type = skip_typeref(orig_type);
4762 if (is_type_integer(type)) {
4763 result = promote_integer(type);
4764 } else if (type == type_float) {
4765 result = type_double;
4771 static void parse_kr_declaration_list(declaration_t *declaration)
4773 type_t *type = skip_typeref(declaration->type);
4774 if (!is_type_function(type))
4777 if (!type->function.kr_style_parameters)
4780 add_anchor_token('{');
4782 /* push function parameters */
4783 size_t const top = environment_top();
4784 scope_push(&declaration->scope);
4786 declaration_t *parameter = declaration->scope.declarations;
4787 for ( ; parameter != NULL; parameter = parameter->next) {
4788 assert(parameter->parent_scope == NULL);
4789 parameter->parent_scope = scope;
4790 environment_push(parameter);
4793 /* parse declaration list */
4794 while (is_declaration_specifier(&token, false)) {
4795 parse_declaration(finished_kr_declaration);
4798 /* pop function parameters */
4799 assert(scope == &declaration->scope);
4801 environment_pop_to(top);
4803 /* update function type */
4804 type_t *new_type = duplicate_type(type);
4806 function_parameter_t *parameters = NULL;
4807 function_parameter_t *last_parameter = NULL;
4809 declaration_t *parameter_declaration = declaration->scope.declarations;
4810 for( ; parameter_declaration != NULL;
4811 parameter_declaration = parameter_declaration->next) {
4812 type_t *parameter_type = parameter_declaration->type;
4813 if (parameter_type == NULL) {
4815 errorf(HERE, "no type specified for function parameter '%Y'",
4816 parameter_declaration->symbol);
4818 if (warning.implicit_int) {
4819 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4820 parameter_declaration->symbol);
4822 parameter_type = type_int;
4823 parameter_declaration->type = parameter_type;
4827 semantic_parameter(parameter_declaration);
4828 parameter_type = parameter_declaration->type;
4831 * we need the default promoted types for the function type
4833 parameter_type = get_default_promoted_type(parameter_type);
4835 function_parameter_t *function_parameter
4836 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4837 memset(function_parameter, 0, sizeof(function_parameter[0]));
4839 function_parameter->type = parameter_type;
4840 if (last_parameter != NULL) {
4841 last_parameter->next = function_parameter;
4843 parameters = function_parameter;
4845 last_parameter = function_parameter;
4848 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4850 new_type->function.parameters = parameters;
4851 new_type->function.unspecified_parameters = true;
4853 type = typehash_insert(new_type);
4854 if (type != new_type) {
4855 obstack_free(type_obst, new_type);
4858 declaration->type = type;
4860 rem_anchor_token('{');
4863 static bool first_err = true;
4866 * When called with first_err set, prints the name of the current function,
4869 static void print_in_function(void)
4873 diagnosticf("%s: In function '%Y':\n",
4874 current_function->source_position.input_name,
4875 current_function->symbol);
4880 * Check if all labels are defined in the current function.
4881 * Check if all labels are used in the current function.
4883 static void check_labels(void)
4885 for (const goto_statement_t *goto_statement = goto_first;
4886 goto_statement != NULL;
4887 goto_statement = goto_statement->next) {
4888 /* skip computed gotos */
4889 if (goto_statement->expression != NULL)
4892 declaration_t *label = goto_statement->label;
4895 if (label->source_position.input_name == NULL) {
4896 print_in_function();
4897 errorf(&goto_statement->base.source_position,
4898 "label '%Y' used but not defined", label->symbol);
4901 goto_first = goto_last = NULL;
4903 if (warning.unused_label) {
4904 for (const label_statement_t *label_statement = label_first;
4905 label_statement != NULL;
4906 label_statement = label_statement->next) {
4907 const declaration_t *label = label_statement->label;
4909 if (! label->used) {
4910 print_in_function();
4911 warningf(&label_statement->base.source_position,
4912 "label '%Y' defined but not used", label->symbol);
4916 label_first = label_last = NULL;
4920 * Check declarations of current_function for unused entities.
4922 static void check_declarations(void)
4924 if (warning.unused_parameter) {
4925 const scope_t *scope = ¤t_function->scope;
4927 if (is_sym_main(current_function->symbol)) {
4928 /* do not issue unused warnings for main */
4931 const declaration_t *parameter = scope->declarations;
4932 for (; parameter != NULL; parameter = parameter->next) {
4933 if (! parameter->used) {
4934 print_in_function();
4935 warningf(¶meter->source_position,
4936 "unused parameter '%Y'", parameter->symbol);
4940 if (warning.unused_variable) {
4944 static int determine_truth(expression_t const* const cond)
4947 !is_constant_expression(cond) ? 0 :
4948 fold_constant(cond) != 0 ? 1 :
4952 static bool noreturn_candidate;
4954 static void check_reachable(statement_t *const stmt)
4956 if (stmt->base.reachable)
4958 if (stmt->kind != STATEMENT_DO_WHILE)
4959 stmt->base.reachable = true;
4961 statement_t *last = stmt;
4963 switch (stmt->kind) {
4964 case STATEMENT_INVALID:
4965 case STATEMENT_EMPTY:
4966 case STATEMENT_DECLARATION:
4968 next = stmt->base.next;
4971 case STATEMENT_COMPOUND:
4972 next = stmt->compound.statements;
4975 case STATEMENT_RETURN:
4976 noreturn_candidate = false;
4979 case STATEMENT_IF: {
4980 if_statement_t const* const ifs = &stmt->ifs;
4981 int const val = determine_truth(ifs->condition);
4984 check_reachable(ifs->true_statement);
4989 if (ifs->false_statement != NULL) {
4990 check_reachable(ifs->false_statement);
4994 next = stmt->base.next;
4998 case STATEMENT_SWITCH: {
4999 switch_statement_t const *const switchs = &stmt->switchs;
5000 expression_t const *const expr = switchs->expression;
5002 if (is_constant_expression(expr)) {
5003 long const val = fold_constant(expr);
5004 case_label_statement_t * defaults = NULL;
5005 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5006 if (i->expression == NULL) {
5011 if (i->first_case <= val && val <= i->last_case) {
5012 check_reachable((statement_t*)i);
5017 if (defaults != NULL) {
5018 check_reachable((statement_t*)defaults);
5022 bool has_default = false;
5023 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5024 if (i->expression == NULL)
5027 check_reachable((statement_t*)i);
5034 next = stmt->base.next;
5038 case STATEMENT_EXPRESSION: {
5039 /* Check for noreturn function call */
5040 expression_t const *const expr = stmt->expression.expression;
5041 if (expr->kind == EXPR_CALL) {
5042 expression_t const *const func = expr->call.function;
5043 if (func->kind == EXPR_REFERENCE) {
5044 declaration_t const *const decl = func->reference.declaration;
5045 if (decl != NULL && decl->modifiers & DM_NORETURN) {
5051 next = stmt->base.next;
5055 case STATEMENT_CONTINUE: {
5056 statement_t *parent = stmt;
5058 parent = parent->base.parent;
5059 if (parent == NULL) /* continue not within loop */
5063 switch (parent->kind) {
5064 case STATEMENT_WHILE: goto continue_while;
5065 case STATEMENT_DO_WHILE: goto continue_do_while;
5066 case STATEMENT_FOR: goto continue_for;
5073 case STATEMENT_BREAK: {
5074 statement_t *parent = stmt;
5076 parent = parent->base.parent;
5077 if (parent == NULL) /* break not within loop/switch */
5080 switch (parent->kind) {
5081 case STATEMENT_SWITCH:
5082 case STATEMENT_WHILE:
5083 case STATEMENT_DO_WHILE:
5086 next = parent->base.next;
5087 goto found_break_parent;
5096 case STATEMENT_GOTO:
5097 if (stmt->gotos.expression) {
5098 statement_t *parent = stmt->base.parent;
5099 if (parent == NULL) /* top level goto */
5103 next = stmt->gotos.label->init.statement;
5104 if (next == NULL) /* missing label */
5109 case STATEMENT_LABEL:
5110 next = stmt->label.statement;
5113 case STATEMENT_CASE_LABEL:
5114 next = stmt->case_label.statement;
5117 case STATEMENT_WHILE: {
5118 while_statement_t const *const whiles = &stmt->whiles;
5119 int const val = determine_truth(whiles->condition);
5122 check_reachable(whiles->body);
5127 next = stmt->base.next;
5131 case STATEMENT_DO_WHILE:
5132 next = stmt->do_while.body;
5135 case STATEMENT_FOR: {
5136 for_statement_t *const fors = &stmt->fors;
5138 if (fors->condition_reachable)
5140 fors->condition_reachable = true;
5142 expression_t const *const cond = fors->condition;
5144 cond == NULL ? 1 : determine_truth(cond);
5147 check_reachable(fors->body);
5152 next = stmt->base.next;
5156 case STATEMENT_MS_TRY: {
5157 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5158 check_reachable(ms_try->try_statement);
5159 next = ms_try->final_statement;
5163 case STATEMENT_LEAVE: {
5164 statement_t *parent = stmt;
5166 parent = parent->base.parent;
5167 if (parent == NULL) /* __leave not within __try */
5170 if (parent->kind == STATEMENT_MS_TRY) {
5172 next = parent->ms_try.final_statement;
5180 while (next == NULL) {
5181 next = last->base.parent;
5183 noreturn_candidate = false;
5185 type_t *const type = current_function->type;
5186 assert(is_type_function(type));
5187 type_t *const ret = skip_typeref(type->function.return_type);
5188 if (warning.return_type &&
5189 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5190 is_type_valid(ret) &&
5191 !is_sym_main(current_function->symbol)) {
5192 warningf(&stmt->base.source_position,
5193 "control reaches end of non-void function");
5198 switch (next->kind) {
5199 case STATEMENT_INVALID:
5200 case STATEMENT_EMPTY:
5201 case STATEMENT_DECLARATION:
5202 case STATEMENT_EXPRESSION:
5204 case STATEMENT_RETURN:
5205 case STATEMENT_CONTINUE:
5206 case STATEMENT_BREAK:
5207 case STATEMENT_GOTO:
5208 case STATEMENT_LEAVE:
5209 panic("invalid control flow in function");
5211 case STATEMENT_COMPOUND:
5213 case STATEMENT_SWITCH:
5214 case STATEMENT_LABEL:
5215 case STATEMENT_CASE_LABEL:
5217 next = next->base.next;
5220 case STATEMENT_WHILE: {
5222 if (next->base.reachable)
5224 next->base.reachable = true;
5226 while_statement_t const *const whiles = &next->whiles;
5227 int const val = determine_truth(whiles->condition);
5230 check_reachable(whiles->body);
5236 next = next->base.next;
5240 case STATEMENT_DO_WHILE: {
5242 if (next->base.reachable)
5244 next->base.reachable = true;
5246 do_while_statement_t const *const dw = &next->do_while;
5247 int const val = determine_truth(dw->condition);
5250 check_reachable(dw->body);
5256 next = next->base.next;
5260 case STATEMENT_FOR: {
5262 for_statement_t *const fors = &next->fors;
5264 fors->step_reachable = true;
5266 if (fors->condition_reachable)
5268 fors->condition_reachable = true;
5270 expression_t const *const cond = fors->condition;
5272 cond == NULL ? 1 : determine_truth(cond);
5275 check_reachable(fors->body);
5281 next = next->base.next;
5285 case STATEMENT_MS_TRY:
5287 next = next->ms_try.final_statement;
5293 next = stmt->base.parent;
5295 warningf(&stmt->base.source_position,
5296 "control reaches end of non-void function");
5300 check_reachable(next);
5303 static void check_unreachable(statement_t const* const stmt)
5305 if (!stmt->base.reachable &&
5306 stmt->kind != STATEMENT_DO_WHILE &&
5307 stmt->kind != STATEMENT_FOR &&
5308 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5309 warningf(&stmt->base.source_position, "statement is unreachable");
5312 switch (stmt->kind) {
5313 case STATEMENT_INVALID:
5314 case STATEMENT_EMPTY:
5315 case STATEMENT_RETURN:
5316 case STATEMENT_DECLARATION:
5317 case STATEMENT_EXPRESSION:
5318 case STATEMENT_CONTINUE:
5319 case STATEMENT_BREAK:
5320 case STATEMENT_GOTO:
5322 case STATEMENT_LEAVE:
5325 case STATEMENT_COMPOUND:
5326 if (stmt->compound.statements)
5327 check_unreachable(stmt->compound.statements);
5331 check_unreachable(stmt->ifs.true_statement);
5332 if (stmt->ifs.false_statement != NULL)
5333 check_unreachable(stmt->ifs.false_statement);
5336 case STATEMENT_SWITCH:
5337 check_unreachable(stmt->switchs.body);
5340 case STATEMENT_LABEL:
5341 check_unreachable(stmt->label.statement);
5344 case STATEMENT_CASE_LABEL:
5345 check_unreachable(stmt->case_label.statement);
5348 case STATEMENT_WHILE:
5349 check_unreachable(stmt->whiles.body);
5352 case STATEMENT_DO_WHILE:
5353 check_unreachable(stmt->do_while.body);
5354 if (!stmt->base.reachable) {
5355 expression_t const *const cond = stmt->do_while.condition;
5356 if (determine_truth(cond) >= 0) {
5357 warningf(&cond->base.source_position,
5358 "condition of do-while-loop is unreachable");
5363 case STATEMENT_FOR: {
5364 for_statement_t const* const fors = &stmt->fors;
5366 // if init and step are unreachable, cond is unreachable, too
5367 if (!stmt->base.reachable && !fors->step_reachable) {
5368 warningf(&stmt->base.source_position, "statement is unreachable");
5370 if (!stmt->base.reachable && fors->initialisation != NULL) {
5371 warningf(&fors->initialisation->base.source_position,
5372 "initialisation of for-statement is unreachable");
5375 if (!fors->condition_reachable && fors->condition != NULL) {
5376 warningf(&fors->condition->base.source_position,
5377 "condition of for-statement is unreachable");
5380 if (!fors->step_reachable && fors->step != NULL) {
5381 warningf(&fors->step->base.source_position,
5382 "step of for-statement is unreachable");
5386 check_unreachable(fors->body);
5390 case STATEMENT_MS_TRY: {
5391 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5392 check_unreachable(ms_try->try_statement);
5393 check_unreachable(ms_try->final_statement);
5397 if (stmt->base.next)
5398 check_unreachable(stmt->base.next);
5401 static void parse_external_declaration(void)
5403 /* function-definitions and declarations both start with declaration
5405 declaration_specifiers_t specifiers;
5406 memset(&specifiers, 0, sizeof(specifiers));
5408 add_anchor_token(';');
5409 parse_declaration_specifiers(&specifiers);
5410 rem_anchor_token(';');
5412 /* must be a declaration */
5413 if (token.type == ';') {
5414 parse_anonymous_declaration_rest(&specifiers);
5418 add_anchor_token(',');
5419 add_anchor_token('=');
5420 add_anchor_token(';');
5421 add_anchor_token('{');
5423 /* declarator is common to both function-definitions and declarations */
5424 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5426 rem_anchor_token('{');
5427 rem_anchor_token(';');
5428 rem_anchor_token('=');
5429 rem_anchor_token(',');
5431 /* must be a declaration */
5432 switch (token.type) {
5436 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5440 /* must be a function definition */
5441 parse_kr_declaration_list(ndeclaration);
5443 if (token.type != '{') {
5444 parse_error_expected("while parsing function definition", '{', NULL);
5445 eat_until_matching_token(';');
5449 type_t *type = ndeclaration->type;
5451 /* note that we don't skip typerefs: the standard doesn't allow them here
5452 * (so we can't use is_type_function here) */
5453 if (type->kind != TYPE_FUNCTION) {
5454 if (is_type_valid(type)) {
5455 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5456 type, ndeclaration->symbol);
5462 if (warning.aggregate_return &&
5463 is_type_compound(skip_typeref(type->function.return_type))) {
5464 warningf(HERE, "function '%Y' returns an aggregate",
5465 ndeclaration->symbol);
5467 if (warning.traditional && !type->function.unspecified_parameters) {
5468 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5469 ndeclaration->symbol);
5471 if (warning.old_style_definition && type->function.unspecified_parameters) {
5472 warningf(HERE, "old-style function definition '%Y'",
5473 ndeclaration->symbol);
5476 /* § 6.7.5.3 (14) a function definition with () means no
5477 * parameters (and not unspecified parameters) */
5478 if (type->function.unspecified_parameters
5479 && type->function.parameters == NULL
5480 && !type->function.kr_style_parameters) {
5481 type_t *duplicate = duplicate_type(type);
5482 duplicate->function.unspecified_parameters = false;
5484 type = typehash_insert(duplicate);
5485 if (type != duplicate) {
5486 obstack_free(type_obst, duplicate);
5488 ndeclaration->type = type;
5491 declaration_t *const declaration = record_declaration(ndeclaration, true);
5492 if (ndeclaration != declaration) {
5493 declaration->scope = ndeclaration->scope;
5495 type = skip_typeref(declaration->type);
5497 /* push function parameters and switch scope */
5498 size_t const top = environment_top();
5499 scope_push(&declaration->scope);
5501 declaration_t *parameter = declaration->scope.declarations;
5502 for( ; parameter != NULL; parameter = parameter->next) {
5503 if (parameter->parent_scope == &ndeclaration->scope) {
5504 parameter->parent_scope = scope;
5506 assert(parameter->parent_scope == NULL
5507 || parameter->parent_scope == scope);
5508 parameter->parent_scope = scope;
5509 if (parameter->symbol == NULL) {
5510 errorf(¶meter->source_position, "parameter name omitted");
5513 environment_push(parameter);
5516 if (declaration->init.statement != NULL) {
5517 parser_error_multiple_definition(declaration, HERE);
5520 /* parse function body */
5521 int label_stack_top = label_top();
5522 declaration_t *old_current_function = current_function;
5523 current_function = declaration;
5524 current_parent = NULL;
5526 statement_t *const body = parse_compound_statement(false);
5527 declaration->init.statement = body;
5530 check_declarations();
5531 if (warning.return_type ||
5532 warning.unreachable_code ||
5533 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5534 noreturn_candidate = true;
5535 check_reachable(body);
5536 if (warning.unreachable_code)
5537 check_unreachable(body);
5538 if (warning.missing_noreturn &&
5539 noreturn_candidate &&
5540 !(declaration->modifiers & DM_NORETURN)) {
5541 warningf(&body->base.source_position,
5542 "function '%#T' is candidate for attribute 'noreturn'",
5543 type, declaration->symbol);
5547 assert(current_parent == NULL);
5548 assert(current_function == declaration);
5549 current_function = old_current_function;
5550 label_pop_to(label_stack_top);
5553 assert(scope == &declaration->scope);
5555 environment_pop_to(top);
5558 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5559 source_position_t *source_position,
5560 const symbol_t *symbol)
5562 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5564 type->bitfield.base_type = base_type;
5565 type->bitfield.size_expression = size;
5568 type_t *skipped_type = skip_typeref(base_type);
5569 if (!is_type_integer(skipped_type)) {
5570 errorf(HERE, "bitfield base type '%T' is not an integer type",
5574 bit_size = skipped_type->base.size * 8;
5577 if (is_constant_expression(size)) {
5578 long v = fold_constant(size);
5581 errorf(source_position, "negative width in bit-field '%Y'",
5583 } else if (v == 0) {
5584 errorf(source_position, "zero width for bit-field '%Y'",
5586 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5587 errorf(source_position, "width of '%Y' exceeds its type",
5590 type->bitfield.bit_size = v;
5597 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5600 declaration_t *iter = compound_declaration->scope.declarations;
5601 for( ; iter != NULL; iter = iter->next) {
5602 if (iter->namespc != NAMESPACE_NORMAL)
5605 if (iter->symbol == NULL) {
5606 type_t *type = skip_typeref(iter->type);
5607 if (is_type_compound(type)) {
5608 declaration_t *result
5609 = find_compound_entry(type->compound.declaration, symbol);
5616 if (iter->symbol == symbol) {
5624 static void parse_compound_declarators(declaration_t *struct_declaration,
5625 const declaration_specifiers_t *specifiers)
5627 declaration_t *last_declaration = struct_declaration->scope.declarations;
5628 if (last_declaration != NULL) {
5629 while (last_declaration->next != NULL) {
5630 last_declaration = last_declaration->next;
5635 declaration_t *declaration;
5637 if (token.type == ':') {
5638 source_position_t source_position = *HERE;
5641 type_t *base_type = specifiers->type;
5642 expression_t *size = parse_constant_expression();
5644 type_t *type = make_bitfield_type(base_type, size,
5645 &source_position, sym_anonymous);
5647 declaration = allocate_declaration_zero();
5648 declaration->namespc = NAMESPACE_NORMAL;
5649 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5650 declaration->storage_class = STORAGE_CLASS_NONE;
5651 declaration->source_position = source_position;
5652 declaration->modifiers = specifiers->modifiers;
5653 declaration->type = type;
5655 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5657 type_t *orig_type = declaration->type;
5658 type_t *type = skip_typeref(orig_type);
5660 if (token.type == ':') {
5661 source_position_t source_position = *HERE;
5663 expression_t *size = parse_constant_expression();
5665 type_t *bitfield_type = make_bitfield_type(orig_type, size,
5666 &source_position, declaration->symbol);
5667 declaration->type = bitfield_type;
5669 /* TODO we ignore arrays for now... what is missing is a check
5670 * that they're at the end of the struct */
5671 if (is_type_incomplete(type) && !is_type_array(type)) {
5673 "compound member '%Y' has incomplete type '%T'",
5674 declaration->symbol, orig_type);
5675 } else if (is_type_function(type)) {
5676 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5677 declaration->symbol, orig_type);
5682 /* make sure we don't define a symbol multiple times */
5683 symbol_t *symbol = declaration->symbol;
5684 if (symbol != NULL) {
5685 declaration_t *prev_decl
5686 = find_compound_entry(struct_declaration, symbol);
5688 if (prev_decl != NULL) {
5689 assert(prev_decl->symbol == symbol);
5690 errorf(&declaration->source_position,
5691 "multiple declarations of symbol '%Y' (declared %P)",
5692 symbol, &prev_decl->source_position);
5696 /* append declaration */
5697 if (last_declaration != NULL) {
5698 last_declaration->next = declaration;
5700 struct_declaration->scope.declarations = declaration;
5702 last_declaration = declaration;
5704 if (token.type != ',')
5714 static void parse_compound_type_entries(declaration_t *compound_declaration)
5717 add_anchor_token('}');
5719 while (token.type != '}') {
5720 if (token.type == T_EOF) {
5721 errorf(HERE, "EOF while parsing struct");
5724 declaration_specifiers_t specifiers;
5725 memset(&specifiers, 0, sizeof(specifiers));
5726 parse_declaration_specifiers(&specifiers);
5728 parse_compound_declarators(compound_declaration, &specifiers);
5730 rem_anchor_token('}');
5734 static type_t *parse_typename(void)
5736 declaration_specifiers_t specifiers;
5737 memset(&specifiers, 0, sizeof(specifiers));
5738 parse_declaration_specifiers(&specifiers);
5739 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5740 /* TODO: improve error message, user does probably not know what a
5741 * storage class is...
5743 errorf(HERE, "typename may not have a storage class");
5746 type_t *result = parse_abstract_declarator(specifiers.type);
5754 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5755 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5756 expression_t *left);
5758 typedef struct expression_parser_function_t expression_parser_function_t;
5759 struct expression_parser_function_t {
5760 unsigned precedence;
5761 parse_expression_function parser;
5762 unsigned infix_precedence;
5763 parse_expression_infix_function infix_parser;
5766 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5769 * Prints an error message if an expression was expected but not read
5771 static expression_t *expected_expression_error(void)
5773 /* skip the error message if the error token was read */
5774 if (token.type != T_ERROR) {
5775 errorf(HERE, "expected expression, got token '%K'", &token);
5779 return create_invalid_expression();
5783 * Parse a string constant.
5785 static expression_t *parse_string_const(void)
5788 if (token.type == T_STRING_LITERAL) {
5789 string_t res = token.v.string;
5791 while (token.type == T_STRING_LITERAL) {
5792 res = concat_strings(&res, &token.v.string);
5795 if (token.type != T_WIDE_STRING_LITERAL) {
5796 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5797 /* note: that we use type_char_ptr here, which is already the
5798 * automatic converted type. revert_automatic_type_conversion
5799 * will construct the array type */
5800 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5801 cnst->string.value = res;
5805 wres = concat_string_wide_string(&res, &token.v.wide_string);
5807 wres = token.v.wide_string;
5812 switch (token.type) {
5813 case T_WIDE_STRING_LITERAL:
5814 wres = concat_wide_strings(&wres, &token.v.wide_string);
5817 case T_STRING_LITERAL:
5818 wres = concat_wide_string_string(&wres, &token.v.string);
5822 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5823 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5824 cnst->wide_string.value = wres;
5833 * Parse an integer constant.
5835 static expression_t *parse_int_const(void)
5837 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5838 cnst->base.source_position = *HERE;
5839 cnst->base.type = token.datatype;
5840 cnst->conste.v.int_value = token.v.intvalue;
5848 * Parse a character constant.
5850 static expression_t *parse_character_constant(void)
5852 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5854 cnst->base.source_position = *HERE;
5855 cnst->base.type = token.datatype;
5856 cnst->conste.v.character = token.v.string;
5858 if (cnst->conste.v.character.size != 1) {
5859 if (warning.multichar && GNU_MODE) {
5860 warningf(HERE, "multi-character character constant");
5862 errorf(HERE, "more than 1 characters in character constant");
5871 * Parse a wide character constant.
5873 static expression_t *parse_wide_character_constant(void)
5875 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5877 cnst->base.source_position = *HERE;
5878 cnst->base.type = token.datatype;
5879 cnst->conste.v.wide_character = token.v.wide_string;
5881 if (cnst->conste.v.wide_character.size != 1) {
5882 if (warning.multichar && GNU_MODE) {
5883 warningf(HERE, "multi-character character constant");
5885 errorf(HERE, "more than 1 characters in character constant");
5894 * Parse a float constant.
5896 static expression_t *parse_float_const(void)
5898 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5899 cnst->base.type = token.datatype;
5900 cnst->conste.v.float_value = token.v.floatvalue;
5907 static declaration_t *create_implicit_function(symbol_t *symbol,
5908 const source_position_t *source_position)
5910 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5911 ntype->function.return_type = type_int;
5912 ntype->function.unspecified_parameters = true;
5914 type_t *type = typehash_insert(ntype);
5915 if (type != ntype) {
5919 declaration_t *const declaration = allocate_declaration_zero();
5920 declaration->storage_class = STORAGE_CLASS_EXTERN;
5921 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5922 declaration->type = type;
5923 declaration->symbol = symbol;
5924 declaration->source_position = *source_position;
5925 declaration->implicit = true;
5927 bool strict_prototypes_old = warning.strict_prototypes;
5928 warning.strict_prototypes = false;
5929 record_declaration(declaration, false);
5930 warning.strict_prototypes = strict_prototypes_old;
5936 * Creates a return_type (func)(argument_type) function type if not
5939 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5940 type_t *argument_type2)
5942 function_parameter_t *parameter2
5943 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5944 memset(parameter2, 0, sizeof(parameter2[0]));
5945 parameter2->type = argument_type2;
5947 function_parameter_t *parameter1
5948 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5949 memset(parameter1, 0, sizeof(parameter1[0]));
5950 parameter1->type = argument_type1;
5951 parameter1->next = parameter2;
5953 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5954 type->function.return_type = return_type;
5955 type->function.parameters = parameter1;
5957 type_t *result = typehash_insert(type);
5958 if (result != type) {
5966 * Creates a return_type (func)(argument_type) function type if not
5969 * @param return_type the return type
5970 * @param argument_type the argument type
5972 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5974 function_parameter_t *parameter
5975 = obstack_alloc(type_obst, sizeof(parameter[0]));
5976 memset(parameter, 0, sizeof(parameter[0]));
5977 parameter->type = argument_type;
5979 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5980 type->function.return_type = return_type;
5981 type->function.parameters = parameter;
5983 type_t *result = typehash_insert(type);
5984 if (result != type) {
5991 static type_t *make_function_0_type(type_t *return_type)
5993 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5994 type->function.return_type = return_type;
5995 type->function.parameters = NULL;
5997 type_t *result = typehash_insert(type);
5998 if (result != type) {
6006 * Creates a function type for some function like builtins.
6008 * @param symbol the symbol describing the builtin
6010 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6012 switch(symbol->ID) {
6013 case T___builtin_alloca:
6014 return make_function_1_type(type_void_ptr, type_size_t);
6015 case T___builtin_huge_val:
6016 return make_function_0_type(type_double);
6017 case T___builtin_inf:
6018 return make_function_0_type(type_double);
6019 case T___builtin_inff:
6020 return make_function_0_type(type_float);
6021 case T___builtin_infl:
6022 return make_function_0_type(type_long_double);
6023 case T___builtin_nan:
6024 return make_function_1_type(type_double, type_char_ptr);
6025 case T___builtin_nanf:
6026 return make_function_1_type(type_float, type_char_ptr);
6027 case T___builtin_nanl:
6028 return make_function_1_type(type_long_double, type_char_ptr);
6029 case T___builtin_va_end:
6030 return make_function_1_type(type_void, type_valist);
6031 case T___builtin_expect:
6032 return make_function_2_type(type_long, type_long, type_long);
6034 internal_errorf(HERE, "not implemented builtin symbol found");
6039 * Performs automatic type cast as described in § 6.3.2.1.
6041 * @param orig_type the original type
6043 static type_t *automatic_type_conversion(type_t *orig_type)
6045 type_t *type = skip_typeref(orig_type);
6046 if (is_type_array(type)) {
6047 array_type_t *array_type = &type->array;
6048 type_t *element_type = array_type->element_type;
6049 unsigned qualifiers = array_type->base.qualifiers;
6051 return make_pointer_type(element_type, qualifiers);
6054 if (is_type_function(type)) {
6055 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6062 * reverts the automatic casts of array to pointer types and function
6063 * to function-pointer types as defined § 6.3.2.1
6065 type_t *revert_automatic_type_conversion(const expression_t *expression)
6067 switch (expression->kind) {
6068 case EXPR_REFERENCE: return expression->reference.declaration->type;
6071 return get_qualified_type(expression->select.compound_entry->type,
6072 expression->base.type->base.qualifiers);
6074 case EXPR_UNARY_DEREFERENCE: {
6075 const expression_t *const value = expression->unary.value;
6076 type_t *const type = skip_typeref(value->base.type);
6077 assert(is_type_pointer(type));
6078 return type->pointer.points_to;
6081 case EXPR_BUILTIN_SYMBOL:
6082 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6084 case EXPR_ARRAY_ACCESS: {
6085 const expression_t *array_ref = expression->array_access.array_ref;
6086 type_t *type_left = skip_typeref(array_ref->base.type);
6087 if (!is_type_valid(type_left))
6089 assert(is_type_pointer(type_left));
6090 return type_left->pointer.points_to;
6093 case EXPR_STRING_LITERAL: {
6094 size_t size = expression->string.value.size;
6095 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6098 case EXPR_WIDE_STRING_LITERAL: {
6099 size_t size = expression->wide_string.value.size;
6100 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6103 case EXPR_COMPOUND_LITERAL:
6104 return expression->compound_literal.type;
6109 return expression->base.type;
6112 static expression_t *parse_reference(void)
6114 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6116 reference_expression_t *ref = &expression->reference;
6117 symbol_t *const symbol = token.v.symbol;
6119 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6121 if (declaration == NULL) {
6122 if (!strict_mode && look_ahead(1)->type == '(') {
6123 /* an implicitly declared function */
6124 if (warning.implicit_function_declaration) {
6125 warningf(HERE, "implicit declaration of function '%Y'",
6129 declaration = create_implicit_function(symbol, HERE);
6131 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6132 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6136 type_t *orig_type = declaration->type;
6138 /* we always do the auto-type conversions; the & and sizeof parser contains
6139 * code to revert this! */
6140 type_t *type = automatic_type_conversion(orig_type);
6142 ref->declaration = declaration;
6143 ref->base.type = type;
6145 /* this declaration is used */
6146 declaration->used = true;
6148 if (declaration->parent_scope != file_scope &&
6149 declaration->parent_scope->depth < current_function->scope.depth &&
6150 is_type_valid(orig_type) && !is_type_function(orig_type)) {
6151 /* access of a variable from an outer function */
6152 declaration->address_taken = true;
6153 ref->is_outer_ref = true;
6154 current_function->need_closure = true;
6157 /* check for deprecated functions */
6158 if (warning.deprecated_declarations &&
6159 declaration->modifiers & DM_DEPRECATED) {
6160 char const *const prefix = is_type_function(declaration->type) ?
6161 "function" : "variable";
6163 if (declaration->deprecated_string != NULL) {
6164 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6165 prefix, declaration->symbol, &declaration->source_position,
6166 declaration->deprecated_string);
6168 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6169 declaration->symbol, &declaration->source_position);
6172 if (warning.init_self && declaration == current_init_decl && !in_type_prop) {
6173 current_init_decl = NULL;
6174 warningf(HERE, "variable '%#T' is initialized by itself",
6175 declaration->type, declaration->symbol);
6182 static bool semantic_cast(expression_t *cast)
6184 expression_t *expression = cast->unary.value;
6185 type_t *orig_dest_type = cast->base.type;
6186 type_t *orig_type_right = expression->base.type;
6187 type_t const *dst_type = skip_typeref(orig_dest_type);
6188 type_t const *src_type = skip_typeref(orig_type_right);
6189 source_position_t const *pos = &cast->base.source_position;
6191 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6192 if (dst_type == type_void)
6195 /* only integer and pointer can be casted to pointer */
6196 if (is_type_pointer(dst_type) &&
6197 !is_type_pointer(src_type) &&
6198 !is_type_integer(src_type) &&
6199 is_type_valid(src_type)) {
6200 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6204 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6205 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6209 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6210 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6214 if (warning.cast_qual &&
6215 is_type_pointer(src_type) &&
6216 is_type_pointer(dst_type)) {
6217 type_t *src = skip_typeref(src_type->pointer.points_to);
6218 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6219 unsigned missing_qualifiers =
6220 src->base.qualifiers & ~dst->base.qualifiers;
6221 if (missing_qualifiers != 0) {
6223 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6224 missing_qualifiers, orig_type_right);
6230 static expression_t *parse_compound_literal(type_t *type)
6232 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6234 parse_initializer_env_t env;
6236 env.declaration = NULL;
6237 env.must_be_constant = false;
6238 initializer_t *initializer = parse_initializer(&env);
6241 expression->compound_literal.initializer = initializer;
6242 expression->compound_literal.type = type;
6243 expression->base.type = automatic_type_conversion(type);
6249 * Parse a cast expression.
6251 static expression_t *parse_cast(void)
6253 add_anchor_token(')');
6255 source_position_t source_position = token.source_position;
6257 type_t *type = parse_typename();
6259 rem_anchor_token(')');
6262 if (token.type == '{') {
6263 return parse_compound_literal(type);
6266 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6267 cast->base.source_position = source_position;
6269 expression_t *value = parse_sub_expression(20);
6270 cast->base.type = type;
6271 cast->unary.value = value;
6273 if (! semantic_cast(cast)) {
6274 /* TODO: record the error in the AST. else it is impossible to detect it */
6279 return create_invalid_expression();
6283 * Parse a statement expression.
6285 static expression_t *parse_statement_expression(void)
6287 add_anchor_token(')');
6289 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6291 statement_t *statement = parse_compound_statement(true);
6292 expression->statement.statement = statement;
6293 expression->base.source_position = statement->base.source_position;
6295 /* find last statement and use its type */
6296 type_t *type = type_void;
6297 const statement_t *stmt = statement->compound.statements;
6299 while (stmt->base.next != NULL)
6300 stmt = stmt->base.next;
6302 if (stmt->kind == STATEMENT_EXPRESSION) {
6303 type = stmt->expression.expression->base.type;
6306 warningf(&expression->base.source_position, "empty statement expression ({})");
6308 expression->base.type = type;
6310 rem_anchor_token(')');
6318 * Parse a parenthesized expression.
6320 static expression_t *parse_parenthesized_expression(void)
6324 switch(token.type) {
6326 /* gcc extension: a statement expression */
6327 return parse_statement_expression();
6331 return parse_cast();
6333 if (is_typedef_symbol(token.v.symbol)) {
6334 return parse_cast();
6338 add_anchor_token(')');
6339 expression_t *result = parse_expression();
6340 rem_anchor_token(')');
6347 static expression_t *parse_function_keyword(void)
6352 if (current_function == NULL) {
6353 errorf(HERE, "'__func__' used outside of a function");
6356 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6357 expression->base.type = type_char_ptr;
6358 expression->funcname.kind = FUNCNAME_FUNCTION;
6363 static expression_t *parse_pretty_function_keyword(void)
6365 eat(T___PRETTY_FUNCTION__);
6367 if (current_function == NULL) {
6368 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6371 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6372 expression->base.type = type_char_ptr;
6373 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6378 static expression_t *parse_funcsig_keyword(void)
6382 if (current_function == NULL) {
6383 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6386 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6387 expression->base.type = type_char_ptr;
6388 expression->funcname.kind = FUNCNAME_FUNCSIG;
6393 static expression_t *parse_funcdname_keyword(void)
6395 eat(T___FUNCDNAME__);
6397 if (current_function == NULL) {
6398 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6401 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6402 expression->base.type = type_char_ptr;
6403 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6408 static designator_t *parse_designator(void)
6410 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6411 result->source_position = *HERE;
6413 if (token.type != T_IDENTIFIER) {
6414 parse_error_expected("while parsing member designator",
6415 T_IDENTIFIER, NULL);
6418 result->symbol = token.v.symbol;
6421 designator_t *last_designator = result;
6423 if (token.type == '.') {
6425 if (token.type != T_IDENTIFIER) {
6426 parse_error_expected("while parsing member designator",
6427 T_IDENTIFIER, NULL);
6430 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6431 designator->source_position = *HERE;
6432 designator->symbol = token.v.symbol;
6435 last_designator->next = designator;
6436 last_designator = designator;
6439 if (token.type == '[') {
6441 add_anchor_token(']');
6442 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6443 designator->source_position = *HERE;
6444 designator->array_index = parse_expression();
6445 rem_anchor_token(']');
6447 if (designator->array_index == NULL) {
6451 last_designator->next = designator;
6452 last_designator = designator;
6464 * Parse the __builtin_offsetof() expression.
6466 static expression_t *parse_offsetof(void)
6468 eat(T___builtin_offsetof);
6470 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6471 expression->base.type = type_size_t;
6474 add_anchor_token(',');
6475 type_t *type = parse_typename();
6476 rem_anchor_token(',');
6478 add_anchor_token(')');
6479 designator_t *designator = parse_designator();
6480 rem_anchor_token(')');
6483 expression->offsetofe.type = type;
6484 expression->offsetofe.designator = designator;
6487 memset(&path, 0, sizeof(path));
6488 path.top_type = type;
6489 path.path = NEW_ARR_F(type_path_entry_t, 0);
6491 descend_into_subtype(&path);
6493 if (!walk_designator(&path, designator, true)) {
6494 return create_invalid_expression();
6497 DEL_ARR_F(path.path);
6501 return create_invalid_expression();
6505 * Parses a _builtin_va_start() expression.
6507 static expression_t *parse_va_start(void)
6509 eat(T___builtin_va_start);
6511 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6514 add_anchor_token(',');
6515 expression->va_starte.ap = parse_assignment_expression();
6516 rem_anchor_token(',');
6518 expression_t *const expr = parse_assignment_expression();
6519 if (expr->kind == EXPR_REFERENCE) {
6520 declaration_t *const decl = expr->reference.declaration;
6521 if (decl->parent_scope != ¤t_function->scope || decl->next != NULL) {
6522 errorf(&expr->base.source_position,
6523 "second argument of 'va_start' must be last parameter of the current function");
6525 expression->va_starte.parameter = decl;
6531 return create_invalid_expression();
6535 * Parses a _builtin_va_arg() expression.
6537 static expression_t *parse_va_arg(void)
6539 eat(T___builtin_va_arg);
6541 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6544 expression->va_arge.ap = parse_assignment_expression();
6546 expression->base.type = parse_typename();
6551 return create_invalid_expression();
6554 static expression_t *parse_builtin_symbol(void)
6556 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6558 symbol_t *symbol = token.v.symbol;
6560 expression->builtin_symbol.symbol = symbol;
6563 type_t *type = get_builtin_symbol_type(symbol);
6564 type = automatic_type_conversion(type);
6566 expression->base.type = type;
6571 * Parses a __builtin_constant() expression.
6573 static expression_t *parse_builtin_constant(void)
6575 eat(T___builtin_constant_p);
6577 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6580 add_anchor_token(')');
6581 expression->builtin_constant.value = parse_assignment_expression();
6582 rem_anchor_token(')');
6584 expression->base.type = type_int;
6588 return create_invalid_expression();
6592 * Parses a __builtin_prefetch() expression.
6594 static expression_t *parse_builtin_prefetch(void)
6596 eat(T___builtin_prefetch);
6598 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6601 add_anchor_token(')');
6602 expression->builtin_prefetch.adr = parse_assignment_expression();
6603 if (token.type == ',') {
6605 expression->builtin_prefetch.rw = parse_assignment_expression();
6607 if (token.type == ',') {
6609 expression->builtin_prefetch.locality = parse_assignment_expression();
6611 rem_anchor_token(')');
6613 expression->base.type = type_void;
6617 return create_invalid_expression();
6621 * Parses a __builtin_is_*() compare expression.
6623 static expression_t *parse_compare_builtin(void)
6625 expression_t *expression;
6627 switch(token.type) {
6628 case T___builtin_isgreater:
6629 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6631 case T___builtin_isgreaterequal:
6632 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6634 case T___builtin_isless:
6635 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6637 case T___builtin_islessequal:
6638 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6640 case T___builtin_islessgreater:
6641 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6643 case T___builtin_isunordered:
6644 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6647 internal_errorf(HERE, "invalid compare builtin found");
6649 expression->base.source_position = *HERE;
6653 expression->binary.left = parse_assignment_expression();
6655 expression->binary.right = parse_assignment_expression();
6658 type_t *const orig_type_left = expression->binary.left->base.type;
6659 type_t *const orig_type_right = expression->binary.right->base.type;
6661 type_t *const type_left = skip_typeref(orig_type_left);
6662 type_t *const type_right = skip_typeref(orig_type_right);
6663 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6664 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6665 type_error_incompatible("invalid operands in comparison",
6666 &expression->base.source_position, orig_type_left, orig_type_right);
6669 semantic_comparison(&expression->binary);
6674 return create_invalid_expression();
6679 * Parses a __builtin_expect() expression.
6681 static expression_t *parse_builtin_expect(void)
6683 eat(T___builtin_expect);
6685 expression_t *expression
6686 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6689 expression->binary.left = parse_assignment_expression();
6691 expression->binary.right = parse_constant_expression();
6694 expression->base.type = expression->binary.left->base.type;
6698 return create_invalid_expression();
6703 * Parses a MS assume() expression.
6705 static expression_t *parse_assume(void)
6709 expression_t *expression
6710 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6713 add_anchor_token(')');
6714 expression->unary.value = parse_assignment_expression();
6715 rem_anchor_token(')');
6718 expression->base.type = type_void;
6721 return create_invalid_expression();
6725 * Return the declaration for a given label symbol or create a new one.
6727 * @param symbol the symbol of the label
6729 static declaration_t *get_label(symbol_t *symbol)
6731 declaration_t *candidate;
6732 assert(current_function != NULL);
6734 candidate = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
6735 /* if we found a local label, we already created the declaration */
6736 if (candidate != NULL) {
6737 if (candidate->parent_scope != scope) {
6738 assert(candidate->parent_scope->depth < scope->depth);
6739 current_function->goto_to_outer = true;
6744 candidate = get_declaration(symbol, NAMESPACE_LABEL);
6745 /* if we found a label in the same function, then we already created the
6747 if (candidate != NULL
6748 && candidate->parent_scope == ¤t_function->scope) {
6752 /* otherwise we need to create a new one */
6753 declaration_t *const declaration = allocate_declaration_zero();
6754 declaration->namespc = NAMESPACE_LABEL;
6755 declaration->symbol = symbol;
6757 label_push(declaration);
6763 * Parses a GNU && label address expression.
6765 static expression_t *parse_label_address(void)
6767 source_position_t source_position = token.source_position;
6769 if (token.type != T_IDENTIFIER) {
6770 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6773 symbol_t *symbol = token.v.symbol;
6776 declaration_t *label = get_label(symbol);
6779 label->address_taken = true;
6781 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6782 expression->base.source_position = source_position;
6784 /* label address is threaten as a void pointer */
6785 expression->base.type = type_void_ptr;
6786 expression->label_address.declaration = label;
6789 return create_invalid_expression();
6793 * Parse a microsoft __noop expression.
6795 static expression_t *parse_noop_expression(void)
6797 source_position_t source_position = *HERE;
6800 if (token.type == '(') {
6801 /* parse arguments */
6803 add_anchor_token(')');
6804 add_anchor_token(',');
6806 if (token.type != ')') {
6808 (void)parse_assignment_expression();
6809 if (token.type != ',')
6815 rem_anchor_token(',');
6816 rem_anchor_token(')');
6819 /* the result is a (int)0 */
6820 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6821 cnst->base.source_position = source_position;
6822 cnst->base.type = type_int;
6823 cnst->conste.v.int_value = 0;
6824 cnst->conste.is_ms_noop = true;
6829 return create_invalid_expression();
6833 * Parses a primary expression.
6835 static expression_t *parse_primary_expression(void)
6837 switch (token.type) {
6838 case T_INTEGER: return parse_int_const();
6839 case T_CHARACTER_CONSTANT: return parse_character_constant();
6840 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6841 case T_FLOATINGPOINT: return parse_float_const();
6842 case T_STRING_LITERAL:
6843 case T_WIDE_STRING_LITERAL: return parse_string_const();
6844 case T_IDENTIFIER: return parse_reference();
6845 case T___FUNCTION__:
6846 case T___func__: return parse_function_keyword();
6847 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6848 case T___FUNCSIG__: return parse_funcsig_keyword();
6849 case T___FUNCDNAME__: return parse_funcdname_keyword();
6850 case T___builtin_offsetof: return parse_offsetof();
6851 case T___builtin_va_start: return parse_va_start();
6852 case T___builtin_va_arg: return parse_va_arg();
6853 case T___builtin_expect:
6854 case T___builtin_alloca:
6855 case T___builtin_inf:
6856 case T___builtin_inff:
6857 case T___builtin_infl:
6858 case T___builtin_nan:
6859 case T___builtin_nanf:
6860 case T___builtin_nanl:
6861 case T___builtin_huge_val:
6862 case T___builtin_va_end: return parse_builtin_symbol();
6863 case T___builtin_isgreater:
6864 case T___builtin_isgreaterequal:
6865 case T___builtin_isless:
6866 case T___builtin_islessequal:
6867 case T___builtin_islessgreater:
6868 case T___builtin_isunordered: return parse_compare_builtin();
6869 case T___builtin_constant_p: return parse_builtin_constant();
6870 case T___builtin_prefetch: return parse_builtin_prefetch();
6871 case T__assume: return parse_assume();
6874 return parse_label_address();
6877 case '(': return parse_parenthesized_expression();
6878 case T___noop: return parse_noop_expression();
6881 errorf(HERE, "unexpected token %K, expected an expression", &token);
6882 return create_invalid_expression();
6886 * Check if the expression has the character type and issue a warning then.
6888 static void check_for_char_index_type(const expression_t *expression)
6890 type_t *const type = expression->base.type;
6891 const type_t *const base_type = skip_typeref(type);
6893 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6894 warning.char_subscripts) {
6895 warningf(&expression->base.source_position,
6896 "array subscript has type '%T'", type);
6900 static expression_t *parse_array_expression(unsigned precedence,
6906 add_anchor_token(']');
6908 expression_t *inside = parse_expression();
6910 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6912 array_access_expression_t *array_access = &expression->array_access;
6914 type_t *const orig_type_left = left->base.type;
6915 type_t *const orig_type_inside = inside->base.type;
6917 type_t *const type_left = skip_typeref(orig_type_left);
6918 type_t *const type_inside = skip_typeref(orig_type_inside);
6920 type_t *return_type;
6921 if (is_type_pointer(type_left)) {
6922 return_type = type_left->pointer.points_to;
6923 array_access->array_ref = left;
6924 array_access->index = inside;
6925 check_for_char_index_type(inside);
6926 } else if (is_type_pointer(type_inside)) {
6927 return_type = type_inside->pointer.points_to;
6928 array_access->array_ref = inside;
6929 array_access->index = left;
6930 array_access->flipped = true;
6931 check_for_char_index_type(left);
6933 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6935 "array access on object with non-pointer types '%T', '%T'",
6936 orig_type_left, orig_type_inside);
6938 return_type = type_error_type;
6939 array_access->array_ref = left;
6940 array_access->index = inside;
6943 expression->base.type = automatic_type_conversion(return_type);
6945 rem_anchor_token(']');
6946 if (token.type == ']') {
6949 parse_error_expected("Problem while parsing array access", ']', NULL);
6954 static expression_t *parse_typeprop(expression_kind_t const kind,
6955 source_position_t const pos,
6956 unsigned const precedence)
6958 expression_t *tp_expression = allocate_expression_zero(kind);
6959 tp_expression->base.type = type_size_t;
6960 tp_expression->base.source_position = pos;
6962 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6964 /* we only refer to a type property, mark this case */
6965 bool old = in_type_prop;
6966 in_type_prop = true;
6967 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6969 add_anchor_token(')');
6970 type_t* const orig_type = parse_typename();
6971 tp_expression->typeprop.type = orig_type;
6973 type_t const* const type = skip_typeref(orig_type);
6974 char const* const wrong_type =
6975 is_type_incomplete(type) ? "incomplete" :
6976 type->kind == TYPE_FUNCTION ? "function designator" :
6977 type->kind == TYPE_BITFIELD ? "bitfield" :
6979 if (wrong_type != NULL) {
6980 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6981 what, wrong_type, type);
6984 rem_anchor_token(')');
6987 expression_t *expression = parse_sub_expression(precedence);
6989 type_t* const orig_type = revert_automatic_type_conversion(expression);
6990 expression->base.type = orig_type;
6992 type_t const* const type = skip_typeref(orig_type);
6993 char const* const wrong_type =
6994 is_type_incomplete(type) ? "incomplete" :
6995 type->kind == TYPE_FUNCTION ? "function designator" :
6996 type->kind == TYPE_BITFIELD ? "bitfield" :
6998 if (wrong_type != NULL) {
6999 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
7002 tp_expression->typeprop.type = expression->base.type;
7003 tp_expression->typeprop.tp_expression = expression;
7008 return tp_expression;
7011 static expression_t *parse_sizeof(unsigned precedence)
7013 source_position_t pos = *HERE;
7015 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
7018 static expression_t *parse_alignof(unsigned precedence)
7020 source_position_t pos = *HERE;
7022 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
7025 static expression_t *parse_select_expression(unsigned precedence,
7026 expression_t *compound)
7029 assert(token.type == '.' || token.type == T_MINUSGREATER);
7031 bool is_pointer = (token.type == T_MINUSGREATER);
7034 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7035 select->select.compound = compound;
7037 if (token.type != T_IDENTIFIER) {
7038 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7041 symbol_t *symbol = token.v.symbol;
7044 type_t *const orig_type = compound->base.type;
7045 type_t *const type = skip_typeref(orig_type);
7048 bool saw_error = false;
7049 if (is_type_pointer(type)) {
7052 "request for member '%Y' in something not a struct or union, but '%T'",
7056 type_left = skip_typeref(type->pointer.points_to);
7058 if (is_pointer && is_type_valid(type)) {
7059 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7065 declaration_t *entry;
7066 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7067 type_left->kind == TYPE_COMPOUND_UNION) {
7068 declaration_t *const declaration = type_left->compound.declaration;
7070 if (!declaration->init.complete) {
7071 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7073 goto create_error_entry;
7076 entry = find_compound_entry(declaration, symbol);
7077 if (entry == NULL) {
7078 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7079 goto create_error_entry;
7082 if (is_type_valid(type_left) && !saw_error) {
7084 "request for member '%Y' in something not a struct or union, but '%T'",
7088 entry = allocate_declaration_zero();
7089 entry->symbol = symbol;
7092 select->select.compound_entry = entry;
7094 type_t *const res_type =
7095 get_qualified_type(entry->type, type_left->base.qualifiers);
7097 /* we always do the auto-type conversions; the & and sizeof parser contains
7098 * code to revert this! */
7099 select->base.type = automatic_type_conversion(res_type);
7101 type_t *skipped = skip_typeref(res_type);
7102 if (skipped->kind == TYPE_BITFIELD) {
7103 select->base.type = skipped->bitfield.base_type;
7109 static void check_call_argument(const function_parameter_t *parameter,
7110 call_argument_t *argument, unsigned pos)
7112 type_t *expected_type = parameter->type;
7113 type_t *expected_type_skip = skip_typeref(expected_type);
7114 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7115 expression_t *arg_expr = argument->expression;
7116 type_t *arg_type = skip_typeref(arg_expr->base.type);
7118 /* handle transparent union gnu extension */
7119 if (is_type_union(expected_type_skip)
7120 && (expected_type_skip->base.modifiers
7121 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7122 declaration_t *union_decl = expected_type_skip->compound.declaration;
7124 declaration_t *declaration = union_decl->scope.declarations;
7125 type_t *best_type = NULL;
7126 for ( ; declaration != NULL; declaration = declaration->next) {
7127 type_t *decl_type = declaration->type;
7128 error = semantic_assign(decl_type, arg_expr);
7129 if (error == ASSIGN_ERROR_INCOMPATIBLE
7130 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7133 if (error == ASSIGN_SUCCESS) {
7134 best_type = decl_type;
7135 } else if (best_type == NULL) {
7136 best_type = decl_type;
7140 if (best_type != NULL) {
7141 expected_type = best_type;
7145 error = semantic_assign(expected_type, arg_expr);
7146 argument->expression = create_implicit_cast(argument->expression,
7149 if (error != ASSIGN_SUCCESS) {
7150 /* report exact scope in error messages (like "in argument 3") */
7152 snprintf(buf, sizeof(buf), "call argument %u", pos);
7153 report_assign_error(error, expected_type, arg_expr, buf,
7154 &arg_expr->base.source_position);
7155 } else if (warning.traditional || warning.conversion) {
7156 type_t *const promoted_type = get_default_promoted_type(arg_type);
7157 if (!types_compatible(expected_type_skip, promoted_type) &&
7158 !types_compatible(expected_type_skip, type_void_ptr) &&
7159 !types_compatible(type_void_ptr, promoted_type)) {
7160 /* Deliberately show the skipped types in this warning */
7161 warningf(&arg_expr->base.source_position,
7162 "passing call argument %u as '%T' rather than '%T' due to prototype",
7163 pos, expected_type_skip, promoted_type);
7169 * Parse a call expression, ie. expression '( ... )'.
7171 * @param expression the function address
7173 static expression_t *parse_call_expression(unsigned precedence,
7174 expression_t *expression)
7177 expression_t *result = allocate_expression_zero(EXPR_CALL);
7178 result->base.source_position = expression->base.source_position;
7180 call_expression_t *call = &result->call;
7181 call->function = expression;
7183 type_t *const orig_type = expression->base.type;
7184 type_t *const type = skip_typeref(orig_type);
7186 function_type_t *function_type = NULL;
7187 if (is_type_pointer(type)) {
7188 type_t *const to_type = skip_typeref(type->pointer.points_to);
7190 if (is_type_function(to_type)) {
7191 function_type = &to_type->function;
7192 call->base.type = function_type->return_type;
7196 if (function_type == NULL && is_type_valid(type)) {
7197 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7200 /* parse arguments */
7202 add_anchor_token(')');
7203 add_anchor_token(',');
7205 if (token.type != ')') {
7206 call_argument_t *last_argument = NULL;
7209 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7211 argument->expression = parse_assignment_expression();
7212 if (last_argument == NULL) {
7213 call->arguments = argument;
7215 last_argument->next = argument;
7217 last_argument = argument;
7219 if (token.type != ',')
7224 rem_anchor_token(',');
7225 rem_anchor_token(')');
7228 if (function_type == NULL)
7231 function_parameter_t *parameter = function_type->parameters;
7232 call_argument_t *argument = call->arguments;
7233 if (!function_type->unspecified_parameters) {
7234 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7235 parameter = parameter->next, argument = argument->next) {
7236 check_call_argument(parameter, argument, ++pos);
7239 if (parameter != NULL) {
7240 errorf(HERE, "too few arguments to function '%E'", expression);
7241 } else if (argument != NULL && !function_type->variadic) {
7242 errorf(HERE, "too many arguments to function '%E'", expression);
7246 /* do default promotion */
7247 for( ; argument != NULL; argument = argument->next) {
7248 type_t *type = argument->expression->base.type;
7250 type = get_default_promoted_type(type);
7252 argument->expression
7253 = create_implicit_cast(argument->expression, type);
7256 check_format(&result->call);
7258 if (warning.aggregate_return &&
7259 is_type_compound(skip_typeref(function_type->return_type))) {
7260 warningf(&result->base.source_position,
7261 "function call has aggregate value");
7268 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7270 static bool same_compound_type(const type_t *type1, const type_t *type2)
7273 is_type_compound(type1) &&
7274 type1->kind == type2->kind &&
7275 type1->compound.declaration == type2->compound.declaration;
7279 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7281 * @param expression the conditional expression
7283 static expression_t *parse_conditional_expression(unsigned precedence,
7284 expression_t *expression)
7286 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7288 conditional_expression_t *conditional = &result->conditional;
7289 conditional->base.source_position = *HERE;
7290 conditional->condition = expression;
7293 add_anchor_token(':');
7296 type_t *const condition_type_orig = expression->base.type;
7297 type_t *const condition_type = skip_typeref(condition_type_orig);
7298 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7299 type_error("expected a scalar type in conditional condition",
7300 &expression->base.source_position, condition_type_orig);
7303 expression_t *true_expression = expression;
7304 bool gnu_cond = false;
7305 if (GNU_MODE && token.type == ':') {
7308 true_expression = parse_expression();
7309 rem_anchor_token(':');
7311 expression_t *false_expression = parse_sub_expression(precedence);
7313 type_t *const orig_true_type = true_expression->base.type;
7314 type_t *const orig_false_type = false_expression->base.type;
7315 type_t *const true_type = skip_typeref(orig_true_type);
7316 type_t *const false_type = skip_typeref(orig_false_type);
7319 type_t *result_type;
7320 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7321 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7322 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7323 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7324 warningf(&conditional->base.source_position,
7325 "ISO C forbids conditional expression with only one void side");
7327 result_type = type_void;
7328 } else if (is_type_arithmetic(true_type)
7329 && is_type_arithmetic(false_type)) {
7330 result_type = semantic_arithmetic(true_type, false_type);
7332 true_expression = create_implicit_cast(true_expression, result_type);
7333 false_expression = create_implicit_cast(false_expression, result_type);
7335 conditional->true_expression = true_expression;
7336 conditional->false_expression = false_expression;
7337 conditional->base.type = result_type;
7338 } else if (same_compound_type(true_type, false_type)) {
7339 /* just take 1 of the 2 types */
7340 result_type = true_type;
7341 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7342 type_t *pointer_type;
7344 expression_t *other_expression;
7345 if (is_type_pointer(true_type) &&
7346 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7347 pointer_type = true_type;
7348 other_type = false_type;
7349 other_expression = false_expression;
7351 pointer_type = false_type;
7352 other_type = true_type;
7353 other_expression = true_expression;
7356 if (is_null_pointer_constant(other_expression)) {
7357 result_type = pointer_type;
7358 } else if (is_type_pointer(other_type)) {
7359 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7360 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7363 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7364 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7366 } else if (types_compatible(get_unqualified_type(to1),
7367 get_unqualified_type(to2))) {
7370 warningf(&conditional->base.source_position,
7371 "pointer types '%T' and '%T' in conditional expression are incompatible",
7372 true_type, false_type);
7376 type_t *const type =
7377 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7378 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7379 } else if (is_type_integer(other_type)) {
7380 warningf(&conditional->base.source_position,
7381 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7382 result_type = pointer_type;
7384 if (is_type_valid(other_type)) {
7385 type_error_incompatible("while parsing conditional",
7386 &expression->base.source_position, true_type, false_type);
7388 result_type = type_error_type;
7391 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7392 type_error_incompatible("while parsing conditional",
7393 &conditional->base.source_position, true_type,
7396 result_type = type_error_type;
7399 conditional->true_expression
7400 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7401 conditional->false_expression
7402 = create_implicit_cast(false_expression, result_type);
7403 conditional->base.type = result_type;
7406 return create_invalid_expression();
7410 * Parse an extension expression.
7412 static expression_t *parse_extension(unsigned precedence)
7414 eat(T___extension__);
7416 bool old_gcc_extension = in_gcc_extension;
7417 in_gcc_extension = true;
7418 expression_t *expression = parse_sub_expression(precedence);
7419 in_gcc_extension = old_gcc_extension;
7424 * Parse a __builtin_classify_type() expression.
7426 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7428 eat(T___builtin_classify_type);
7430 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7431 result->base.type = type_int;
7434 add_anchor_token(')');
7435 expression_t *expression = parse_sub_expression(precedence);
7436 rem_anchor_token(')');
7438 result->classify_type.type_expression = expression;
7442 return create_invalid_expression();
7445 static bool check_pointer_arithmetic(const source_position_t *source_position,
7446 type_t *pointer_type,
7447 type_t *orig_pointer_type)
7449 type_t *points_to = pointer_type->pointer.points_to;
7450 points_to = skip_typeref(points_to);
7452 if (is_type_incomplete(points_to)) {
7453 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7454 errorf(source_position,
7455 "arithmetic with pointer to incomplete type '%T' not allowed",
7458 } else if (warning.pointer_arith) {
7459 warningf(source_position,
7460 "pointer of type '%T' used in arithmetic",
7463 } else if (is_type_function(points_to)) {
7465 errorf(source_position,
7466 "arithmetic with pointer to function type '%T' not allowed",
7469 } else if (warning.pointer_arith) {
7470 warningf(source_position,
7471 "pointer to a function '%T' used in arithmetic",
7478 static bool is_lvalue(const expression_t *expression)
7480 switch (expression->kind) {
7481 case EXPR_REFERENCE:
7482 case EXPR_ARRAY_ACCESS:
7484 case EXPR_UNARY_DEREFERENCE:
7488 /* Claim it is an lvalue, if the type is invalid. There was a parse
7489 * error before, which maybe prevented properly recognizing it as
7491 return !is_type_valid(skip_typeref(expression->base.type));
7495 static void semantic_incdec(unary_expression_t *expression)
7497 type_t *const orig_type = expression->value->base.type;
7498 type_t *const type = skip_typeref(orig_type);
7499 if (is_type_pointer(type)) {
7500 if (!check_pointer_arithmetic(&expression->base.source_position,
7504 } else if (!is_type_real(type) && is_type_valid(type)) {
7505 /* TODO: improve error message */
7506 errorf(&expression->base.source_position,
7507 "operation needs an arithmetic or pointer type");
7510 if (!is_lvalue(expression->value)) {
7511 /* TODO: improve error message */
7512 errorf(&expression->base.source_position, "lvalue required as operand");
7514 expression->base.type = orig_type;
7517 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7519 type_t *const orig_type = expression->value->base.type;
7520 type_t *const type = skip_typeref(orig_type);
7521 if (!is_type_arithmetic(type)) {
7522 if (is_type_valid(type)) {
7523 /* TODO: improve error message */
7524 errorf(&expression->base.source_position,
7525 "operation needs an arithmetic type");
7530 expression->base.type = orig_type;
7533 static void semantic_unexpr_plus(unary_expression_t *expression)
7535 semantic_unexpr_arithmetic(expression);
7536 if (warning.traditional)
7537 warningf(&expression->base.source_position,
7538 "traditional C rejects the unary plus operator");
7541 static expression_t const *get_reference_address(expression_t const *expr)
7543 bool regular_take_address = true;
7545 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7546 expr = expr->unary.value;
7548 regular_take_address = false;
7551 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7554 expr = expr->unary.value;
7557 if (expr->kind != EXPR_REFERENCE)
7560 if (!regular_take_address &&
7561 !is_type_function(skip_typeref(expr->reference.declaration->type))) {
7568 static void warn_function_address_as_bool(expression_t const* expr)
7570 if (!warning.address)
7573 expr = get_reference_address(expr);
7575 warningf(&expr->base.source_position,
7576 "the address of '%Y' will always evaluate as 'true'",
7577 expr->reference.declaration->symbol);
7581 static void semantic_not(unary_expression_t *expression)
7583 type_t *const orig_type = expression->value->base.type;
7584 type_t *const type = skip_typeref(orig_type);
7585 if (!is_type_scalar(type) && is_type_valid(type)) {
7586 errorf(&expression->base.source_position,
7587 "operand of ! must be of scalar type");
7590 warn_function_address_as_bool(expression->value);
7592 expression->base.type = type_int;
7595 static void semantic_unexpr_integer(unary_expression_t *expression)
7597 type_t *const orig_type = expression->value->base.type;
7598 type_t *const type = skip_typeref(orig_type);
7599 if (!is_type_integer(type)) {
7600 if (is_type_valid(type)) {
7601 errorf(&expression->base.source_position,
7602 "operand of ~ must be of integer type");
7607 expression->base.type = orig_type;
7610 static void semantic_dereference(unary_expression_t *expression)
7612 type_t *const orig_type = expression->value->base.type;
7613 type_t *const type = skip_typeref(orig_type);
7614 if (!is_type_pointer(type)) {
7615 if (is_type_valid(type)) {
7616 errorf(&expression->base.source_position,
7617 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7622 type_t *result_type = type->pointer.points_to;
7623 result_type = automatic_type_conversion(result_type);
7624 expression->base.type = result_type;
7628 * Record that an address is taken (expression represents an lvalue).
7630 * @param expression the expression
7631 * @param may_be_register if true, the expression might be an register
7633 static void set_address_taken(expression_t *expression, bool may_be_register)
7635 if (expression->kind != EXPR_REFERENCE)
7638 declaration_t *const declaration = expression->reference.declaration;
7639 /* happens for parse errors */
7640 if (declaration == NULL)
7643 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7644 errorf(&expression->base.source_position,
7645 "address of register variable '%Y' requested",
7646 declaration->symbol);
7648 declaration->address_taken = 1;
7653 * Check the semantic of the address taken expression.
7655 static void semantic_take_addr(unary_expression_t *expression)
7657 expression_t *value = expression->value;
7658 value->base.type = revert_automatic_type_conversion(value);
7660 type_t *orig_type = value->base.type;
7661 if (!is_type_valid(skip_typeref(orig_type)))
7664 set_address_taken(value, false);
7666 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7669 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7670 static expression_t *parse_##unexpression_type(unsigned precedence) \
7672 expression_t *unary_expression \
7673 = allocate_expression_zero(unexpression_type); \
7674 unary_expression->base.source_position = *HERE; \
7676 unary_expression->unary.value = parse_sub_expression(precedence); \
7678 sfunc(&unary_expression->unary); \
7680 return unary_expression; \
7683 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7684 semantic_unexpr_arithmetic)
7685 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7686 semantic_unexpr_plus)
7687 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7689 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7690 semantic_dereference)
7691 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7693 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7694 semantic_unexpr_integer)
7695 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7697 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7700 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7702 static expression_t *parse_##unexpression_type(unsigned precedence, \
7703 expression_t *left) \
7705 (void) precedence; \
7707 expression_t *unary_expression \
7708 = allocate_expression_zero(unexpression_type); \
7709 unary_expression->base.source_position = *HERE; \
7711 unary_expression->unary.value = left; \
7713 sfunc(&unary_expression->unary); \
7715 return unary_expression; \
7718 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7719 EXPR_UNARY_POSTFIX_INCREMENT,
7721 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7722 EXPR_UNARY_POSTFIX_DECREMENT,
7725 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7727 /* TODO: handle complex + imaginary types */
7729 type_left = get_unqualified_type(type_left);
7730 type_right = get_unqualified_type(type_right);
7732 /* § 6.3.1.8 Usual arithmetic conversions */
7733 if (type_left == type_long_double || type_right == type_long_double) {
7734 return type_long_double;
7735 } else if (type_left == type_double || type_right == type_double) {
7737 } else if (type_left == type_float || type_right == type_float) {
7741 type_left = promote_integer(type_left);
7742 type_right = promote_integer(type_right);
7744 if (type_left == type_right)
7747 bool const signed_left = is_type_signed(type_left);
7748 bool const signed_right = is_type_signed(type_right);
7749 int const rank_left = get_rank(type_left);
7750 int const rank_right = get_rank(type_right);
7752 if (signed_left == signed_right)
7753 return rank_left >= rank_right ? type_left : type_right;
7762 u_rank = rank_right;
7763 u_type = type_right;
7765 s_rank = rank_right;
7766 s_type = type_right;
7771 if (u_rank >= s_rank)
7774 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7776 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7777 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7781 case ATOMIC_TYPE_INT: return type_unsigned_int;
7782 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7783 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7785 default: panic("invalid atomic type");
7790 * Check the semantic restrictions for a binary expression.
7792 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7794 expression_t *const left = expression->left;
7795 expression_t *const right = expression->right;
7796 type_t *const orig_type_left = left->base.type;
7797 type_t *const orig_type_right = right->base.type;
7798 type_t *const type_left = skip_typeref(orig_type_left);
7799 type_t *const type_right = skip_typeref(orig_type_right);
7801 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7802 /* TODO: improve error message */
7803 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7804 errorf(&expression->base.source_position,
7805 "operation needs arithmetic types");
7810 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7811 expression->left = create_implicit_cast(left, arithmetic_type);
7812 expression->right = create_implicit_cast(right, arithmetic_type);
7813 expression->base.type = arithmetic_type;
7816 static void warn_div_by_zero(binary_expression_t const *const expression)
7818 if (!warning.div_by_zero ||
7819 !is_type_integer(expression->base.type))
7822 expression_t const *const right = expression->right;
7823 /* The type of the right operand can be different for /= */
7824 if (is_type_integer(right->base.type) &&
7825 is_constant_expression(right) &&
7826 fold_constant(right) == 0) {
7827 warningf(&expression->base.source_position, "division by zero");
7832 * Check the semantic restrictions for a div/mod expression.
7834 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7835 semantic_binexpr_arithmetic(expression);
7836 warn_div_by_zero(expression);
7839 static void semantic_shift_op(binary_expression_t *expression)
7841 expression_t *const left = expression->left;
7842 expression_t *const right = expression->right;
7843 type_t *const orig_type_left = left->base.type;
7844 type_t *const orig_type_right = right->base.type;
7845 type_t * type_left = skip_typeref(orig_type_left);
7846 type_t * type_right = skip_typeref(orig_type_right);
7848 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7849 /* TODO: improve error message */
7850 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7851 errorf(&expression->base.source_position,
7852 "operands of shift operation must have integer types");
7857 type_left = promote_integer(type_left);
7858 type_right = promote_integer(type_right);
7860 expression->left = create_implicit_cast(left, type_left);
7861 expression->right = create_implicit_cast(right, type_right);
7862 expression->base.type = type_left;
7865 static void semantic_add(binary_expression_t *expression)
7867 expression_t *const left = expression->left;
7868 expression_t *const right = expression->right;
7869 type_t *const orig_type_left = left->base.type;
7870 type_t *const orig_type_right = right->base.type;
7871 type_t *const type_left = skip_typeref(orig_type_left);
7872 type_t *const type_right = skip_typeref(orig_type_right);
7875 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7876 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7877 expression->left = create_implicit_cast(left, arithmetic_type);
7878 expression->right = create_implicit_cast(right, arithmetic_type);
7879 expression->base.type = arithmetic_type;
7881 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7882 check_pointer_arithmetic(&expression->base.source_position,
7883 type_left, orig_type_left);
7884 expression->base.type = type_left;
7885 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7886 check_pointer_arithmetic(&expression->base.source_position,
7887 type_right, orig_type_right);
7888 expression->base.type = type_right;
7889 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7890 errorf(&expression->base.source_position,
7891 "invalid operands to binary + ('%T', '%T')",
7892 orig_type_left, orig_type_right);
7896 static void semantic_sub(binary_expression_t *expression)
7898 expression_t *const left = expression->left;
7899 expression_t *const right = expression->right;
7900 type_t *const orig_type_left = left->base.type;
7901 type_t *const orig_type_right = right->base.type;
7902 type_t *const type_left = skip_typeref(orig_type_left);
7903 type_t *const type_right = skip_typeref(orig_type_right);
7904 source_position_t const *const pos = &expression->base.source_position;
7907 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7908 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7909 expression->left = create_implicit_cast(left, arithmetic_type);
7910 expression->right = create_implicit_cast(right, arithmetic_type);
7911 expression->base.type = arithmetic_type;
7913 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7914 check_pointer_arithmetic(&expression->base.source_position,
7915 type_left, orig_type_left);
7916 expression->base.type = type_left;
7917 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7918 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7919 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7920 if (!types_compatible(unqual_left, unqual_right)) {
7922 "subtracting pointers to incompatible types '%T' and '%T'",
7923 orig_type_left, orig_type_right);
7924 } else if (!is_type_object(unqual_left)) {
7925 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7926 warningf(pos, "subtracting pointers to void");
7928 errorf(pos, "subtracting pointers to non-object types '%T'",
7932 expression->base.type = type_ptrdiff_t;
7933 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7934 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7935 orig_type_left, orig_type_right);
7939 static void warn_string_literal_address(expression_t const* expr)
7941 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7942 expr = expr->unary.value;
7943 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7945 expr = expr->unary.value;
7948 if (expr->kind == EXPR_STRING_LITERAL ||
7949 expr->kind == EXPR_WIDE_STRING_LITERAL) {
7950 warningf(&expr->base.source_position,
7951 "comparison with string literal results in unspecified behaviour");
7956 * Check the semantics of comparison expressions.
7958 * @param expression The expression to check.
7960 static void semantic_comparison(binary_expression_t *expression)
7962 expression_t *left = expression->left;
7963 expression_t *right = expression->right;
7965 if (warning.address) {
7966 warn_string_literal_address(left);
7967 warn_string_literal_address(right);
7969 expression_t const* const func_left = get_reference_address(left);
7970 if (func_left != NULL && is_null_pointer_constant(right)) {
7971 warningf(&expression->base.source_position,
7972 "the address of '%Y' will never be NULL",
7973 func_left->reference.declaration->symbol);
7976 expression_t const* const func_right = get_reference_address(right);
7977 if (func_right != NULL && is_null_pointer_constant(right)) {
7978 warningf(&expression->base.source_position,
7979 "the address of '%Y' will never be NULL",
7980 func_right->reference.declaration->symbol);
7984 type_t *orig_type_left = left->base.type;
7985 type_t *orig_type_right = right->base.type;
7986 type_t *type_left = skip_typeref(orig_type_left);
7987 type_t *type_right = skip_typeref(orig_type_right);
7989 /* TODO non-arithmetic types */
7990 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7991 /* test for signed vs unsigned compares */
7992 if (warning.sign_compare &&
7993 (expression->base.kind != EXPR_BINARY_EQUAL &&
7994 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7995 (is_type_signed(type_left) != is_type_signed(type_right))) {
7997 /* check if 1 of the operands is a constant, in this case we just
7998 * check wether we can safely represent the resulting constant in
7999 * the type of the other operand. */
8000 expression_t *const_expr = NULL;
8001 expression_t *other_expr = NULL;
8003 if (is_constant_expression(left)) {
8006 } else if (is_constant_expression(right)) {
8011 if (const_expr != NULL) {
8012 type_t *other_type = skip_typeref(other_expr->base.type);
8013 long val = fold_constant(const_expr);
8014 /* TODO: check if val can be represented by other_type */
8018 warningf(&expression->base.source_position,
8019 "comparison between signed and unsigned");
8021 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8022 expression->left = create_implicit_cast(left, arithmetic_type);
8023 expression->right = create_implicit_cast(right, arithmetic_type);
8024 expression->base.type = arithmetic_type;
8025 if (warning.float_equal &&
8026 (expression->base.kind == EXPR_BINARY_EQUAL ||
8027 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8028 is_type_float(arithmetic_type)) {
8029 warningf(&expression->base.source_position,
8030 "comparing floating point with == or != is unsafe");
8032 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8033 /* TODO check compatibility */
8034 } else if (is_type_pointer(type_left)) {
8035 expression->right = create_implicit_cast(right, type_left);
8036 } else if (is_type_pointer(type_right)) {
8037 expression->left = create_implicit_cast(left, type_right);
8038 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8039 type_error_incompatible("invalid operands in comparison",
8040 &expression->base.source_position,
8041 type_left, type_right);
8043 expression->base.type = type_int;
8047 * Checks if a compound type has constant fields.
8049 static bool has_const_fields(const compound_type_t *type)
8051 const scope_t *scope = &type->declaration->scope;
8052 const declaration_t *declaration = scope->declarations;
8054 for (; declaration != NULL; declaration = declaration->next) {
8055 if (declaration->namespc != NAMESPACE_NORMAL)
8058 const type_t *decl_type = skip_typeref(declaration->type);
8059 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8066 static bool is_valid_assignment_lhs(expression_t const* const left)
8068 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8069 type_t *const type_left = skip_typeref(orig_type_left);
8071 if (!is_lvalue(left)) {
8072 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8077 if (is_type_array(type_left)) {
8078 errorf(HERE, "cannot assign to arrays ('%E')", left);
8081 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8082 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8086 if (is_type_incomplete(type_left)) {
8087 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8088 left, orig_type_left);
8091 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8092 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8093 left, orig_type_left);
8100 static void semantic_arithmetic_assign(binary_expression_t *expression)
8102 expression_t *left = expression->left;
8103 expression_t *right = expression->right;
8104 type_t *orig_type_left = left->base.type;
8105 type_t *orig_type_right = right->base.type;
8107 if (!is_valid_assignment_lhs(left))
8110 type_t *type_left = skip_typeref(orig_type_left);
8111 type_t *type_right = skip_typeref(orig_type_right);
8113 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8114 /* TODO: improve error message */
8115 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8116 errorf(&expression->base.source_position,
8117 "operation needs arithmetic types");
8122 /* combined instructions are tricky. We can't create an implicit cast on
8123 * the left side, because we need the uncasted form for the store.
8124 * The ast2firm pass has to know that left_type must be right_type
8125 * for the arithmetic operation and create a cast by itself */
8126 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8127 expression->right = create_implicit_cast(right, arithmetic_type);
8128 expression->base.type = type_left;
8131 static void semantic_divmod_assign(binary_expression_t *expression)
8133 semantic_arithmetic_assign(expression);
8134 warn_div_by_zero(expression);
8137 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8139 expression_t *const left = expression->left;
8140 expression_t *const right = expression->right;
8141 type_t *const orig_type_left = left->base.type;
8142 type_t *const orig_type_right = right->base.type;
8143 type_t *const type_left = skip_typeref(orig_type_left);
8144 type_t *const type_right = skip_typeref(orig_type_right);
8146 if (!is_valid_assignment_lhs(left))
8149 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8150 /* combined instructions are tricky. We can't create an implicit cast on
8151 * the left side, because we need the uncasted form for the store.
8152 * The ast2firm pass has to know that left_type must be right_type
8153 * for the arithmetic operation and create a cast by itself */
8154 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8155 expression->right = create_implicit_cast(right, arithmetic_type);
8156 expression->base.type = type_left;
8157 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8158 check_pointer_arithmetic(&expression->base.source_position,
8159 type_left, orig_type_left);
8160 expression->base.type = type_left;
8161 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8162 errorf(&expression->base.source_position,
8163 "incompatible types '%T' and '%T' in assignment",
8164 orig_type_left, orig_type_right);
8169 * Check the semantic restrictions of a logical expression.
8171 static void semantic_logical_op(binary_expression_t *expression)
8173 expression_t *const left = expression->left;
8174 expression_t *const right = expression->right;
8175 type_t *const orig_type_left = left->base.type;
8176 type_t *const orig_type_right = right->base.type;
8177 type_t *const type_left = skip_typeref(orig_type_left);
8178 type_t *const type_right = skip_typeref(orig_type_right);
8180 warn_function_address_as_bool(left);
8181 warn_function_address_as_bool(right);
8183 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8184 /* TODO: improve error message */
8185 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8186 errorf(&expression->base.source_position,
8187 "operation needs scalar types");
8192 expression->base.type = type_int;
8196 * Check the semantic restrictions of a binary assign expression.
8198 static void semantic_binexpr_assign(binary_expression_t *expression)
8200 expression_t *left = expression->left;
8201 type_t *orig_type_left = left->base.type;
8203 if (!is_valid_assignment_lhs(left))
8206 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8207 report_assign_error(error, orig_type_left, expression->right,
8208 "assignment", &left->base.source_position);
8209 expression->right = create_implicit_cast(expression->right, orig_type_left);
8210 expression->base.type = orig_type_left;
8214 * Determine if the outermost operation (or parts thereof) of the given
8215 * expression has no effect in order to generate a warning about this fact.
8216 * Therefore in some cases this only examines some of the operands of the
8217 * expression (see comments in the function and examples below).
8219 * f() + 23; // warning, because + has no effect
8220 * x || f(); // no warning, because x controls execution of f()
8221 * x ? y : f(); // warning, because y has no effect
8222 * (void)x; // no warning to be able to suppress the warning
8223 * This function can NOT be used for an "expression has definitely no effect"-
8225 static bool expression_has_effect(const expression_t *const expr)
8227 switch (expr->kind) {
8228 case EXPR_UNKNOWN: break;
8229 case EXPR_INVALID: return true; /* do NOT warn */
8230 case EXPR_REFERENCE: return false;
8231 /* suppress the warning for microsoft __noop operations */
8232 case EXPR_CONST: return expr->conste.is_ms_noop;
8233 case EXPR_CHARACTER_CONSTANT: return false;
8234 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8235 case EXPR_STRING_LITERAL: return false;
8236 case EXPR_WIDE_STRING_LITERAL: return false;
8237 case EXPR_LABEL_ADDRESS: return false;
8240 const call_expression_t *const call = &expr->call;
8241 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8244 switch (call->function->builtin_symbol.symbol->ID) {
8245 case T___builtin_va_end: return true;
8246 default: return false;
8250 /* Generate the warning if either the left or right hand side of a
8251 * conditional expression has no effect */
8252 case EXPR_CONDITIONAL: {
8253 const conditional_expression_t *const cond = &expr->conditional;
8255 expression_has_effect(cond->true_expression) &&
8256 expression_has_effect(cond->false_expression);
8259 case EXPR_SELECT: return false;
8260 case EXPR_ARRAY_ACCESS: return false;
8261 case EXPR_SIZEOF: return false;
8262 case EXPR_CLASSIFY_TYPE: return false;
8263 case EXPR_ALIGNOF: return false;
8265 case EXPR_FUNCNAME: return false;
8266 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8267 case EXPR_BUILTIN_CONSTANT_P: return false;
8268 case EXPR_BUILTIN_PREFETCH: return true;
8269 case EXPR_OFFSETOF: return false;
8270 case EXPR_VA_START: return true;
8271 case EXPR_VA_ARG: return true;
8272 case EXPR_STATEMENT: return true; // TODO
8273 case EXPR_COMPOUND_LITERAL: return false;
8275 case EXPR_UNARY_NEGATE: return false;
8276 case EXPR_UNARY_PLUS: return false;
8277 case EXPR_UNARY_BITWISE_NEGATE: return false;
8278 case EXPR_UNARY_NOT: return false;
8279 case EXPR_UNARY_DEREFERENCE: return false;
8280 case EXPR_UNARY_TAKE_ADDRESS: return false;
8281 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8282 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8283 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8284 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8286 /* Treat void casts as if they have an effect in order to being able to
8287 * suppress the warning */
8288 case EXPR_UNARY_CAST: {
8289 type_t *const type = skip_typeref(expr->base.type);
8290 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8293 case EXPR_UNARY_CAST_IMPLICIT: return true;
8294 case EXPR_UNARY_ASSUME: return true;
8296 case EXPR_BINARY_ADD: return false;
8297 case EXPR_BINARY_SUB: return false;
8298 case EXPR_BINARY_MUL: return false;
8299 case EXPR_BINARY_DIV: return false;
8300 case EXPR_BINARY_MOD: return false;
8301 case EXPR_BINARY_EQUAL: return false;
8302 case EXPR_BINARY_NOTEQUAL: return false;
8303 case EXPR_BINARY_LESS: return false;
8304 case EXPR_BINARY_LESSEQUAL: return false;
8305 case EXPR_BINARY_GREATER: return false;
8306 case EXPR_BINARY_GREATEREQUAL: return false;
8307 case EXPR_BINARY_BITWISE_AND: return false;
8308 case EXPR_BINARY_BITWISE_OR: return false;
8309 case EXPR_BINARY_BITWISE_XOR: return false;
8310 case EXPR_BINARY_SHIFTLEFT: return false;
8311 case EXPR_BINARY_SHIFTRIGHT: return false;
8312 case EXPR_BINARY_ASSIGN: return true;
8313 case EXPR_BINARY_MUL_ASSIGN: return true;
8314 case EXPR_BINARY_DIV_ASSIGN: return true;
8315 case EXPR_BINARY_MOD_ASSIGN: return true;
8316 case EXPR_BINARY_ADD_ASSIGN: return true;
8317 case EXPR_BINARY_SUB_ASSIGN: return true;
8318 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8319 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8320 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8321 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8322 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8324 /* Only examine the right hand side of && and ||, because the left hand
8325 * side already has the effect of controlling the execution of the right
8327 case EXPR_BINARY_LOGICAL_AND:
8328 case EXPR_BINARY_LOGICAL_OR:
8329 /* Only examine the right hand side of a comma expression, because the left
8330 * hand side has a separate warning */
8331 case EXPR_BINARY_COMMA:
8332 return expression_has_effect(expr->binary.right);
8334 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8335 case EXPR_BINARY_ISGREATER: return false;
8336 case EXPR_BINARY_ISGREATEREQUAL: return false;
8337 case EXPR_BINARY_ISLESS: return false;
8338 case EXPR_BINARY_ISLESSEQUAL: return false;
8339 case EXPR_BINARY_ISLESSGREATER: return false;
8340 case EXPR_BINARY_ISUNORDERED: return false;
8343 internal_errorf(HERE, "unexpected expression");
8346 static void semantic_comma(binary_expression_t *expression)
8348 if (warning.unused_value) {
8349 const expression_t *const left = expression->left;
8350 if (!expression_has_effect(left)) {
8351 warningf(&left->base.source_position,
8352 "left-hand operand of comma expression has no effect");
8355 expression->base.type = expression->right->base.type;
8358 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8359 static expression_t *parse_##binexpression_type(unsigned precedence, \
8360 expression_t *left) \
8362 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8363 binexpr->base.source_position = *HERE; \
8364 binexpr->binary.left = left; \
8367 expression_t *right = parse_sub_expression(precedence + lr); \
8369 binexpr->binary.right = right; \
8370 sfunc(&binexpr->binary); \
8375 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8376 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8377 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8378 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8379 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8380 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8381 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8382 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8383 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8385 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8386 semantic_comparison, 1)
8387 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8388 semantic_comparison, 1)
8389 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8390 semantic_comparison, 1)
8391 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8392 semantic_comparison, 1)
8394 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8395 semantic_binexpr_arithmetic, 1)
8396 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8397 semantic_binexpr_arithmetic, 1)
8398 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8399 semantic_binexpr_arithmetic, 1)
8400 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8401 semantic_logical_op, 1)
8402 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8403 semantic_logical_op, 1)
8404 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8405 semantic_shift_op, 1)
8406 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8407 semantic_shift_op, 1)
8408 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8409 semantic_arithmetic_addsubb_assign, 0)
8410 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8411 semantic_arithmetic_addsubb_assign, 0)
8412 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8413 semantic_arithmetic_assign, 0)
8414 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8415 semantic_divmod_assign, 0)
8416 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8417 semantic_divmod_assign, 0)
8418 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8419 semantic_arithmetic_assign, 0)
8420 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8421 semantic_arithmetic_assign, 0)
8422 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8423 semantic_arithmetic_assign, 0)
8424 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8425 semantic_arithmetic_assign, 0)
8426 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8427 semantic_arithmetic_assign, 0)
8429 static expression_t *parse_sub_expression(unsigned precedence)
8431 if (token.type < 0) {
8432 return expected_expression_error();
8435 expression_parser_function_t *parser
8436 = &expression_parsers[token.type];
8437 source_position_t source_position = token.source_position;
8440 if (parser->parser != NULL) {
8441 left = parser->parser(parser->precedence);
8443 left = parse_primary_expression();
8445 assert(left != NULL);
8446 left->base.source_position = source_position;
8449 if (token.type < 0) {
8450 return expected_expression_error();
8453 parser = &expression_parsers[token.type];
8454 if (parser->infix_parser == NULL)
8456 if (parser->infix_precedence < precedence)
8459 left = parser->infix_parser(parser->infix_precedence, left);
8461 assert(left != NULL);
8462 assert(left->kind != EXPR_UNKNOWN);
8463 left->base.source_position = source_position;
8470 * Parse an expression.
8472 static expression_t *parse_expression(void)
8474 return parse_sub_expression(1);
8478 * Register a parser for a prefix-like operator with given precedence.
8480 * @param parser the parser function
8481 * @param token_type the token type of the prefix token
8482 * @param precedence the precedence of the operator
8484 static void register_expression_parser(parse_expression_function parser,
8485 int token_type, unsigned precedence)
8487 expression_parser_function_t *entry = &expression_parsers[token_type];
8489 if (entry->parser != NULL) {
8490 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8491 panic("trying to register multiple expression parsers for a token");
8493 entry->parser = parser;
8494 entry->precedence = precedence;
8498 * Register a parser for an infix operator with given precedence.
8500 * @param parser the parser function
8501 * @param token_type the token type of the infix operator
8502 * @param precedence the precedence of the operator
8504 static void register_infix_parser(parse_expression_infix_function parser,
8505 int token_type, unsigned precedence)
8507 expression_parser_function_t *entry = &expression_parsers[token_type];
8509 if (entry->infix_parser != NULL) {
8510 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8511 panic("trying to register multiple infix expression parsers for a "
8514 entry->infix_parser = parser;
8515 entry->infix_precedence = precedence;
8519 * Initialize the expression parsers.
8521 static void init_expression_parsers(void)
8523 memset(&expression_parsers, 0, sizeof(expression_parsers));
8525 register_infix_parser(parse_array_expression, '[', 30);
8526 register_infix_parser(parse_call_expression, '(', 30);
8527 register_infix_parser(parse_select_expression, '.', 30);
8528 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8529 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8531 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8534 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8535 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8536 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8537 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8538 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8539 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8540 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8541 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8542 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8543 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8544 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8545 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8546 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8547 T_EXCLAMATIONMARKEQUAL, 13);
8548 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8549 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8550 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8551 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8552 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8553 register_infix_parser(parse_conditional_expression, '?', 7);
8554 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8555 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8556 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8557 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8558 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8559 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8560 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8561 T_LESSLESSEQUAL, 2);
8562 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8563 T_GREATERGREATEREQUAL, 2);
8564 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8566 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8568 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8571 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8573 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8574 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8575 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8576 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8577 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8578 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8579 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8581 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8583 register_expression_parser(parse_sizeof, T_sizeof, 25);
8584 register_expression_parser(parse_alignof, T___alignof__, 25);
8585 register_expression_parser(parse_extension, T___extension__, 25);
8586 register_expression_parser(parse_builtin_classify_type,
8587 T___builtin_classify_type, 25);
8591 * Parse a asm statement arguments specification.
8593 static asm_argument_t *parse_asm_arguments(bool is_out)
8595 asm_argument_t *result = NULL;
8596 asm_argument_t *last = NULL;
8598 while (token.type == T_STRING_LITERAL || token.type == '[') {
8599 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8600 memset(argument, 0, sizeof(argument[0]));
8602 if (token.type == '[') {
8604 if (token.type != T_IDENTIFIER) {
8605 parse_error_expected("while parsing asm argument",
8606 T_IDENTIFIER, NULL);
8609 argument->symbol = token.v.symbol;
8614 argument->constraints = parse_string_literals();
8616 add_anchor_token(')');
8617 expression_t *expression = parse_expression();
8618 rem_anchor_token(')');
8620 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8621 * change size or type representation (e.g. int -> long is ok, but
8622 * int -> float is not) */
8623 if (expression->kind == EXPR_UNARY_CAST) {
8624 type_t *const type = expression->base.type;
8625 type_kind_t const kind = type->kind;
8626 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8629 if (kind == TYPE_ATOMIC) {
8630 atomic_type_kind_t const akind = type->atomic.akind;
8631 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8632 size = get_atomic_type_size(akind);
8634 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8635 size = get_atomic_type_size(get_intptr_kind());
8639 expression_t *const value = expression->unary.value;
8640 type_t *const value_type = value->base.type;
8641 type_kind_t const value_kind = value_type->kind;
8643 unsigned value_flags;
8644 unsigned value_size;
8645 if (value_kind == TYPE_ATOMIC) {
8646 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8647 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8648 value_size = get_atomic_type_size(value_akind);
8649 } else if (value_kind == TYPE_POINTER) {
8650 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8651 value_size = get_atomic_type_size(get_intptr_kind());
8656 if (value_flags != flags || value_size != size)
8660 } while (expression->kind == EXPR_UNARY_CAST);
8664 if (!is_lvalue(expression)) {
8665 errorf(&expression->base.source_position,
8666 "asm output argument is not an lvalue");
8669 argument->expression = expression;
8672 set_address_taken(expression, true);
8675 last->next = argument;
8681 if (token.type != ',')
8692 * Parse a asm statement clobber specification.
8694 static asm_clobber_t *parse_asm_clobbers(void)
8696 asm_clobber_t *result = NULL;
8697 asm_clobber_t *last = NULL;
8699 while(token.type == T_STRING_LITERAL) {
8700 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8701 clobber->clobber = parse_string_literals();
8704 last->next = clobber;
8710 if (token.type != ',')
8719 * Parse an asm statement.
8721 static statement_t *parse_asm_statement(void)
8723 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8724 asm_statement_t *asm_statement = &statement->asms;
8728 if (token.type == T_volatile) {
8730 asm_statement->is_volatile = true;
8734 add_anchor_token(')');
8735 add_anchor_token(':');
8736 asm_statement->asm_text = parse_string_literals();
8738 if (token.type != ':') {
8739 rem_anchor_token(':');
8744 asm_statement->outputs = parse_asm_arguments(true);
8745 if (token.type != ':') {
8746 rem_anchor_token(':');
8751 asm_statement->inputs = parse_asm_arguments(false);
8752 if (token.type != ':') {
8753 rem_anchor_token(':');
8756 rem_anchor_token(':');
8759 asm_statement->clobbers = parse_asm_clobbers();
8762 rem_anchor_token(')');
8766 if (asm_statement->outputs == NULL) {
8767 /* GCC: An 'asm' instruction without any output operands will be treated
8768 * identically to a volatile 'asm' instruction. */
8769 asm_statement->is_volatile = true;
8774 return create_invalid_statement();
8778 * Parse a case statement.
8780 static statement_t *parse_case_statement(void)
8782 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8783 source_position_t *const pos = &statement->base.source_position;
8787 expression_t *const expression = parse_expression();
8788 statement->case_label.expression = expression;
8789 if (!is_constant_expression(expression)) {
8790 /* This check does not prevent the error message in all cases of an
8791 * prior error while parsing the expression. At least it catches the
8792 * common case of a mistyped enum entry. */
8793 if (is_type_valid(skip_typeref(expression->base.type))) {
8794 errorf(pos, "case label does not reduce to an integer constant");
8796 statement->case_label.is_bad = true;
8798 long const val = fold_constant(expression);
8799 statement->case_label.first_case = val;
8800 statement->case_label.last_case = val;
8804 if (token.type == T_DOTDOTDOT) {
8806 expression_t *const end_range = parse_expression();
8807 statement->case_label.end_range = end_range;
8808 if (!is_constant_expression(end_range)) {
8809 /* This check does not prevent the error message in all cases of an
8810 * prior error while parsing the expression. At least it catches the
8811 * common case of a mistyped enum entry. */
8812 if (is_type_valid(skip_typeref(end_range->base.type))) {
8813 errorf(pos, "case range does not reduce to an integer constant");
8815 statement->case_label.is_bad = true;
8817 long const val = fold_constant(end_range);
8818 statement->case_label.last_case = val;
8820 if (val < statement->case_label.first_case) {
8821 statement->case_label.is_empty_range = true;
8822 warningf(pos, "empty range specified");
8828 PUSH_PARENT(statement);
8832 if (current_switch != NULL) {
8833 if (! statement->case_label.is_bad) {
8834 /* Check for duplicate case values */
8835 case_label_statement_t *c = &statement->case_label;
8836 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8837 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8840 if (c->last_case < l->first_case || c->first_case > l->last_case)
8843 errorf(pos, "duplicate case value (previously used %P)",
8844 &l->base.source_position);
8848 /* link all cases into the switch statement */
8849 if (current_switch->last_case == NULL) {
8850 current_switch->first_case = &statement->case_label;
8852 current_switch->last_case->next = &statement->case_label;
8854 current_switch->last_case = &statement->case_label;
8856 errorf(pos, "case label not within a switch statement");
8859 statement_t *const inner_stmt = parse_statement();
8860 statement->case_label.statement = inner_stmt;
8861 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8862 errorf(&inner_stmt->base.source_position, "declaration after case label");
8869 return create_invalid_statement();
8873 * Parse a default statement.
8875 static statement_t *parse_default_statement(void)
8877 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8881 PUSH_PARENT(statement);
8884 if (current_switch != NULL) {
8885 const case_label_statement_t *def_label = current_switch->default_label;
8886 if (def_label != NULL) {
8887 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8888 &def_label->base.source_position);
8890 current_switch->default_label = &statement->case_label;
8892 /* link all cases into the switch statement */
8893 if (current_switch->last_case == NULL) {
8894 current_switch->first_case = &statement->case_label;
8896 current_switch->last_case->next = &statement->case_label;
8898 current_switch->last_case = &statement->case_label;
8901 errorf(&statement->base.source_position,
8902 "'default' label not within a switch statement");
8905 statement_t *const inner_stmt = parse_statement();
8906 statement->case_label.statement = inner_stmt;
8907 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8908 errorf(&inner_stmt->base.source_position, "declaration after default label");
8915 return create_invalid_statement();
8919 * Parse a label statement.
8921 static statement_t *parse_label_statement(void)
8923 assert(token.type == T_IDENTIFIER);
8924 symbol_t *symbol = token.v.symbol;
8925 declaration_t *label = get_label(symbol);
8927 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8928 statement->label.label = label;
8932 PUSH_PARENT(statement);
8934 /* if statement is already set then the label is defined twice,
8935 * otherwise it was just mentioned in a goto/local label declaration so far */
8936 if (label->init.statement != NULL) {
8937 errorf(HERE, "duplicate label '%Y' (declared %P)",
8938 symbol, &label->source_position);
8940 label->source_position = token.source_position;
8941 label->init.statement = statement;
8946 if (token.type == '}') {
8947 /* TODO only warn? */
8949 warningf(HERE, "label at end of compound statement");
8950 statement->label.statement = create_empty_statement();
8952 errorf(HERE, "label at end of compound statement");
8953 statement->label.statement = create_invalid_statement();
8955 } else if (token.type == ';') {
8956 /* Eat an empty statement here, to avoid the warning about an empty
8957 * statement after a label. label:; is commonly used to have a label
8958 * before a closing brace. */
8959 statement->label.statement = create_empty_statement();
8962 statement_t *const inner_stmt = parse_statement();
8963 statement->label.statement = inner_stmt;
8964 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8965 errorf(&inner_stmt->base.source_position, "declaration after label");
8969 /* remember the labels in a list for later checking */
8970 if (label_last == NULL) {
8971 label_first = &statement->label;
8973 label_last->next = &statement->label;
8975 label_last = &statement->label;
8982 * Parse an if statement.
8984 static statement_t *parse_if(void)
8986 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8990 PUSH_PARENT(statement);
8992 add_anchor_token('{');
8995 add_anchor_token(')');
8996 statement->ifs.condition = parse_expression();
8997 rem_anchor_token(')');
9001 rem_anchor_token('{');
9003 add_anchor_token(T_else);
9004 statement->ifs.true_statement = parse_statement();
9005 rem_anchor_token(T_else);
9007 if (token.type == T_else) {
9009 statement->ifs.false_statement = parse_statement();
9017 * Check that all enums are handled in a switch.
9019 * @param statement the switch statement to check
9021 static void check_enum_cases(const switch_statement_t *statement) {
9022 const type_t *type = skip_typeref(statement->expression->base.type);
9023 if (! is_type_enum(type))
9025 const enum_type_t *enumt = &type->enumt;
9027 /* if we have a default, no warnings */
9028 if (statement->default_label != NULL)
9031 /* FIXME: calculation of value should be done while parsing */
9032 const declaration_t *declaration;
9033 long last_value = -1;
9034 for (declaration = enumt->declaration->next;
9035 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
9036 declaration = declaration->next) {
9037 const expression_t *expression = declaration->init.enum_value;
9038 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9040 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9041 if (l->expression == NULL)
9043 if (l->first_case <= value && value <= l->last_case) {
9049 warningf(&statement->base.source_position,
9050 "enumeration value '%Y' not handled in switch", declaration->symbol);
9057 * Parse a switch statement.
9059 static statement_t *parse_switch(void)
9061 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9065 PUSH_PARENT(statement);
9068 add_anchor_token(')');
9069 expression_t *const expr = parse_expression();
9070 type_t * type = skip_typeref(expr->base.type);
9071 if (is_type_integer(type)) {
9072 type = promote_integer(type);
9073 if (warning.traditional) {
9074 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9075 warningf(&expr->base.source_position,
9076 "'%T' switch expression not converted to '%T' in ISO C",
9080 } else if (is_type_valid(type)) {
9081 errorf(&expr->base.source_position,
9082 "switch quantity is not an integer, but '%T'", type);
9083 type = type_error_type;
9085 statement->switchs.expression = create_implicit_cast(expr, type);
9087 rem_anchor_token(')');
9089 switch_statement_t *rem = current_switch;
9090 current_switch = &statement->switchs;
9091 statement->switchs.body = parse_statement();
9092 current_switch = rem;
9094 if (warning.switch_default &&
9095 statement->switchs.default_label == NULL) {
9096 warningf(&statement->base.source_position, "switch has no default case");
9098 if (warning.switch_enum)
9099 check_enum_cases(&statement->switchs);
9105 return create_invalid_statement();
9108 static statement_t *parse_loop_body(statement_t *const loop)
9110 statement_t *const rem = current_loop;
9111 current_loop = loop;
9113 statement_t *const body = parse_statement();
9120 * Parse a while statement.
9122 static statement_t *parse_while(void)
9124 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9128 PUSH_PARENT(statement);
9131 add_anchor_token(')');
9132 statement->whiles.condition = parse_expression();
9133 rem_anchor_token(')');
9136 statement->whiles.body = parse_loop_body(statement);
9142 return create_invalid_statement();
9146 * Parse a do statement.
9148 static statement_t *parse_do(void)
9150 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9154 PUSH_PARENT(statement);
9156 add_anchor_token(T_while);
9157 statement->do_while.body = parse_loop_body(statement);
9158 rem_anchor_token(T_while);
9162 add_anchor_token(')');
9163 statement->do_while.condition = parse_expression();
9164 rem_anchor_token(')');
9172 return create_invalid_statement();
9176 * Parse a for statement.
9178 static statement_t *parse_for(void)
9180 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9184 PUSH_PARENT(statement);
9186 size_t const top = environment_top();
9187 scope_push(&statement->fors.scope);
9190 add_anchor_token(')');
9192 if (token.type != ';') {
9193 if (is_declaration_specifier(&token, false)) {
9194 parse_declaration(record_declaration);
9196 add_anchor_token(';');
9197 expression_t *const init = parse_expression();
9198 statement->fors.initialisation = init;
9199 if (warning.unused_value && !expression_has_effect(init)) {
9200 warningf(&init->base.source_position,
9201 "initialisation of 'for'-statement has no effect");
9203 rem_anchor_token(';');
9210 if (token.type != ';') {
9211 add_anchor_token(';');
9212 statement->fors.condition = parse_expression();
9213 rem_anchor_token(';');
9216 if (token.type != ')') {
9217 expression_t *const step = parse_expression();
9218 statement->fors.step = step;
9219 if (warning.unused_value && !expression_has_effect(step)) {
9220 warningf(&step->base.source_position,
9221 "step of 'for'-statement has no effect");
9224 rem_anchor_token(')');
9226 statement->fors.body = parse_loop_body(statement);
9228 assert(scope == &statement->fors.scope);
9230 environment_pop_to(top);
9237 rem_anchor_token(')');
9238 assert(scope == &statement->fors.scope);
9240 environment_pop_to(top);
9242 return create_invalid_statement();
9246 * Parse a goto statement.
9248 static statement_t *parse_goto(void)
9250 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9253 if (GNU_MODE && token.type == '*') {
9255 expression_t *expression = parse_expression();
9257 /* Argh: although documentation say the expression must be of type void *,
9258 * gcc excepts anything that can be casted into void * without error */
9259 type_t *type = expression->base.type;
9261 if (type != type_error_type) {
9262 if (!is_type_pointer(type) && !is_type_integer(type)) {
9263 errorf(&expression->base.source_position,
9264 "cannot convert to a pointer type");
9265 } else if (type != type_void_ptr) {
9266 warningf(&expression->base.source_position,
9267 "type of computed goto expression should be 'void*' not '%T'", type);
9269 expression = create_implicit_cast(expression, type_void_ptr);
9272 statement->gotos.expression = expression;
9274 if (token.type != T_IDENTIFIER) {
9276 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9278 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9282 symbol_t *symbol = token.v.symbol;
9285 statement->gotos.label = get_label(symbol);
9287 if (statement->gotos.label->parent_scope->depth < current_function->scope.depth) {
9288 statement->gotos.outer_fkt_jmp = true;
9292 /* remember the goto's in a list for later checking */
9293 if (goto_last == NULL) {
9294 goto_first = &statement->gotos;
9296 goto_last->next = &statement->gotos;
9298 goto_last = &statement->gotos;
9304 return create_invalid_statement();
9308 * Parse a continue statement.
9310 static statement_t *parse_continue(void)
9312 if (current_loop == NULL) {
9313 errorf(HERE, "continue statement not within loop");
9316 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9326 * Parse a break statement.
9328 static statement_t *parse_break(void)
9330 if (current_switch == NULL && current_loop == NULL) {
9331 errorf(HERE, "break statement not within loop or switch");
9334 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9344 * Parse a __leave statement.
9346 static statement_t *parse_leave_statement(void)
9348 if (current_try == NULL) {
9349 errorf(HERE, "__leave statement not within __try");
9352 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9362 * Check if a given declaration represents a local variable.
9364 static bool is_local_var_declaration(const declaration_t *declaration)
9366 switch ((storage_class_tag_t) declaration->storage_class) {
9367 case STORAGE_CLASS_AUTO:
9368 case STORAGE_CLASS_REGISTER: {
9369 const type_t *type = skip_typeref(declaration->type);
9370 if (is_type_function(type)) {
9382 * Check if a given declaration represents a variable.
9384 static bool is_var_declaration(const declaration_t *declaration)
9386 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9389 const type_t *type = skip_typeref(declaration->type);
9390 return !is_type_function(type);
9394 * Check if a given expression represents a local variable.
9396 static bool is_local_variable(const expression_t *expression)
9398 if (expression->base.kind != EXPR_REFERENCE) {
9401 const declaration_t *declaration = expression->reference.declaration;
9402 return is_local_var_declaration(declaration);
9406 * Check if a given expression represents a local variable and
9407 * return its declaration then, else return NULL.
9409 declaration_t *expr_is_variable(const expression_t *expression)
9411 if (expression->base.kind != EXPR_REFERENCE) {
9414 declaration_t *declaration = expression->reference.declaration;
9415 if (is_var_declaration(declaration))
9421 * Parse a return statement.
9423 static statement_t *parse_return(void)
9427 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9429 expression_t *return_value = NULL;
9430 if (token.type != ';') {
9431 return_value = parse_expression();
9434 const type_t *const func_type = current_function->type;
9435 assert(is_type_function(func_type));
9436 type_t *const return_type = skip_typeref(func_type->function.return_type);
9438 if (return_value != NULL) {
9439 type_t *return_value_type = skip_typeref(return_value->base.type);
9441 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9442 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9443 warningf(&statement->base.source_position,
9444 "'return' with a value, in function returning void");
9445 return_value = NULL;
9447 assign_error_t error = semantic_assign(return_type, return_value);
9448 report_assign_error(error, return_type, return_value, "'return'",
9449 &statement->base.source_position);
9450 return_value = create_implicit_cast(return_value, return_type);
9452 /* check for returning address of a local var */
9453 if (return_value != NULL &&
9454 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9455 const expression_t *expression = return_value->unary.value;
9456 if (is_local_variable(expression)) {
9457 warningf(&statement->base.source_position,
9458 "function returns address of local variable");
9462 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9463 warningf(&statement->base.source_position,
9464 "'return' without value, in function returning non-void");
9467 statement->returns.value = return_value;
9476 * Parse a declaration statement.
9478 static statement_t *parse_declaration_statement(void)
9480 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9482 declaration_t *before = last_declaration;
9484 parse_external_declaration();
9486 parse_declaration(record_declaration);
9488 if (before == NULL) {
9489 statement->declaration.declarations_begin = scope->declarations;
9491 statement->declaration.declarations_begin = before->next;
9493 statement->declaration.declarations_end = last_declaration;
9499 * Parse an expression statement, ie. expr ';'.
9501 static statement_t *parse_expression_statement(void)
9503 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9505 expression_t *const expr = parse_expression();
9506 statement->expression.expression = expr;
9515 * Parse a microsoft __try { } __finally { } or
9516 * __try{ } __except() { }
9518 static statement_t *parse_ms_try_statment(void)
9520 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9523 PUSH_PARENT(statement);
9525 ms_try_statement_t *rem = current_try;
9526 current_try = &statement->ms_try;
9527 statement->ms_try.try_statement = parse_compound_statement(false);
9532 if (token.type == T___except) {
9535 add_anchor_token(')');
9536 expression_t *const expr = parse_expression();
9537 type_t * type = skip_typeref(expr->base.type);
9538 if (is_type_integer(type)) {
9539 type = promote_integer(type);
9540 } else if (is_type_valid(type)) {
9541 errorf(&expr->base.source_position,
9542 "__expect expression is not an integer, but '%T'", type);
9543 type = type_error_type;
9545 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9546 rem_anchor_token(')');
9548 statement->ms_try.final_statement = parse_compound_statement(false);
9549 } else if (token.type == T__finally) {
9551 statement->ms_try.final_statement = parse_compound_statement(false);
9553 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9554 return create_invalid_statement();
9558 return create_invalid_statement();
9561 static statement_t *parse_empty_statement(void)
9563 if (warning.empty_statement) {
9564 warningf(HERE, "statement is empty");
9566 statement_t *const statement = create_empty_statement();
9571 static statement_t *parse_local_label_declaration(void) {
9572 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9576 declaration_t *begin = NULL, *end = NULL;
9579 if (token.type != T_IDENTIFIER) {
9580 parse_error_expected("while parsing local label declaration",
9581 T_IDENTIFIER, NULL);
9584 symbol_t *symbol = token.v.symbol;
9585 declaration_t *declaration = get_declaration(symbol, NAMESPACE_LOCAL_LABEL);
9586 if (declaration != NULL) {
9587 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition at %P)",
9588 symbol, &declaration->source_position);
9590 declaration = allocate_declaration_zero();
9591 declaration->namespc = NAMESPACE_LOCAL_LABEL;
9592 declaration->source_position = token.source_position;
9593 declaration->symbol = symbol;
9594 declaration->parent_scope = scope;
9595 declaration->init.statement = NULL;
9598 end->next = declaration;
9601 begin = declaration;
9603 local_label_push(declaration);
9607 if (token.type != ',')
9613 statement->declaration.declarations_begin = begin;
9614 statement->declaration.declarations_end = end;
9619 * Parse a statement.
9620 * There's also parse_statement() which additionally checks for
9621 * "statement has no effect" warnings
9623 static statement_t *intern_parse_statement(void)
9625 statement_t *statement = NULL;
9627 /* declaration or statement */
9628 add_anchor_token(';');
9629 switch (token.type) {
9630 case T_IDENTIFIER: {
9631 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9632 if (la1_type == ':') {
9633 statement = parse_label_statement();
9634 } else if (is_typedef_symbol(token.v.symbol)) {
9635 statement = parse_declaration_statement();
9636 } else switch (la1_type) {
9638 if (get_declaration(token.v.symbol, NAMESPACE_NORMAL) != NULL)
9639 goto expression_statment;
9644 statement = parse_declaration_statement();
9648 expression_statment:
9649 statement = parse_expression_statement();
9655 case T___extension__:
9656 /* This can be a prefix to a declaration or an expression statement.
9657 * We simply eat it now and parse the rest with tail recursion. */
9660 } while (token.type == T___extension__);
9661 bool old_gcc_extension = in_gcc_extension;
9662 in_gcc_extension = true;
9663 statement = parse_statement();
9664 in_gcc_extension = old_gcc_extension;
9668 statement = parse_declaration_statement();
9672 statement = parse_local_label_declaration();
9675 case ';': statement = parse_empty_statement(); break;
9676 case '{': statement = parse_compound_statement(false); break;
9677 case T___leave: statement = parse_leave_statement(); break;
9678 case T___try: statement = parse_ms_try_statment(); break;
9679 case T_asm: statement = parse_asm_statement(); break;
9680 case T_break: statement = parse_break(); break;
9681 case T_case: statement = parse_case_statement(); break;
9682 case T_continue: statement = parse_continue(); break;
9683 case T_default: statement = parse_default_statement(); break;
9684 case T_do: statement = parse_do(); break;
9685 case T_for: statement = parse_for(); break;
9686 case T_goto: statement = parse_goto(); break;
9687 case T_if: statement = parse_if (); break;
9688 case T_return: statement = parse_return(); break;
9689 case T_switch: statement = parse_switch(); break;
9690 case T_while: statement = parse_while(); break;
9700 case T_CHARACTER_CONSTANT:
9701 case T_FLOATINGPOINT:
9705 case T_STRING_LITERAL:
9706 case T_WIDE_CHARACTER_CONSTANT:
9707 case T_WIDE_STRING_LITERAL:
9708 case T___FUNCDNAME__:
9710 case T___FUNCTION__:
9711 case T___PRETTY_FUNCTION__:
9712 case T___builtin_alloca:
9713 case T___builtin_classify_type:
9714 case T___builtin_constant_p:
9715 case T___builtin_expect:
9716 case T___builtin_huge_val:
9717 case T___builtin_isgreater:
9718 case T___builtin_isgreaterequal:
9719 case T___builtin_isless:
9720 case T___builtin_islessequal:
9721 case T___builtin_islessgreater:
9722 case T___builtin_isunordered:
9723 case T___builtin_inf:
9724 case T___builtin_inff:
9725 case T___builtin_infl:
9726 case T___builtin_nan:
9727 case T___builtin_nanf:
9728 case T___builtin_nanl:
9729 case T___builtin_offsetof:
9730 case T___builtin_prefetch:
9731 case T___builtin_va_arg:
9732 case T___builtin_va_end:
9733 case T___builtin_va_start:
9737 statement = parse_expression_statement();
9741 errorf(HERE, "unexpected token %K while parsing statement", &token);
9742 statement = create_invalid_statement();
9747 rem_anchor_token(';');
9749 assert(statement != NULL
9750 && statement->base.source_position.input_name != NULL);
9756 * parse a statement and emits "statement has no effect" warning if needed
9757 * (This is really a wrapper around intern_parse_statement with check for 1
9758 * single warning. It is needed, because for statement expressions we have
9759 * to avoid the warning on the last statement)
9761 static statement_t *parse_statement(void)
9763 statement_t *statement = intern_parse_statement();
9765 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9766 expression_t *expression = statement->expression.expression;
9767 if (!expression_has_effect(expression)) {
9768 warningf(&expression->base.source_position,
9769 "statement has no effect");
9777 * Parse a compound statement.
9779 static statement_t *parse_compound_statement(bool inside_expression_statement)
9781 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9783 PUSH_PARENT(statement);
9786 add_anchor_token('}');
9788 size_t const top = environment_top();
9789 size_t const top_local = local_label_top();
9790 scope_push(&statement->compound.scope);
9792 statement_t **anchor = &statement->compound.statements;
9793 bool only_decls_so_far = true;
9794 while (token.type != '}') {
9795 if (token.type == T_EOF) {
9796 errorf(&statement->base.source_position,
9797 "EOF while parsing compound statement");
9800 statement_t *sub_statement = intern_parse_statement();
9801 if (is_invalid_statement(sub_statement)) {
9802 /* an error occurred. if we are at an anchor, return */
9808 if (warning.declaration_after_statement) {
9809 if (sub_statement->kind != STATEMENT_DECLARATION) {
9810 only_decls_so_far = false;
9811 } else if (!only_decls_so_far) {
9812 warningf(&sub_statement->base.source_position,
9813 "ISO C90 forbids mixed declarations and code");
9817 *anchor = sub_statement;
9819 while (sub_statement->base.next != NULL)
9820 sub_statement = sub_statement->base.next;
9822 anchor = &sub_statement->base.next;
9826 /* look over all statements again to produce no effect warnings */
9827 if (warning.unused_value) {
9828 statement_t *sub_statement = statement->compound.statements;
9829 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9830 if (sub_statement->kind != STATEMENT_EXPRESSION)
9832 /* don't emit a warning for the last expression in an expression
9833 * statement as it has always an effect */
9834 if (inside_expression_statement && sub_statement->base.next == NULL)
9837 expression_t *expression = sub_statement->expression.expression;
9838 if (!expression_has_effect(expression)) {
9839 warningf(&expression->base.source_position,
9840 "statement has no effect");
9846 rem_anchor_token('}');
9847 assert(scope == &statement->compound.scope);
9849 environment_pop_to(top);
9850 local_label_pop_to(top_local);
9857 * Initialize builtin types.
9859 static void initialize_builtin_types(void)
9861 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9862 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9863 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9864 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9865 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9866 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9867 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9868 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9870 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9871 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9872 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9873 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9875 /* const version of wchar_t */
9876 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9877 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9878 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9880 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9884 * Check for unused global static functions and variables
9886 static void check_unused_globals(void)
9888 if (!warning.unused_function && !warning.unused_variable)
9891 for (const declaration_t *decl = file_scope->declarations; decl != NULL; decl = decl->next) {
9893 decl->modifiers & DM_UNUSED ||
9894 decl->modifiers & DM_USED ||
9895 decl->storage_class != STORAGE_CLASS_STATIC)
9898 type_t *const type = decl->type;
9900 if (is_type_function(skip_typeref(type))) {
9901 if (!warning.unused_function || decl->is_inline)
9904 s = (decl->init.statement != NULL ? "defined" : "declared");
9906 if (!warning.unused_variable)
9912 warningf(&decl->source_position, "'%#T' %s but not used",
9913 type, decl->symbol, s);
9917 static void parse_global_asm(void)
9919 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9924 statement->asms.asm_text = parse_string_literals();
9925 statement->base.next = unit->global_asm;
9926 unit->global_asm = statement;
9935 * Parse a translation unit.
9937 static void parse_translation_unit(void)
9939 add_anchor_token(T_EOF);
9942 unsigned char token_anchor_copy[T_LAST_TOKEN];
9943 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
9947 bool anchor_leak = false;
9948 for (int i = 0; i != T_LAST_TOKEN; ++i) {
9949 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
9951 errorf(HERE, "Leaked anchor token %k %d times", i, count);
9955 if (in_gcc_extension) {
9956 errorf(HERE, "Leaked __extension__");
9964 switch (token.type) {
9967 case T___extension__:
9968 parse_external_declaration();
9976 rem_anchor_token(T_EOF);
9981 warningf(HERE, "stray ';' outside of function");
9988 errorf(HERE, "stray %K outside of function", &token);
9989 if (token.type == '(' || token.type == '{' || token.type == '[')
9990 eat_until_matching_token(token.type);
10000 * @return the translation unit or NULL if errors occurred.
10002 void start_parsing(void)
10004 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10005 label_stack = NEW_ARR_F(stack_entry_t, 0);
10006 local_label_stack = NEW_ARR_F(stack_entry_t, 0);
10007 diagnostic_count = 0;
10011 type_set_output(stderr);
10012 ast_set_output(stderr);
10014 assert(unit == NULL);
10015 unit = allocate_ast_zero(sizeof(unit[0]));
10017 assert(file_scope == NULL);
10018 file_scope = &unit->scope;
10020 assert(scope == NULL);
10021 scope_push(&unit->scope);
10023 initialize_builtin_types();
10026 translation_unit_t *finish_parsing(void)
10028 /* do NOT use scope_pop() here, this will crash, will it by hand */
10029 assert(scope == &unit->scope);
10031 last_declaration = NULL;
10033 assert(file_scope == &unit->scope);
10034 check_unused_globals();
10037 DEL_ARR_F(environment_stack);
10038 DEL_ARR_F(label_stack);
10039 DEL_ARR_F(local_label_stack);
10041 translation_unit_t *result = unit;
10048 lookahead_bufpos = 0;
10049 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10052 parse_translation_unit();
10056 * Initialize the parser.
10058 void init_parser(void)
10060 sym_anonymous = symbol_table_insert("<anonymous>");
10062 if (c_mode & _MS) {
10063 /* add predefined symbols for extended-decl-modifier */
10064 sym_align = symbol_table_insert("align");
10065 sym_allocate = symbol_table_insert("allocate");
10066 sym_dllimport = symbol_table_insert("dllimport");
10067 sym_dllexport = symbol_table_insert("dllexport");
10068 sym_naked = symbol_table_insert("naked");
10069 sym_noinline = symbol_table_insert("noinline");
10070 sym_noreturn = symbol_table_insert("noreturn");
10071 sym_nothrow = symbol_table_insert("nothrow");
10072 sym_novtable = symbol_table_insert("novtable");
10073 sym_property = symbol_table_insert("property");
10074 sym_get = symbol_table_insert("get");
10075 sym_put = symbol_table_insert("put");
10076 sym_selectany = symbol_table_insert("selectany");
10077 sym_thread = symbol_table_insert("thread");
10078 sym_uuid = symbol_table_insert("uuid");
10079 sym_deprecated = symbol_table_insert("deprecated");
10080 sym_restrict = symbol_table_insert("restrict");
10081 sym_noalias = symbol_table_insert("noalias");
10083 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10085 init_expression_parsers();
10086 obstack_init(&temp_obst);
10088 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10089 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10093 * Terminate the parser.
10095 void exit_parser(void)
10097 obstack_free(&temp_obst, NULL);