2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
36 #include "lang_features.h"
38 #include "adt/bitfiddle.h"
39 #include "adt/error.h"
40 #include "adt/array.h"
42 /** if wchar_t is equal to unsigned short. */
43 bool opt_short_wchar_t =
50 //#define PRINT_TOKENS
51 #define MAX_LOOKAHEAD 2
54 declaration_t *old_declaration;
56 unsigned short namespc;
59 typedef struct argument_list_t argument_list_t;
60 struct argument_list_t {
62 argument_list_t *next;
65 typedef struct gnu_attribute_t gnu_attribute_t;
66 struct gnu_attribute_t {
67 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
68 gnu_attribute_t *next;
69 bool invalid; /**< Set if this attribute had argument errors, */
70 bool have_arguments; /**< True, if this attribute has arguments. */
74 atomic_type_kind_t akind;
75 long argument; /**< Single argument. */
76 argument_list_t *arguments; /**< List of argument expressions. */
80 typedef struct declaration_specifiers_t declaration_specifiers_t;
81 struct declaration_specifiers_t {
82 source_position_t source_position;
83 unsigned char declared_storage_class;
84 unsigned char alignment; /**< Alignment, 0 if not set. */
85 unsigned int is_inline : 1;
86 unsigned int deprecated : 1;
87 decl_modifiers_t modifiers; /**< declaration modifiers */
88 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
89 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
90 symbol_t *get_property_sym; /**< the name of the get property if set. */
91 symbol_t *put_property_sym; /**< the name of the put property if set. */
96 * An environment for parsing initializers (and compound literals).
98 typedef struct parse_initializer_env_t {
99 type_t *type; /**< the type of the initializer. In case of an
100 array type with unspecified size this gets
101 adjusted to the actual size. */
102 declaration_t *declaration; /**< the declaration that is initialized if any */
103 bool must_be_constant;
104 } parse_initializer_env_t;
106 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration, bool is_definition);
108 static token_t token;
109 static token_t lookahead_buffer[MAX_LOOKAHEAD];
110 static int lookahead_bufpos;
111 static stack_entry_t *environment_stack = NULL;
112 static stack_entry_t *label_stack = NULL;
113 static scope_t *global_scope = NULL;
114 static scope_t *scope = NULL;
115 static declaration_t *last_declaration = NULL;
116 static declaration_t *current_function = NULL;
117 static declaration_t *current_init_decl = NULL;
118 static switch_statement_t *current_switch = NULL;
119 static statement_t *current_loop = NULL;
120 static statement_t *current_parent = NULL;
121 static ms_try_statement_t *current_try = NULL;
122 static goto_statement_t *goto_first = NULL;
123 static goto_statement_t *goto_last = NULL;
124 static label_statement_t *label_first = NULL;
125 static label_statement_t *label_last = NULL;
126 static translation_unit_t *unit = NULL;
127 static struct obstack temp_obst;
129 #define PUSH_PARENT(stmt) \
130 statement_t *const prev_parent = current_parent; \
131 current_parent = (stmt);
132 #define POP_PARENT ((void)(current_parent = prev_parent))
134 static source_position_t null_position = { NULL, 0 };
136 /* symbols for Microsoft extended-decl-modifier */
137 static const symbol_t *sym_align = NULL;
138 static const symbol_t *sym_allocate = NULL;
139 static const symbol_t *sym_dllimport = NULL;
140 static const symbol_t *sym_dllexport = NULL;
141 static const symbol_t *sym_naked = NULL;
142 static const symbol_t *sym_noinline = NULL;
143 static const symbol_t *sym_noreturn = NULL;
144 static const symbol_t *sym_nothrow = NULL;
145 static const symbol_t *sym_novtable = NULL;
146 static const symbol_t *sym_property = NULL;
147 static const symbol_t *sym_get = NULL;
148 static const symbol_t *sym_put = NULL;
149 static const symbol_t *sym_selectany = NULL;
150 static const symbol_t *sym_thread = NULL;
151 static const symbol_t *sym_uuid = NULL;
152 static const symbol_t *sym_deprecated = NULL;
153 static const symbol_t *sym_restrict = NULL;
154 static const symbol_t *sym_noalias = NULL;
156 /** The token anchor set */
157 static unsigned char token_anchor_set[T_LAST_TOKEN];
159 /** The current source position. */
160 #define HERE (&token.source_position)
162 static type_t *type_valist;
164 static statement_t *parse_compound_statement(bool inside_expression_statement);
165 static statement_t *parse_statement(void);
167 static expression_t *parse_sub_expression(unsigned precedence);
168 static expression_t *parse_expression(void);
169 static type_t *parse_typename(void);
171 static void parse_compound_type_entries(declaration_t *compound_declaration);
172 static declaration_t *parse_declarator(
173 const declaration_specifiers_t *specifiers, bool may_be_abstract);
174 static declaration_t *record_declaration(declaration_t *declaration, bool is_definition);
176 static void semantic_comparison(binary_expression_t *expression);
178 #define STORAGE_CLASSES \
186 #define TYPE_QUALIFIERS \
191 case T__forceinline: \
192 case T___attribute__:
194 #ifdef PROVIDE_COMPLEX
195 #define COMPLEX_SPECIFIERS \
197 #define IMAGINARY_SPECIFIERS \
200 #define COMPLEX_SPECIFIERS
201 #define IMAGINARY_SPECIFIERS
204 #define TYPE_SPECIFIERS \
219 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define TYPENAME_START \
234 * Allocate an AST node with given size and
235 * initialize all fields with zero.
237 static void *allocate_ast_zero(size_t size)
239 void *res = allocate_ast(size);
240 memset(res, 0, size);
244 static declaration_t *allocate_declaration_zero(void)
246 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
247 declaration->type = type_error_type;
248 declaration->alignment = 0;
253 * Returns the size of a statement node.
255 * @param kind the statement kind
257 static size_t get_statement_struct_size(statement_kind_t kind)
259 static const size_t sizes[] = {
260 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
261 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
262 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
263 [STATEMENT_RETURN] = sizeof(return_statement_t),
264 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
265 [STATEMENT_IF] = sizeof(if_statement_t),
266 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
267 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
268 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
269 [STATEMENT_BREAK] = sizeof(statement_base_t),
270 [STATEMENT_GOTO] = sizeof(goto_statement_t),
271 [STATEMENT_LABEL] = sizeof(label_statement_t),
272 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
273 [STATEMENT_WHILE] = sizeof(while_statement_t),
274 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
275 [STATEMENT_FOR] = sizeof(for_statement_t),
276 [STATEMENT_ASM] = sizeof(asm_statement_t),
277 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
278 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
280 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
281 assert(sizes[kind] != 0);
286 * Returns the size of an expression node.
288 * @param kind the expression kind
290 static size_t get_expression_struct_size(expression_kind_t kind)
292 static const size_t sizes[] = {
293 [EXPR_INVALID] = sizeof(expression_base_t),
294 [EXPR_REFERENCE] = sizeof(reference_expression_t),
295 [EXPR_CONST] = sizeof(const_expression_t),
296 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
297 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
298 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
299 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
300 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
301 [EXPR_CALL] = sizeof(call_expression_t),
302 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
303 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
304 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
305 [EXPR_SELECT] = sizeof(select_expression_t),
306 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
307 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
308 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
309 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
310 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
311 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
312 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
313 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
314 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
315 [EXPR_VA_START] = sizeof(va_start_expression_t),
316 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
317 [EXPR_STATEMENT] = sizeof(statement_expression_t),
319 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
320 return sizes[EXPR_UNARY_FIRST];
322 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
323 return sizes[EXPR_BINARY_FIRST];
325 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
326 assert(sizes[kind] != 0);
331 * Allocate a statement node of given kind and initialize all
334 static statement_t *allocate_statement_zero(statement_kind_t kind)
336 size_t size = get_statement_struct_size(kind);
337 statement_t *res = allocate_ast_zero(size);
339 res->base.kind = kind;
340 res->base.parent = current_parent;
345 * Allocate an expression node of given kind and initialize all
348 static expression_t *allocate_expression_zero(expression_kind_t kind)
350 size_t size = get_expression_struct_size(kind);
351 expression_t *res = allocate_ast_zero(size);
353 res->base.kind = kind;
354 res->base.type = type_error_type;
359 * Creates a new invalid expression.
361 static expression_t *create_invalid_expression(void)
363 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
364 expression->base.source_position = token.source_position;
369 * Creates a new invalid statement.
371 static statement_t *create_invalid_statement(void)
373 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
374 statement->base.source_position = token.source_position;
379 * Allocate a new empty statement.
381 static statement_t *create_empty_statement(void)
383 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
384 statement->base.source_position = token.source_position;
389 * Returns the size of a type node.
391 * @param kind the type kind
393 static size_t get_type_struct_size(type_kind_t kind)
395 static const size_t sizes[] = {
396 [TYPE_ATOMIC] = sizeof(atomic_type_t),
397 [TYPE_COMPLEX] = sizeof(complex_type_t),
398 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
399 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
400 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
401 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
402 [TYPE_ENUM] = sizeof(enum_type_t),
403 [TYPE_FUNCTION] = sizeof(function_type_t),
404 [TYPE_POINTER] = sizeof(pointer_type_t),
405 [TYPE_ARRAY] = sizeof(array_type_t),
406 [TYPE_BUILTIN] = sizeof(builtin_type_t),
407 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
408 [TYPE_TYPEOF] = sizeof(typeof_type_t),
410 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
411 assert(kind <= TYPE_TYPEOF);
412 assert(sizes[kind] != 0);
417 * Allocate a type node of given kind and initialize all
420 * @param kind type kind to allocate
421 * @param source_position the source position of the type definition
423 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
425 size_t size = get_type_struct_size(kind);
426 type_t *res = obstack_alloc(type_obst, size);
427 memset(res, 0, size);
429 res->base.kind = kind;
430 res->base.source_position = *source_position;
435 * Returns the size of an initializer node.
437 * @param kind the initializer kind
439 static size_t get_initializer_size(initializer_kind_t kind)
441 static const size_t sizes[] = {
442 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
443 [INITIALIZER_STRING] = sizeof(initializer_string_t),
444 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
445 [INITIALIZER_LIST] = sizeof(initializer_list_t),
446 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
448 assert(kind < sizeof(sizes) / sizeof(*sizes));
449 assert(sizes[kind] != 0);
454 * Allocate an initializer node of given kind and initialize all
457 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
459 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
466 * Free a type from the type obstack.
468 static void free_type(void *type)
470 obstack_free(type_obst, type);
474 * Returns the index of the top element of the environment stack.
476 static size_t environment_top(void)
478 return ARR_LEN(environment_stack);
482 * Returns the index of the top element of the label stack.
484 static size_t label_top(void)
486 return ARR_LEN(label_stack);
490 * Return the next token.
492 static inline void next_token(void)
494 token = lookahead_buffer[lookahead_bufpos];
495 lookahead_buffer[lookahead_bufpos] = lexer_token;
498 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
501 print_token(stderr, &token);
502 fprintf(stderr, "\n");
507 * Return the next token with a given lookahead.
509 static inline const token_t *look_ahead(int num)
511 assert(num > 0 && num <= MAX_LOOKAHEAD);
512 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
513 return &lookahead_buffer[pos];
517 * Adds a token to the token anchor set (a multi-set).
519 static void add_anchor_token(int token_type)
521 assert(0 <= token_type && token_type < T_LAST_TOKEN);
522 ++token_anchor_set[token_type];
525 static int save_and_reset_anchor_state(int token_type)
527 assert(0 <= token_type && token_type < T_LAST_TOKEN);
528 int count = token_anchor_set[token_type];
529 token_anchor_set[token_type] = 0;
533 static void restore_anchor_state(int token_type, int count)
535 assert(0 <= token_type && token_type < T_LAST_TOKEN);
536 token_anchor_set[token_type] = count;
540 * Remove a token from the token anchor set (a multi-set).
542 static void rem_anchor_token(int token_type)
544 assert(0 <= token_type && token_type < T_LAST_TOKEN);
545 --token_anchor_set[token_type];
548 static bool at_anchor(void)
552 return token_anchor_set[token.type];
556 * Eat tokens until a matching token is found.
558 static void eat_until_matching_token(int type)
562 case '(': end_token = ')'; break;
563 case '{': end_token = '}'; break;
564 case '[': end_token = ']'; break;
565 default: end_token = type; break;
568 unsigned parenthesis_count = 0;
569 unsigned brace_count = 0;
570 unsigned bracket_count = 0;
571 while (token.type != end_token ||
572 parenthesis_count != 0 ||
574 bracket_count != 0) {
575 switch (token.type) {
577 case '(': ++parenthesis_count; break;
578 case '{': ++brace_count; break;
579 case '[': ++bracket_count; break;
582 if (parenthesis_count > 0)
592 if (bracket_count > 0)
595 if (token.type == end_token &&
596 parenthesis_count == 0 &&
610 * Eat input tokens until an anchor is found.
612 static void eat_until_anchor(void)
614 if (token.type == T_EOF)
616 while (token_anchor_set[token.type] == 0) {
617 if (token.type == '(' || token.type == '{' || token.type == '[')
618 eat_until_matching_token(token.type);
619 if (token.type == T_EOF)
625 static void eat_block(void)
627 eat_until_matching_token('{');
628 if (token.type == '}')
633 * eat all token until a ';' is reached or a stop token is found.
635 static void eat_statement(void)
637 eat_until_matching_token(';');
638 if (token.type == ';')
642 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
645 * Report a parse error because an expected token was not found.
648 #if defined __GNUC__ && __GNUC__ >= 4
649 __attribute__((sentinel))
651 void parse_error_expected(const char *message, ...)
653 if (message != NULL) {
654 errorf(HERE, "%s", message);
657 va_start(ap, message);
658 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
663 * Report a type error.
665 static void type_error(const char *msg, const source_position_t *source_position,
668 errorf(source_position, "%s, but found type '%T'", msg, type);
672 * Report an incompatible type.
674 static void type_error_incompatible(const char *msg,
675 const source_position_t *source_position, type_t *type1, type_t *type2)
677 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
682 * Expect the the current token is the expected token.
683 * If not, generate an error, eat the current statement,
684 * and goto the end_error label.
686 #define expect(expected) \
688 if (UNLIKELY(token.type != (expected))) { \
689 parse_error_expected(NULL, (expected), NULL); \
690 add_anchor_token(expected); \
691 eat_until_anchor(); \
692 if (token.type == expected) \
694 rem_anchor_token(expected); \
700 static void set_scope(scope_t *new_scope)
703 scope->last_declaration = last_declaration;
707 last_declaration = new_scope->last_declaration;
711 * Search a symbol in a given namespace and returns its declaration or
712 * NULL if this symbol was not found.
714 static declaration_t *get_declaration(const symbol_t *const symbol,
715 const namespace_t namespc)
717 declaration_t *declaration = symbol->declaration;
718 for( ; declaration != NULL; declaration = declaration->symbol_next) {
719 if (declaration->namespc == namespc)
727 * pushs an environment_entry on the environment stack and links the
728 * corresponding symbol to the new entry
730 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
732 symbol_t *symbol = declaration->symbol;
733 namespace_t namespc = (namespace_t) declaration->namespc;
735 /* replace/add declaration into declaration list of the symbol */
736 declaration_t *iter = symbol->declaration;
738 symbol->declaration = declaration;
740 declaration_t *iter_last = NULL;
741 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
742 /* replace an entry? */
743 if (iter->namespc == namespc) {
744 if (iter_last == NULL) {
745 symbol->declaration = declaration;
747 iter_last->symbol_next = declaration;
749 declaration->symbol_next = iter->symbol_next;
754 assert(iter_last->symbol_next == NULL);
755 iter_last->symbol_next = declaration;
759 /* remember old declaration */
761 entry.symbol = symbol;
762 entry.old_declaration = iter;
763 entry.namespc = (unsigned short) namespc;
764 ARR_APP1(stack_entry_t, *stack_ptr, entry);
767 static void environment_push(declaration_t *declaration)
769 assert(declaration->source_position.input_name != NULL);
770 assert(declaration->parent_scope != NULL);
771 stack_push(&environment_stack, declaration);
775 * Push a declaration of the label stack.
777 * @param declaration the declaration
779 static void label_push(declaration_t *declaration)
781 declaration->parent_scope = ¤t_function->scope;
782 stack_push(&label_stack, declaration);
786 * pops symbols from the environment stack until @p new_top is the top element
788 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
790 stack_entry_t *stack = *stack_ptr;
791 size_t top = ARR_LEN(stack);
794 assert(new_top <= top);
798 for(i = top; i > new_top; --i) {
799 stack_entry_t *entry = &stack[i - 1];
801 declaration_t *old_declaration = entry->old_declaration;
802 symbol_t *symbol = entry->symbol;
803 namespace_t namespc = (namespace_t)entry->namespc;
805 /* replace/remove declaration */
806 declaration_t *declaration = symbol->declaration;
807 assert(declaration != NULL);
808 if (declaration->namespc == namespc) {
809 if (old_declaration == NULL) {
810 symbol->declaration = declaration->symbol_next;
812 symbol->declaration = old_declaration;
815 declaration_t *iter_last = declaration;
816 declaration_t *iter = declaration->symbol_next;
817 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
818 /* replace an entry? */
819 if (iter->namespc == namespc) {
820 assert(iter_last != NULL);
821 iter_last->symbol_next = old_declaration;
822 if (old_declaration != NULL) {
823 old_declaration->symbol_next = iter->symbol_next;
828 assert(iter != NULL);
832 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
835 static void environment_pop_to(size_t new_top)
837 stack_pop_to(&environment_stack, new_top);
841 * Pop all entries on the label stack until the new_top
844 * @param new_top the new stack top
846 static void label_pop_to(size_t new_top)
848 stack_pop_to(&label_stack, new_top);
851 static int get_akind_rank(atomic_type_kind_t akind)
856 static int get_rank(const type_t *type)
858 assert(!is_typeref(type));
859 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
860 * and esp. footnote 108). However we can't fold constants (yet), so we
861 * can't decide whether unsigned int is possible, while int always works.
862 * (unsigned int would be preferable when possible... for stuff like
863 * struct { enum { ... } bla : 4; } ) */
864 if (type->kind == TYPE_ENUM)
865 return get_akind_rank(ATOMIC_TYPE_INT);
867 assert(type->kind == TYPE_ATOMIC);
868 return get_akind_rank(type->atomic.akind);
871 static type_t *promote_integer(type_t *type)
873 if (type->kind == TYPE_BITFIELD)
874 type = type->bitfield.base_type;
876 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
883 * Create a cast expression.
885 * @param expression the expression to cast
886 * @param dest_type the destination type
888 static expression_t *create_cast_expression(expression_t *expression,
891 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
893 cast->unary.value = expression;
894 cast->base.type = dest_type;
900 * Check if a given expression represents the 0 pointer constant.
902 static bool is_null_pointer_constant(const expression_t *expression)
904 /* skip void* cast */
905 if (expression->kind == EXPR_UNARY_CAST
906 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
907 expression = expression->unary.value;
910 /* TODO: not correct yet, should be any constant integer expression
911 * which evaluates to 0 */
912 if (expression->kind != EXPR_CONST)
915 type_t *const type = skip_typeref(expression->base.type);
916 if (!is_type_integer(type))
919 return expression->conste.v.int_value == 0;
923 * Create an implicit cast expression.
925 * @param expression the expression to cast
926 * @param dest_type the destination type
928 static expression_t *create_implicit_cast(expression_t *expression,
931 type_t *const source_type = expression->base.type;
933 if (source_type == dest_type)
936 return create_cast_expression(expression, dest_type);
939 typedef enum assign_error_t {
941 ASSIGN_ERROR_INCOMPATIBLE,
942 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
943 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
944 ASSIGN_WARNING_POINTER_FROM_INT,
945 ASSIGN_WARNING_INT_FROM_POINTER
948 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
949 const expression_t *const right,
951 const source_position_t *source_position)
953 type_t *const orig_type_right = right->base.type;
954 type_t *const type_left = skip_typeref(orig_type_left);
955 type_t *const type_right = skip_typeref(orig_type_right);
960 case ASSIGN_ERROR_INCOMPATIBLE:
961 errorf(source_position,
962 "destination type '%T' in %s is incompatible with type '%T'",
963 orig_type_left, context, orig_type_right);
966 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
967 type_t *points_to_left
968 = skip_typeref(type_left->pointer.points_to);
969 type_t *points_to_right
970 = skip_typeref(type_right->pointer.points_to);
972 /* the left type has all qualifiers from the right type */
973 unsigned missing_qualifiers
974 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
975 warningf(source_position,
976 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
977 orig_type_left, context, orig_type_right, missing_qualifiers);
981 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
982 warningf(source_position,
983 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
984 orig_type_left, context, right, orig_type_right);
987 case ASSIGN_WARNING_POINTER_FROM_INT:
988 warningf(source_position,
989 "%s makes integer '%T' from pointer '%T' without a cast",
990 context, orig_type_left, orig_type_right);
993 case ASSIGN_WARNING_INT_FROM_POINTER:
994 warningf(source_position,
995 "%s makes integer '%T' from pointer '%T' without a cast",
996 context, orig_type_left, orig_type_right);
1000 panic("invalid error value");
1004 /** Implements the rules from § 6.5.16.1 */
1005 static assign_error_t semantic_assign(type_t *orig_type_left,
1006 const expression_t *const right)
1008 type_t *const orig_type_right = right->base.type;
1009 type_t *const type_left = skip_typeref(orig_type_left);
1010 type_t *const type_right = skip_typeref(orig_type_right);
1012 if (is_type_pointer(type_left)) {
1013 if (is_null_pointer_constant(right)) {
1014 return ASSIGN_SUCCESS;
1015 } else if (is_type_pointer(type_right)) {
1016 type_t *points_to_left
1017 = skip_typeref(type_left->pointer.points_to);
1018 type_t *points_to_right
1019 = skip_typeref(type_right->pointer.points_to);
1020 assign_error_t res = ASSIGN_SUCCESS;
1022 /* the left type has all qualifiers from the right type */
1023 unsigned missing_qualifiers
1024 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1025 if (missing_qualifiers != 0) {
1026 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1029 points_to_left = get_unqualified_type(points_to_left);
1030 points_to_right = get_unqualified_type(points_to_right);
1032 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1033 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1037 if (!types_compatible(points_to_left, points_to_right)) {
1038 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1042 } else if (is_type_integer(type_right)) {
1043 return ASSIGN_WARNING_POINTER_FROM_INT;
1045 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1046 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1047 && is_type_pointer(type_right))) {
1048 return ASSIGN_SUCCESS;
1049 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1050 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1051 type_t *const unqual_type_left = get_unqualified_type(type_left);
1052 type_t *const unqual_type_right = get_unqualified_type(type_right);
1053 if (types_compatible(unqual_type_left, unqual_type_right)) {
1054 return ASSIGN_SUCCESS;
1056 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1057 return ASSIGN_WARNING_INT_FROM_POINTER;
1060 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1061 return ASSIGN_SUCCESS;
1063 return ASSIGN_ERROR_INCOMPATIBLE;
1066 static expression_t *parse_constant_expression(void)
1068 /* start parsing at precedence 7 (conditional expression) */
1069 expression_t *result = parse_sub_expression(7);
1071 if (!is_constant_expression(result)) {
1072 errorf(&result->base.source_position,
1073 "expression '%E' is not constant\n", result);
1079 static expression_t *parse_assignment_expression(void)
1081 /* start parsing at precedence 2 (assignment expression) */
1082 return parse_sub_expression(2);
1085 static type_t *make_global_typedef(const char *name, type_t *type)
1087 symbol_t *const symbol = symbol_table_insert(name);
1089 declaration_t *const declaration = allocate_declaration_zero();
1090 declaration->namespc = NAMESPACE_NORMAL;
1091 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1092 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1093 declaration->type = type;
1094 declaration->symbol = symbol;
1095 declaration->source_position = builtin_source_position;
1096 declaration->implicit = true;
1098 record_declaration(declaration, false);
1100 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1101 typedef_type->typedeft.declaration = declaration;
1103 return typedef_type;
1106 static string_t parse_string_literals(void)
1108 assert(token.type == T_STRING_LITERAL);
1109 string_t result = token.v.string;
1113 while (token.type == T_STRING_LITERAL) {
1114 result = concat_strings(&result, &token.v.string);
1121 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1122 [GNU_AK_CONST] = "const",
1123 [GNU_AK_VOLATILE] = "volatile",
1124 [GNU_AK_CDECL] = "cdecl",
1125 [GNU_AK_STDCALL] = "stdcall",
1126 [GNU_AK_FASTCALL] = "fastcall",
1127 [GNU_AK_DEPRECATED] = "deprecated",
1128 [GNU_AK_NOINLINE] = "noinline",
1129 [GNU_AK_NORETURN] = "noreturn",
1130 [GNU_AK_NAKED] = "naked",
1131 [GNU_AK_PURE] = "pure",
1132 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1133 [GNU_AK_MALLOC] = "malloc",
1134 [GNU_AK_WEAK] = "weak",
1135 [GNU_AK_CONSTRUCTOR] = "constructor",
1136 [GNU_AK_DESTRUCTOR] = "destructor",
1137 [GNU_AK_NOTHROW] = "nothrow",
1138 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1139 [GNU_AK_COMMON] = "common",
1140 [GNU_AK_NOCOMMON] = "nocommon",
1141 [GNU_AK_PACKED] = "packed",
1142 [GNU_AK_SHARED] = "shared",
1143 [GNU_AK_NOTSHARED] = "notshared",
1144 [GNU_AK_USED] = "used",
1145 [GNU_AK_UNUSED] = "unused",
1146 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1147 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1148 [GNU_AK_LONGCALL] = "longcall",
1149 [GNU_AK_SHORTCALL] = "shortcall",
1150 [GNU_AK_LONG_CALL] = "long_call",
1151 [GNU_AK_SHORT_CALL] = "short_call",
1152 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1153 [GNU_AK_INTERRUPT] = "interrupt",
1154 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1155 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1156 [GNU_AK_NESTING] = "nesting",
1157 [GNU_AK_NEAR] = "near",
1158 [GNU_AK_FAR] = "far",
1159 [GNU_AK_SIGNAL] = "signal",
1160 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1161 [GNU_AK_TINY_DATA] = "tiny_data",
1162 [GNU_AK_SAVEALL] = "saveall",
1163 [GNU_AK_FLATTEN] = "flatten",
1164 [GNU_AK_SSEREGPARM] = "sseregparm",
1165 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1166 [GNU_AK_RETURN_TWICE] = "return_twice",
1167 [GNU_AK_MAY_ALIAS] = "may_alias",
1168 [GNU_AK_MS_STRUCT] = "ms_struct",
1169 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1170 [GNU_AK_DLLIMPORT] = "dllimport",
1171 [GNU_AK_DLLEXPORT] = "dllexport",
1172 [GNU_AK_ALIGNED] = "aligned",
1173 [GNU_AK_ALIAS] = "alias",
1174 [GNU_AK_SECTION] = "section",
1175 [GNU_AK_FORMAT] = "format",
1176 [GNU_AK_FORMAT_ARG] = "format_arg",
1177 [GNU_AK_WEAKREF] = "weakref",
1178 [GNU_AK_NONNULL] = "nonnull",
1179 [GNU_AK_TLS_MODEL] = "tls_model",
1180 [GNU_AK_VISIBILITY] = "visibility",
1181 [GNU_AK_REGPARM] = "regparm",
1182 [GNU_AK_MODE] = "mode",
1183 [GNU_AK_MODEL] = "model",
1184 [GNU_AK_TRAP_EXIT] = "trap_exit",
1185 [GNU_AK_SP_SWITCH] = "sp_switch",
1186 [GNU_AK_SENTINEL] = "sentinel"
1190 * compare two string, ignoring double underscores on the second.
1192 static int strcmp_underscore(const char *s1, const char *s2)
1194 if (s2[0] == '_' && s2[1] == '_') {
1195 size_t len2 = strlen(s2);
1196 size_t len1 = strlen(s1);
1197 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1198 return strncmp(s1, s2+2, len2-4);
1202 return strcmp(s1, s2);
1206 * Allocate a new gnu temporal attribute.
1208 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1210 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1211 attribute->kind = kind;
1212 attribute->next = NULL;
1213 attribute->invalid = false;
1214 attribute->have_arguments = false;
1220 * parse one constant expression argument.
1222 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1224 expression_t *expression;
1225 add_anchor_token(')');
1226 expression = parse_constant_expression();
1227 rem_anchor_token(')');
1229 attribute->u.argument = fold_constant(expression);
1232 attribute->invalid = true;
1236 * parse a list of constant expressions arguments.
1238 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1240 argument_list_t **list = &attribute->u.arguments;
1241 argument_list_t *entry;
1242 expression_t *expression;
1243 add_anchor_token(')');
1244 add_anchor_token(',');
1246 expression = parse_constant_expression();
1247 entry = obstack_alloc(&temp_obst, sizeof(entry));
1248 entry->argument = fold_constant(expression);
1251 list = &entry->next;
1252 if (token.type != ',')
1256 rem_anchor_token(',');
1257 rem_anchor_token(')');
1261 attribute->invalid = true;
1265 * parse one string literal argument.
1267 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1270 add_anchor_token('(');
1271 if (token.type != T_STRING_LITERAL) {
1272 parse_error_expected("while parsing attribute directive",
1273 T_STRING_LITERAL, NULL);
1276 *string = parse_string_literals();
1277 rem_anchor_token('(');
1281 attribute->invalid = true;
1285 * parse one tls model.
1287 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1289 static const char *const tls_models[] = {
1295 string_t string = { NULL, 0 };
1296 parse_gnu_attribute_string_arg(attribute, &string);
1297 if (string.begin != NULL) {
1298 for(size_t i = 0; i < 4; ++i) {
1299 if (strcmp(tls_models[i], string.begin) == 0) {
1300 attribute->u.value = i;
1304 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1306 attribute->invalid = true;
1310 * parse one tls model.
1312 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1314 static const char *const visibilities[] = {
1320 string_t string = { NULL, 0 };
1321 parse_gnu_attribute_string_arg(attribute, &string);
1322 if (string.begin != NULL) {
1323 for(size_t i = 0; i < 4; ++i) {
1324 if (strcmp(visibilities[i], string.begin) == 0) {
1325 attribute->u.value = i;
1329 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1331 attribute->invalid = true;
1335 * parse one (code) model.
1337 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1339 static const char *const visibilities[] = {
1344 string_t string = { NULL, 0 };
1345 parse_gnu_attribute_string_arg(attribute, &string);
1346 if (string.begin != NULL) {
1347 for(int i = 0; i < 3; ++i) {
1348 if (strcmp(visibilities[i], string.begin) == 0) {
1349 attribute->u.value = i;
1353 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1355 attribute->invalid = true;
1358 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1360 /* TODO: find out what is allowed here... */
1362 /* at least: byte, word, pointer, list of machine modes
1363 * __XXX___ is interpreted as XXX */
1364 add_anchor_token(')');
1366 if (token.type != T_IDENTIFIER) {
1367 expect(T_IDENTIFIER);
1370 /* This isn't really correct, the backend should provide a list of machine
1371 * specific modes (according to gcc philosophy that is...) */
1372 const char *symbol_str = token.v.symbol->string;
1373 if (strcmp_underscore("QI", symbol_str) == 0 ||
1374 strcmp_underscore("byte", symbol_str) == 0) {
1375 attribute->u.akind = ATOMIC_TYPE_CHAR;
1376 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1377 attribute->u.akind = ATOMIC_TYPE_SHORT;
1378 } else if (strcmp_underscore("SI", symbol_str) == 0
1379 || strcmp_underscore("word", symbol_str) == 0
1380 || strcmp_underscore("pointer", symbol_str) == 0) {
1381 attribute->u.akind = ATOMIC_TYPE_INT;
1382 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1383 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1385 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1386 attribute->invalid = true;
1390 rem_anchor_token(')');
1394 attribute->invalid = true;
1398 * parse one interrupt argument.
1400 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1402 static const char *const interrupts[] = {
1409 string_t string = { NULL, 0 };
1410 parse_gnu_attribute_string_arg(attribute, &string);
1411 if (string.begin != NULL) {
1412 for(size_t i = 0; i < 5; ++i) {
1413 if (strcmp(interrupts[i], string.begin) == 0) {
1414 attribute->u.value = i;
1418 errorf(HERE, "'%s' is not an interrupt", string.begin);
1420 attribute->invalid = true;
1424 * parse ( identifier, const expression, const expression )
1426 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1428 static const char *const format_names[] = {
1436 if (token.type != T_IDENTIFIER) {
1437 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1440 const char *name = token.v.symbol->string;
1441 for(i = 0; i < 4; ++i) {
1442 if (strcmp_underscore(format_names[i], name) == 0)
1446 if (warning.attribute)
1447 warningf(HERE, "'%s' is an unrecognized format function type", name);
1452 add_anchor_token(')');
1453 add_anchor_token(',');
1454 parse_constant_expression();
1455 rem_anchor_token(',');
1456 rem_anchor_token('(');
1459 add_anchor_token(')');
1460 parse_constant_expression();
1461 rem_anchor_token('(');
1465 attribute->u.value = true;
1468 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1470 if (!attribute->have_arguments)
1473 /* should have no arguments */
1474 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1475 eat_until_matching_token('(');
1476 /* we have already consumed '(', so we stop before ')', eat it */
1478 attribute->invalid = true;
1482 * Parse one GNU attribute.
1484 * Note that attribute names can be specified WITH or WITHOUT
1485 * double underscores, ie const or __const__.
1487 * The following attributes are parsed without arguments
1512 * no_instrument_function
1513 * warn_unused_result
1530 * externally_visible
1538 * The following attributes are parsed with arguments
1539 * aligned( const expression )
1540 * alias( string literal )
1541 * section( string literal )
1542 * format( identifier, const expression, const expression )
1543 * format_arg( const expression )
1544 * tls_model( string literal )
1545 * visibility( string literal )
1546 * regparm( const expression )
1547 * model( string leteral )
1548 * trap_exit( const expression )
1549 * sp_switch( string literal )
1551 * The following attributes might have arguments
1552 * weak_ref( string literal )
1553 * non_null( const expression // ',' )
1554 * interrupt( string literal )
1555 * sentinel( constant expression )
1557 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1559 gnu_attribute_t *head = *attributes;
1560 gnu_attribute_t *last = *attributes;
1561 decl_modifiers_t modifiers = 0;
1562 gnu_attribute_t *attribute;
1564 eat(T___attribute__);
1568 if (token.type != ')') {
1569 /* find the end of the list */
1571 while (last->next != NULL)
1575 /* non-empty attribute list */
1578 if (token.type == T_const) {
1580 } else if (token.type == T_volatile) {
1582 } else if (token.type == T_cdecl) {
1583 /* __attribute__((cdecl)), WITH ms mode */
1585 } else if (token.type == T_IDENTIFIER) {
1586 const symbol_t *sym = token.v.symbol;
1589 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1596 for(i = 0; i < GNU_AK_LAST; ++i) {
1597 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1600 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1603 if (kind == GNU_AK_LAST) {
1604 if (warning.attribute)
1605 warningf(HERE, "'%s' attribute directive ignored", name);
1607 /* skip possible arguments */
1608 if (token.type == '(') {
1609 eat_until_matching_token(')');
1612 /* check for arguments */
1613 attribute = allocate_gnu_attribute(kind);
1614 if (token.type == '(') {
1616 if (token.type == ')') {
1617 /* empty args are allowed */
1620 attribute->have_arguments = true;
1625 case GNU_AK_VOLATILE:
1630 case GNU_AK_NOCOMMON:
1632 case GNU_AK_NOTSHARED:
1633 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1634 case GNU_AK_WARN_UNUSED_RESULT:
1635 case GNU_AK_LONGCALL:
1636 case GNU_AK_SHORTCALL:
1637 case GNU_AK_LONG_CALL:
1638 case GNU_AK_SHORT_CALL:
1639 case GNU_AK_FUNCTION_VECTOR:
1640 case GNU_AK_INTERRUPT_HANDLER:
1641 case GNU_AK_NMI_HANDLER:
1642 case GNU_AK_NESTING:
1646 case GNU_AK_EIGTHBIT_DATA:
1647 case GNU_AK_TINY_DATA:
1648 case GNU_AK_SAVEALL:
1649 case GNU_AK_FLATTEN:
1650 case GNU_AK_SSEREGPARM:
1651 case GNU_AK_EXTERNALLY_VISIBLE:
1652 case GNU_AK_RETURN_TWICE:
1653 case GNU_AK_MAY_ALIAS:
1654 case GNU_AK_MS_STRUCT:
1655 case GNU_AK_GCC_STRUCT:
1658 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1659 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1660 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1661 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1662 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1663 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1664 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1665 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1666 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1667 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1668 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1669 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1670 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1671 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1672 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1673 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1674 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1676 case GNU_AK_ALIGNED:
1677 /* __align__ may be used without an argument */
1678 if (attribute->have_arguments) {
1679 parse_gnu_attribute_const_arg(attribute);
1683 case GNU_AK_FORMAT_ARG:
1684 case GNU_AK_REGPARM:
1685 case GNU_AK_TRAP_EXIT:
1686 if (!attribute->have_arguments) {
1687 /* should have arguments */
1688 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1689 attribute->invalid = true;
1691 parse_gnu_attribute_const_arg(attribute);
1694 case GNU_AK_SECTION:
1695 case GNU_AK_SP_SWITCH:
1696 if (!attribute->have_arguments) {
1697 /* should have arguments */
1698 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1699 attribute->invalid = true;
1701 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1704 if (!attribute->have_arguments) {
1705 /* should have arguments */
1706 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1707 attribute->invalid = true;
1709 parse_gnu_attribute_format_args(attribute);
1711 case GNU_AK_WEAKREF:
1712 /* may have one string argument */
1713 if (attribute->have_arguments)
1714 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1716 case GNU_AK_NONNULL:
1717 if (attribute->have_arguments)
1718 parse_gnu_attribute_const_arg_list(attribute);
1720 case GNU_AK_TLS_MODEL:
1721 if (!attribute->have_arguments) {
1722 /* should have arguments */
1723 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1725 parse_gnu_attribute_tls_model_arg(attribute);
1727 case GNU_AK_VISIBILITY:
1728 if (!attribute->have_arguments) {
1729 /* should have arguments */
1730 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1732 parse_gnu_attribute_visibility_arg(attribute);
1735 if (!attribute->have_arguments) {
1736 /* should have arguments */
1737 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1739 parse_gnu_attribute_model_arg(attribute);
1743 if (!attribute->have_arguments) {
1744 /* should have arguments */
1745 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1747 parse_gnu_attribute_mode_arg(attribute);
1750 case GNU_AK_INTERRUPT:
1751 /* may have one string argument */
1752 if (attribute->have_arguments)
1753 parse_gnu_attribute_interrupt_arg(attribute);
1755 case GNU_AK_SENTINEL:
1756 /* may have one string argument */
1757 if (attribute->have_arguments)
1758 parse_gnu_attribute_const_arg(attribute);
1761 /* already handled */
1765 check_no_argument(attribute, name);
1768 if (attribute != NULL) {
1770 last->next = attribute;
1773 head = last = attribute;
1777 if (token.type != ',')
1791 * Parse GNU attributes.
1793 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1795 decl_modifiers_t modifiers = 0;
1798 switch(token.type) {
1799 case T___attribute__:
1800 modifiers |= parse_gnu_attribute(attributes);
1806 if (token.type != T_STRING_LITERAL) {
1807 parse_error_expected("while parsing assembler attribute",
1808 T_STRING_LITERAL, NULL);
1809 eat_until_matching_token('(');
1812 parse_string_literals();
1817 case T_cdecl: modifiers |= DM_CDECL; break;
1818 case T__fastcall: modifiers |= DM_FASTCALL; break;
1819 case T__stdcall: modifiers |= DM_STDCALL; break;
1822 /* TODO record modifier */
1823 warningf(HERE, "Ignoring declaration modifier %K", &token);
1827 default: return modifiers;
1834 static designator_t *parse_designation(void)
1836 designator_t *result = NULL;
1837 designator_t *last = NULL;
1840 designator_t *designator;
1841 switch(token.type) {
1843 designator = allocate_ast_zero(sizeof(designator[0]));
1844 designator->source_position = token.source_position;
1846 add_anchor_token(']');
1847 designator->array_index = parse_constant_expression();
1848 rem_anchor_token(']');
1852 designator = allocate_ast_zero(sizeof(designator[0]));
1853 designator->source_position = token.source_position;
1855 if (token.type != T_IDENTIFIER) {
1856 parse_error_expected("while parsing designator",
1857 T_IDENTIFIER, NULL);
1860 designator->symbol = token.v.symbol;
1868 assert(designator != NULL);
1870 last->next = designator;
1872 result = designator;
1880 static initializer_t *initializer_from_string(array_type_t *type,
1881 const string_t *const string)
1883 /* TODO: check len vs. size of array type */
1886 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1887 initializer->string.string = *string;
1892 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1893 wide_string_t *const string)
1895 /* TODO: check len vs. size of array type */
1898 initializer_t *const initializer =
1899 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1900 initializer->wide_string.string = *string;
1906 * Build an initializer from a given expression.
1908 static initializer_t *initializer_from_expression(type_t *orig_type,
1909 expression_t *expression)
1911 /* TODO check that expression is a constant expression */
1913 /* § 6.7.8.14/15 char array may be initialized by string literals */
1914 type_t *type = skip_typeref(orig_type);
1915 type_t *expr_type_orig = expression->base.type;
1916 type_t *expr_type = skip_typeref(expr_type_orig);
1917 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1918 array_type_t *const array_type = &type->array;
1919 type_t *const element_type = skip_typeref(array_type->element_type);
1921 if (element_type->kind == TYPE_ATOMIC) {
1922 atomic_type_kind_t akind = element_type->atomic.akind;
1923 switch (expression->kind) {
1924 case EXPR_STRING_LITERAL:
1925 if (akind == ATOMIC_TYPE_CHAR
1926 || akind == ATOMIC_TYPE_SCHAR
1927 || akind == ATOMIC_TYPE_UCHAR) {
1928 return initializer_from_string(array_type,
1929 &expression->string.value);
1932 case EXPR_WIDE_STRING_LITERAL: {
1933 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1934 if (get_unqualified_type(element_type) == bare_wchar_type) {
1935 return initializer_from_wide_string(array_type,
1936 &expression->wide_string.value);
1946 assign_error_t error = semantic_assign(type, expression);
1947 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1949 report_assign_error(error, type, expression, "initializer",
1950 &expression->base.source_position);
1952 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1953 result->value.value = create_implicit_cast(expression, type);
1959 * Checks if a given expression can be used as an constant initializer.
1961 static bool is_initializer_constant(const expression_t *expression)
1963 return is_constant_expression(expression)
1964 || is_address_constant(expression);
1968 * Parses an scalar initializer.
1970 * § 6.7.8.11; eat {} without warning
1972 static initializer_t *parse_scalar_initializer(type_t *type,
1973 bool must_be_constant)
1975 /* there might be extra {} hierarchies */
1977 if (token.type == '{') {
1978 warningf(HERE, "extra curly braces around scalar initializer");
1982 } while (token.type == '{');
1985 expression_t *expression = parse_assignment_expression();
1986 if (must_be_constant && !is_initializer_constant(expression)) {
1987 errorf(&expression->base.source_position,
1988 "Initialisation expression '%E' is not constant\n",
1992 initializer_t *initializer = initializer_from_expression(type, expression);
1994 if (initializer == NULL) {
1995 errorf(&expression->base.source_position,
1996 "expression '%E' (type '%T') doesn't match expected type '%T'",
1997 expression, expression->base.type, type);
2002 bool additional_warning_displayed = false;
2003 while (braces > 0) {
2004 if (token.type == ',') {
2007 if (token.type != '}') {
2008 if (!additional_warning_displayed) {
2009 warningf(HERE, "additional elements in scalar initializer");
2010 additional_warning_displayed = true;
2021 * An entry in the type path.
2023 typedef struct type_path_entry_t type_path_entry_t;
2024 struct type_path_entry_t {
2025 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2027 size_t index; /**< For array types: the current index. */
2028 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2033 * A type path expression a position inside compound or array types.
2035 typedef struct type_path_t type_path_t;
2036 struct type_path_t {
2037 type_path_entry_t *path; /**< An flexible array containing the current path. */
2038 type_t *top_type; /**< type of the element the path points */
2039 size_t max_index; /**< largest index in outermost array */
2043 * Prints a type path for debugging.
2045 static __attribute__((unused)) void debug_print_type_path(
2046 const type_path_t *path)
2048 size_t len = ARR_LEN(path->path);
2050 for(size_t i = 0; i < len; ++i) {
2051 const type_path_entry_t *entry = & path->path[i];
2053 type_t *type = skip_typeref(entry->type);
2054 if (is_type_compound(type)) {
2055 /* in gcc mode structs can have no members */
2056 if (entry->v.compound_entry == NULL) {
2060 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2061 } else if (is_type_array(type)) {
2062 fprintf(stderr, "[%zu]", entry->v.index);
2064 fprintf(stderr, "-INVALID-");
2067 if (path->top_type != NULL) {
2068 fprintf(stderr, " (");
2069 print_type(path->top_type);
2070 fprintf(stderr, ")");
2075 * Return the top type path entry, ie. in a path
2076 * (type).a.b returns the b.
2078 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2080 size_t len = ARR_LEN(path->path);
2082 return &path->path[len-1];
2086 * Enlarge the type path by an (empty) element.
2088 static type_path_entry_t *append_to_type_path(type_path_t *path)
2090 size_t len = ARR_LEN(path->path);
2091 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2093 type_path_entry_t *result = & path->path[len];
2094 memset(result, 0, sizeof(result[0]));
2099 * Descending into a sub-type. Enter the scope of the current
2102 static void descend_into_subtype(type_path_t *path)
2104 type_t *orig_top_type = path->top_type;
2105 type_t *top_type = skip_typeref(orig_top_type);
2107 assert(is_type_compound(top_type) || is_type_array(top_type));
2109 type_path_entry_t *top = append_to_type_path(path);
2110 top->type = top_type;
2112 if (is_type_compound(top_type)) {
2113 declaration_t *declaration = top_type->compound.declaration;
2114 declaration_t *entry = declaration->scope.declarations;
2115 top->v.compound_entry = entry;
2117 if (entry != NULL) {
2118 path->top_type = entry->type;
2120 path->top_type = NULL;
2123 assert(is_type_array(top_type));
2126 path->top_type = top_type->array.element_type;
2131 * Pop an entry from the given type path, ie. returning from
2132 * (type).a.b to (type).a
2134 static void ascend_from_subtype(type_path_t *path)
2136 type_path_entry_t *top = get_type_path_top(path);
2138 path->top_type = top->type;
2140 size_t len = ARR_LEN(path->path);
2141 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2145 * Pop entries from the given type path until the given
2146 * path level is reached.
2148 static void ascend_to(type_path_t *path, size_t top_path_level)
2150 size_t len = ARR_LEN(path->path);
2152 while (len > top_path_level) {
2153 ascend_from_subtype(path);
2154 len = ARR_LEN(path->path);
2158 static bool walk_designator(type_path_t *path, const designator_t *designator,
2159 bool used_in_offsetof)
2161 for( ; designator != NULL; designator = designator->next) {
2162 type_path_entry_t *top = get_type_path_top(path);
2163 type_t *orig_type = top->type;
2165 type_t *type = skip_typeref(orig_type);
2167 if (designator->symbol != NULL) {
2168 symbol_t *symbol = designator->symbol;
2169 if (!is_type_compound(type)) {
2170 if (is_type_valid(type)) {
2171 errorf(&designator->source_position,
2172 "'.%Y' designator used for non-compound type '%T'",
2178 declaration_t *declaration = type->compound.declaration;
2179 declaration_t *iter = declaration->scope.declarations;
2180 for( ; iter != NULL; iter = iter->next) {
2181 if (iter->symbol == symbol) {
2186 errorf(&designator->source_position,
2187 "'%T' has no member named '%Y'", orig_type, symbol);
2190 if (used_in_offsetof) {
2191 type_t *real_type = skip_typeref(iter->type);
2192 if (real_type->kind == TYPE_BITFIELD) {
2193 errorf(&designator->source_position,
2194 "offsetof designator '%Y' may not specify bitfield",
2200 top->type = orig_type;
2201 top->v.compound_entry = iter;
2202 orig_type = iter->type;
2204 expression_t *array_index = designator->array_index;
2205 assert(designator->array_index != NULL);
2207 if (!is_type_array(type)) {
2208 if (is_type_valid(type)) {
2209 errorf(&designator->source_position,
2210 "[%E] designator used for non-array type '%T'",
2211 array_index, orig_type);
2215 if (!is_type_valid(array_index->base.type)) {
2219 long index = fold_constant(array_index);
2220 if (!used_in_offsetof) {
2222 errorf(&designator->source_position,
2223 "array index [%E] must be positive", array_index);
2226 if (type->array.size_constant == true) {
2227 long array_size = type->array.size;
2228 if (index >= array_size) {
2229 errorf(&designator->source_position,
2230 "designator [%E] (%d) exceeds array size %d",
2231 array_index, index, array_size);
2237 top->type = orig_type;
2238 top->v.index = (size_t) index;
2239 orig_type = type->array.element_type;
2241 path->top_type = orig_type;
2243 if (designator->next != NULL) {
2244 descend_into_subtype(path);
2253 static void advance_current_object(type_path_t *path, size_t top_path_level)
2255 type_path_entry_t *top = get_type_path_top(path);
2257 type_t *type = skip_typeref(top->type);
2258 if (is_type_union(type)) {
2259 /* in unions only the first element is initialized */
2260 top->v.compound_entry = NULL;
2261 } else if (is_type_struct(type)) {
2262 declaration_t *entry = top->v.compound_entry;
2264 entry = entry->next;
2265 top->v.compound_entry = entry;
2266 if (entry != NULL) {
2267 path->top_type = entry->type;
2271 assert(is_type_array(type));
2275 if (!type->array.size_constant || top->v.index < type->array.size) {
2280 /* we're past the last member of the current sub-aggregate, try if we
2281 * can ascend in the type hierarchy and continue with another subobject */
2282 size_t len = ARR_LEN(path->path);
2284 if (len > top_path_level) {
2285 ascend_from_subtype(path);
2286 advance_current_object(path, top_path_level);
2288 path->top_type = NULL;
2293 * skip until token is found.
2295 static void skip_until(int type)
2297 while (token.type != type) {
2298 if (token.type == T_EOF)
2305 * skip any {...} blocks until a closing bracket is reached.
2307 static void skip_initializers(void)
2309 if (token.type == '{')
2312 while (token.type != '}') {
2313 if (token.type == T_EOF)
2315 if (token.type == '{') {
2323 static initializer_t *create_empty_initializer(void)
2325 static initializer_t empty_initializer
2326 = { .list = { { INITIALIZER_LIST }, 0 } };
2327 return &empty_initializer;
2331 * Parse a part of an initialiser for a struct or union,
2333 static initializer_t *parse_sub_initializer(type_path_t *path,
2334 type_t *outer_type, size_t top_path_level,
2335 parse_initializer_env_t *env)
2337 if (token.type == '}') {
2338 /* empty initializer */
2339 return create_empty_initializer();
2342 type_t *orig_type = path->top_type;
2343 type_t *type = NULL;
2345 if (orig_type == NULL) {
2346 /* We are initializing an empty compound. */
2348 type = skip_typeref(orig_type);
2350 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2351 * initializers in this case. */
2352 if (!is_type_valid(type)) {
2353 skip_initializers();
2354 return create_empty_initializer();
2358 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2361 designator_t *designator = NULL;
2362 if (token.type == '.' || token.type == '[') {
2363 designator = parse_designation();
2364 goto finish_designator;
2365 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2366 /* GNU-style designator ("identifier: value") */
2367 designator = allocate_ast_zero(sizeof(designator[0]));
2368 designator->source_position = token.source_position;
2369 designator->symbol = token.v.symbol;
2374 /* reset path to toplevel, evaluate designator from there */
2375 ascend_to(path, top_path_level);
2376 if (!walk_designator(path, designator, false)) {
2377 /* can't continue after designation error */
2381 initializer_t *designator_initializer
2382 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2383 designator_initializer->designator.designator = designator;
2384 ARR_APP1(initializer_t*, initializers, designator_initializer);
2386 orig_type = path->top_type;
2387 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2392 if (token.type == '{') {
2393 if (type != NULL && is_type_scalar(type)) {
2394 sub = parse_scalar_initializer(type, env->must_be_constant);
2398 if (env->declaration != NULL) {
2399 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2400 env->declaration->symbol);
2402 errorf(HERE, "extra brace group at end of initializer");
2405 descend_into_subtype(path);
2407 add_anchor_token('}');
2408 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2410 rem_anchor_token('}');
2413 ascend_from_subtype(path);
2417 goto error_parse_next;
2421 /* must be an expression */
2422 expression_t *expression = parse_assignment_expression();
2424 if (env->must_be_constant && !is_initializer_constant(expression)) {
2425 errorf(&expression->base.source_position,
2426 "Initialisation expression '%E' is not constant\n",
2431 /* we are already outside, ... */
2435 /* handle { "string" } special case */
2436 if ((expression->kind == EXPR_STRING_LITERAL
2437 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2438 && outer_type != NULL) {
2439 sub = initializer_from_expression(outer_type, expression);
2441 if (token.type == ',') {
2444 if (token.type != '}') {
2445 warningf(HERE, "excessive elements in initializer for type '%T'",
2448 /* TODO: eat , ... */
2453 /* descend into subtypes until expression matches type */
2455 orig_type = path->top_type;
2456 type = skip_typeref(orig_type);
2458 sub = initializer_from_expression(orig_type, expression);
2462 if (!is_type_valid(type)) {
2465 if (is_type_scalar(type)) {
2466 errorf(&expression->base.source_position,
2467 "expression '%E' doesn't match expected type '%T'",
2468 expression, orig_type);
2472 descend_into_subtype(path);
2476 /* update largest index of top array */
2477 const type_path_entry_t *first = &path->path[0];
2478 type_t *first_type = first->type;
2479 first_type = skip_typeref(first_type);
2480 if (is_type_array(first_type)) {
2481 size_t index = first->v.index;
2482 if (index > path->max_index)
2483 path->max_index = index;
2487 /* append to initializers list */
2488 ARR_APP1(initializer_t*, initializers, sub);
2491 if (env->declaration != NULL)
2492 warningf(HERE, "excess elements in struct initializer for '%Y'",
2493 env->declaration->symbol);
2495 warningf(HERE, "excess elements in struct initializer");
2499 if (token.type == '}') {
2503 if (token.type == '}') {
2508 /* advance to the next declaration if we are not at the end */
2509 advance_current_object(path, top_path_level);
2510 orig_type = path->top_type;
2511 if (orig_type != NULL)
2512 type = skip_typeref(orig_type);
2518 size_t len = ARR_LEN(initializers);
2519 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2520 initializer_t *result = allocate_ast_zero(size);
2521 result->kind = INITIALIZER_LIST;
2522 result->list.len = len;
2523 memcpy(&result->list.initializers, initializers,
2524 len * sizeof(initializers[0]));
2526 DEL_ARR_F(initializers);
2527 ascend_to(path, top_path_level+1);
2532 skip_initializers();
2533 DEL_ARR_F(initializers);
2534 ascend_to(path, top_path_level+1);
2539 * Parses an initializer. Parsers either a compound literal
2540 * (env->declaration == NULL) or an initializer of a declaration.
2542 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2544 type_t *type = skip_typeref(env->type);
2545 initializer_t *result = NULL;
2548 if (is_type_scalar(type)) {
2549 result = parse_scalar_initializer(type, env->must_be_constant);
2550 } else if (token.type == '{') {
2554 memset(&path, 0, sizeof(path));
2555 path.top_type = env->type;
2556 path.path = NEW_ARR_F(type_path_entry_t, 0);
2558 descend_into_subtype(&path);
2560 add_anchor_token('}');
2561 result = parse_sub_initializer(&path, env->type, 1, env);
2562 rem_anchor_token('}');
2564 max_index = path.max_index;
2565 DEL_ARR_F(path.path);
2569 /* parse_scalar_initializer() also works in this case: we simply
2570 * have an expression without {} around it */
2571 result = parse_scalar_initializer(type, env->must_be_constant);
2574 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2575 * the array type size */
2576 if (is_type_array(type) && type->array.size_expression == NULL
2577 && result != NULL) {
2579 switch (result->kind) {
2580 case INITIALIZER_LIST:
2581 size = max_index + 1;
2584 case INITIALIZER_STRING:
2585 size = result->string.string.size;
2588 case INITIALIZER_WIDE_STRING:
2589 size = result->wide_string.string.size;
2592 case INITIALIZER_DESIGNATOR:
2593 case INITIALIZER_VALUE:
2594 /* can happen for parse errors */
2599 internal_errorf(HERE, "invalid initializer type");
2602 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2603 cnst->base.type = type_size_t;
2604 cnst->conste.v.int_value = size;
2606 type_t *new_type = duplicate_type(type);
2608 new_type->array.size_expression = cnst;
2609 new_type->array.size_constant = true;
2610 new_type->array.size = size;
2611 env->type = new_type;
2619 static declaration_t *append_declaration(declaration_t *declaration);
2621 static declaration_t *parse_compound_type_specifier(bool is_struct)
2623 gnu_attribute_t *attributes = NULL;
2624 decl_modifiers_t modifiers = 0;
2631 symbol_t *symbol = NULL;
2632 declaration_t *declaration = NULL;
2634 if (token.type == T___attribute__) {
2635 modifiers |= parse_attributes(&attributes);
2638 if (token.type == T_IDENTIFIER) {
2639 symbol = token.v.symbol;
2642 namespace_t const namespc =
2643 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2644 declaration = get_declaration(symbol, namespc);
2645 if (declaration != NULL) {
2646 if (declaration->parent_scope != scope &&
2647 (token.type == '{' || token.type == ';')) {
2649 } else if (declaration->init.complete &&
2650 token.type == '{') {
2651 assert(symbol != NULL);
2652 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2653 is_struct ? "struct" : "union", symbol,
2654 &declaration->source_position);
2655 declaration->scope.declarations = NULL;
2658 } else if (token.type != '{') {
2660 parse_error_expected("while parsing struct type specifier",
2661 T_IDENTIFIER, '{', NULL);
2663 parse_error_expected("while parsing union type specifier",
2664 T_IDENTIFIER, '{', NULL);
2670 if (declaration == NULL) {
2671 declaration = allocate_declaration_zero();
2672 declaration->namespc =
2673 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2674 declaration->source_position = token.source_position;
2675 declaration->symbol = symbol;
2676 declaration->parent_scope = scope;
2677 if (symbol != NULL) {
2678 environment_push(declaration);
2680 append_declaration(declaration);
2683 if (token.type == '{') {
2684 declaration->init.complete = true;
2686 parse_compound_type_entries(declaration);
2687 modifiers |= parse_attributes(&attributes);
2690 declaration->modifiers |= modifiers;
2694 static void parse_enum_entries(type_t *const enum_type)
2698 if (token.type == '}') {
2700 errorf(HERE, "empty enum not allowed");
2704 add_anchor_token('}');
2706 if (token.type != T_IDENTIFIER) {
2707 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2709 rem_anchor_token('}');
2713 declaration_t *const entry = allocate_declaration_zero();
2714 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2715 entry->type = enum_type;
2716 entry->symbol = token.v.symbol;
2717 entry->source_position = token.source_position;
2720 if (token.type == '=') {
2722 expression_t *value = parse_constant_expression();
2724 value = create_implicit_cast(value, enum_type);
2725 entry->init.enum_value = value;
2730 record_declaration(entry, false);
2732 if (token.type != ',')
2735 } while (token.type != '}');
2736 rem_anchor_token('}');
2744 static type_t *parse_enum_specifier(void)
2746 gnu_attribute_t *attributes = NULL;
2747 declaration_t *declaration;
2751 if (token.type == T_IDENTIFIER) {
2752 symbol = token.v.symbol;
2755 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2756 } else if (token.type != '{') {
2757 parse_error_expected("while parsing enum type specifier",
2758 T_IDENTIFIER, '{', NULL);
2765 if (declaration == NULL) {
2766 declaration = allocate_declaration_zero();
2767 declaration->namespc = NAMESPACE_ENUM;
2768 declaration->source_position = token.source_position;
2769 declaration->symbol = symbol;
2770 declaration->parent_scope = scope;
2773 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2774 type->enumt.declaration = declaration;
2776 if (token.type == '{') {
2777 if (declaration->init.complete) {
2778 errorf(HERE, "multiple definitions of enum %Y", symbol);
2780 if (symbol != NULL) {
2781 environment_push(declaration);
2783 append_declaration(declaration);
2784 declaration->init.complete = true;
2786 parse_enum_entries(type);
2787 parse_attributes(&attributes);
2794 * if a symbol is a typedef to another type, return true
2796 static bool is_typedef_symbol(symbol_t *symbol)
2798 const declaration_t *const declaration =
2799 get_declaration(symbol, NAMESPACE_NORMAL);
2801 declaration != NULL &&
2802 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2805 static type_t *parse_typeof(void)
2812 add_anchor_token(')');
2814 expression_t *expression = NULL;
2817 switch(token.type) {
2818 case T___extension__:
2819 /* This can be a prefix to a typename or an expression. We simply eat
2823 } while (token.type == T___extension__);
2827 if (is_typedef_symbol(token.v.symbol)) {
2828 type = parse_typename();
2830 expression = parse_expression();
2831 type = expression->base.type;
2836 type = parse_typename();
2840 expression = parse_expression();
2841 type = expression->base.type;
2845 rem_anchor_token(')');
2848 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2849 typeof_type->typeoft.expression = expression;
2850 typeof_type->typeoft.typeof_type = type;
2857 typedef enum specifiers_t {
2858 SPECIFIER_SIGNED = 1 << 0,
2859 SPECIFIER_UNSIGNED = 1 << 1,
2860 SPECIFIER_LONG = 1 << 2,
2861 SPECIFIER_INT = 1 << 3,
2862 SPECIFIER_DOUBLE = 1 << 4,
2863 SPECIFIER_CHAR = 1 << 5,
2864 SPECIFIER_SHORT = 1 << 6,
2865 SPECIFIER_LONG_LONG = 1 << 7,
2866 SPECIFIER_FLOAT = 1 << 8,
2867 SPECIFIER_BOOL = 1 << 9,
2868 SPECIFIER_VOID = 1 << 10,
2869 SPECIFIER_INT8 = 1 << 11,
2870 SPECIFIER_INT16 = 1 << 12,
2871 SPECIFIER_INT32 = 1 << 13,
2872 SPECIFIER_INT64 = 1 << 14,
2873 SPECIFIER_INT128 = 1 << 15,
2874 SPECIFIER_COMPLEX = 1 << 16,
2875 SPECIFIER_IMAGINARY = 1 << 17,
2878 static type_t *create_builtin_type(symbol_t *const symbol,
2879 type_t *const real_type)
2881 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2882 type->builtin.symbol = symbol;
2883 type->builtin.real_type = real_type;
2885 type_t *result = typehash_insert(type);
2886 if (type != result) {
2893 static type_t *get_typedef_type(symbol_t *symbol)
2895 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2896 if (declaration == NULL ||
2897 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2900 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2901 type->typedeft.declaration = declaration;
2907 * check for the allowed MS alignment values.
2909 static bool check_alignment_value(long long intvalue)
2911 if (intvalue < 1 || intvalue > 8192) {
2912 errorf(HERE, "illegal alignment value");
2915 unsigned v = (unsigned)intvalue;
2916 for(unsigned i = 1; i <= 8192; i += i) {
2920 errorf(HERE, "alignment must be power of two");
2924 #define DET_MOD(name, tag) do { \
2925 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2926 *modifiers |= tag; \
2929 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2931 decl_modifiers_t *modifiers = &specifiers->modifiers;
2934 if (token.type == T_restrict) {
2936 DET_MOD(restrict, DM_RESTRICT);
2938 } else if (token.type != T_IDENTIFIER)
2940 symbol_t *symbol = token.v.symbol;
2941 if (symbol == sym_align) {
2944 if (token.type != T_INTEGER)
2946 if (check_alignment_value(token.v.intvalue)) {
2947 if (specifiers->alignment != 0)
2948 warningf(HERE, "align used more than once");
2949 specifiers->alignment = (unsigned char)token.v.intvalue;
2953 } else if (symbol == sym_allocate) {
2956 if (token.type != T_IDENTIFIER)
2958 (void)token.v.symbol;
2960 } else if (symbol == sym_dllimport) {
2962 DET_MOD(dllimport, DM_DLLIMPORT);
2963 } else if (symbol == sym_dllexport) {
2965 DET_MOD(dllexport, DM_DLLEXPORT);
2966 } else if (symbol == sym_thread) {
2968 DET_MOD(thread, DM_THREAD);
2969 } else if (symbol == sym_naked) {
2971 DET_MOD(naked, DM_NAKED);
2972 } else if (symbol == sym_noinline) {
2974 DET_MOD(noinline, DM_NOINLINE);
2975 } else if (symbol == sym_noreturn) {
2977 DET_MOD(noreturn, DM_NORETURN);
2978 } else if (symbol == sym_nothrow) {
2980 DET_MOD(nothrow, DM_NOTHROW);
2981 } else if (symbol == sym_novtable) {
2983 DET_MOD(novtable, DM_NOVTABLE);
2984 } else if (symbol == sym_property) {
2988 bool is_get = false;
2989 if (token.type != T_IDENTIFIER)
2991 if (token.v.symbol == sym_get) {
2993 } else if (token.v.symbol == sym_put) {
2995 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3000 if (token.type != T_IDENTIFIER)
3003 if (specifiers->get_property_sym != NULL) {
3004 errorf(HERE, "get property name already specified");
3006 specifiers->get_property_sym = token.v.symbol;
3009 if (specifiers->put_property_sym != NULL) {
3010 errorf(HERE, "put property name already specified");
3012 specifiers->put_property_sym = token.v.symbol;
3016 if (token.type == ',') {
3023 } else if (symbol == sym_selectany) {
3025 DET_MOD(selectany, DM_SELECTANY);
3026 } else if (symbol == sym_uuid) {
3029 if (token.type != T_STRING_LITERAL)
3033 } else if (symbol == sym_deprecated) {
3035 if (specifiers->deprecated != 0)
3036 warningf(HERE, "deprecated used more than once");
3037 specifiers->deprecated = 1;
3038 if (token.type == '(') {
3040 if (token.type == T_STRING_LITERAL) {
3041 specifiers->deprecated_string = token.v.string.begin;
3044 errorf(HERE, "string literal expected");
3048 } else if (symbol == sym_noalias) {
3050 DET_MOD(noalias, DM_NOALIAS);
3052 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3054 if (token.type == '(')
3058 if (token.type == ',')
3065 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3067 declaration_t *const decl = allocate_declaration_zero();
3068 decl->source_position = *HERE;
3069 decl->declared_storage_class = storage_class;
3070 decl->storage_class =
3071 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3072 storage_class : STORAGE_CLASS_AUTO;
3073 decl->symbol = symbol;
3074 decl->implicit = true;
3075 record_declaration(decl, false);
3080 * Finish the construction of a struct type by calculating
3081 * its size, offsets, alignment.
3083 static void finish_struct_type(compound_type_t *type) {
3084 if (type->declaration == NULL)
3086 declaration_t *struct_decl = type->declaration;
3087 if (! struct_decl->init.complete)
3092 il_alignment_t alignment = 1;
3093 bool need_pad = false;
3095 declaration_t *entry = struct_decl->scope.declarations;
3096 for (; entry != NULL; entry = entry->next) {
3097 if (entry->namespc != NAMESPACE_NORMAL)
3100 type_t *m_type = skip_typeref(entry->type);
3101 il_alignment_t m_alignment = m_type->base.alignment;
3103 new_size = (size + m_alignment - 1) & -m_alignment;
3104 if (m_alignment > alignment)
3105 alignment = m_alignment;
3106 if (new_size > size)
3108 entry->offset = new_size;
3109 size = new_size + m_type->base.size;
3111 if (type->base.alignment != 0) {
3112 alignment = type->base.alignment;
3115 new_size = (size + alignment - 1) & -alignment;
3116 if (new_size > size)
3119 if (warning.padded && need_pad) {
3120 warningf(&struct_decl->source_position,
3121 "'%#T' needs padding", type, struct_decl->symbol);
3123 if (warning.packed && !need_pad) {
3124 warningf(&struct_decl->source_position,
3125 "superfluous packed attribute on '%#T'",
3126 type, struct_decl->symbol);
3129 type->base.size = new_size;
3130 type->base.alignment = alignment;
3134 * Finish the construction of an union type by calculating
3135 * its size and alignment.
3137 static void finish_union_type(compound_type_t *type) {
3138 if (type->declaration == NULL)
3140 declaration_t *union_decl = type->declaration;
3141 if (! union_decl->init.complete)
3145 il_alignment_t alignment = 1;
3147 declaration_t *entry = union_decl->scope.declarations;
3148 for (; entry != NULL; entry = entry->next) {
3149 if (entry->namespc != NAMESPACE_NORMAL)
3152 type_t *m_type = skip_typeref(entry->type);
3155 if (m_type->base.size > size)
3156 size = m_type->base.size;
3157 if (m_type->base.alignment > alignment)
3158 alignment = m_type->base.alignment;
3160 if (type->base.alignment != 0) {
3161 alignment = type->base.alignment;
3163 size = (size + alignment - 1) & -alignment;
3164 type->base.size = size;
3165 type->base.alignment = alignment;
3168 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3170 type_t *type = NULL;
3171 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3172 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3173 unsigned type_specifiers = 0;
3174 bool newtype = false;
3175 bool saw_error = false;
3177 specifiers->source_position = token.source_position;
3180 specifiers->modifiers
3181 |= parse_attributes(&specifiers->gnu_attributes);
3182 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3183 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3185 switch(token.type) {
3188 #define MATCH_STORAGE_CLASS(token, class) \
3190 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3191 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3193 specifiers->declared_storage_class = class; \
3197 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3198 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3199 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3200 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3201 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3206 add_anchor_token(')');
3207 parse_microsoft_extended_decl_modifier(specifiers);
3208 rem_anchor_token(')');
3213 switch (specifiers->declared_storage_class) {
3214 case STORAGE_CLASS_NONE:
3215 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3218 case STORAGE_CLASS_EXTERN:
3219 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3222 case STORAGE_CLASS_STATIC:
3223 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3227 errorf(HERE, "multiple storage classes in declaration specifiers");
3233 /* type qualifiers */
3234 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3236 qualifiers |= qualifier; \
3240 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3241 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3242 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3243 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3244 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3245 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3246 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3247 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3249 case T___extension__:
3254 /* type specifiers */
3255 #define MATCH_SPECIFIER(token, specifier, name) \
3258 if (type_specifiers & specifier) { \
3259 errorf(HERE, "multiple " name " type specifiers given"); \
3261 type_specifiers |= specifier; \
3265 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3266 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3267 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3268 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3269 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3270 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3271 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3272 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3273 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3274 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3275 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3276 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3277 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3278 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3279 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3280 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3282 case T__forceinline:
3283 /* only in microsoft mode */
3284 specifiers->modifiers |= DM_FORCEINLINE;
3289 specifiers->is_inline = true;
3294 if (type_specifiers & SPECIFIER_LONG_LONG) {
3295 errorf(HERE, "multiple type specifiers given");
3296 } else if (type_specifiers & SPECIFIER_LONG) {
3297 type_specifiers |= SPECIFIER_LONG_LONG;
3299 type_specifiers |= SPECIFIER_LONG;
3304 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3306 type->compound.declaration = parse_compound_type_specifier(true);
3307 finish_struct_type(&type->compound);
3311 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3312 type->compound.declaration = parse_compound_type_specifier(false);
3313 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3314 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3316 finish_union_type(&type->compound);
3319 type = parse_enum_specifier();
3322 type = parse_typeof();
3324 case T___builtin_va_list:
3325 type = duplicate_type(type_valist);
3329 case T_IDENTIFIER: {
3330 /* only parse identifier if we haven't found a type yet */
3331 if (type != NULL || type_specifiers != 0) {
3332 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3333 * declaration, so it doesn't generate errors about expecting '(' or
3335 switch (look_ahead(1)->type) {
3342 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3345 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3350 goto finish_specifiers;
3354 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3355 if (typedef_type == NULL) {
3356 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3357 * declaration, so it doesn't generate 'implicit int' followed by more
3358 * errors later on. */
3359 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3364 errorf(HERE, "%K does not name a type", &token);
3366 declaration_t *const decl =
3367 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3369 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3370 type->typedeft.declaration = decl;
3374 if (la1_type == '*')
3375 goto finish_specifiers;
3380 goto finish_specifiers;
3385 type = typedef_type;
3389 /* function specifier */
3391 goto finish_specifiers;
3396 if (type == NULL || (saw_error && type_specifiers != 0)) {
3397 atomic_type_kind_t atomic_type;
3399 /* match valid basic types */
3400 switch(type_specifiers) {
3401 case SPECIFIER_VOID:
3402 atomic_type = ATOMIC_TYPE_VOID;
3404 case SPECIFIER_CHAR:
3405 atomic_type = ATOMIC_TYPE_CHAR;
3407 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3408 atomic_type = ATOMIC_TYPE_SCHAR;
3410 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3411 atomic_type = ATOMIC_TYPE_UCHAR;
3413 case SPECIFIER_SHORT:
3414 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3415 case SPECIFIER_SHORT | SPECIFIER_INT:
3416 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3417 atomic_type = ATOMIC_TYPE_SHORT;
3419 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3420 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3421 atomic_type = ATOMIC_TYPE_USHORT;
3424 case SPECIFIER_SIGNED:
3425 case SPECIFIER_SIGNED | SPECIFIER_INT:
3426 atomic_type = ATOMIC_TYPE_INT;
3428 case SPECIFIER_UNSIGNED:
3429 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3430 atomic_type = ATOMIC_TYPE_UINT;
3432 case SPECIFIER_LONG:
3433 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3434 case SPECIFIER_LONG | SPECIFIER_INT:
3435 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3436 atomic_type = ATOMIC_TYPE_LONG;
3438 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3439 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3440 atomic_type = ATOMIC_TYPE_ULONG;
3443 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3444 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3445 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3446 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3448 atomic_type = ATOMIC_TYPE_LONGLONG;
3449 goto warn_about_long_long;
3451 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3452 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3454 atomic_type = ATOMIC_TYPE_ULONGLONG;
3455 warn_about_long_long:
3456 if (warning.long_long) {
3457 warningf(&specifiers->source_position,
3458 "ISO C90 does not support 'long long'");
3462 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3463 atomic_type = unsigned_int8_type_kind;
3466 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3467 atomic_type = unsigned_int16_type_kind;
3470 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3471 atomic_type = unsigned_int32_type_kind;
3474 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3475 atomic_type = unsigned_int64_type_kind;
3478 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3479 atomic_type = unsigned_int128_type_kind;
3482 case SPECIFIER_INT8:
3483 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3484 atomic_type = int8_type_kind;
3487 case SPECIFIER_INT16:
3488 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3489 atomic_type = int16_type_kind;
3492 case SPECIFIER_INT32:
3493 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3494 atomic_type = int32_type_kind;
3497 case SPECIFIER_INT64:
3498 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3499 atomic_type = int64_type_kind;
3502 case SPECIFIER_INT128:
3503 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3504 atomic_type = int128_type_kind;
3507 case SPECIFIER_FLOAT:
3508 atomic_type = ATOMIC_TYPE_FLOAT;
3510 case SPECIFIER_DOUBLE:
3511 atomic_type = ATOMIC_TYPE_DOUBLE;
3513 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3514 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3516 case SPECIFIER_BOOL:
3517 atomic_type = ATOMIC_TYPE_BOOL;
3519 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3520 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3521 atomic_type = ATOMIC_TYPE_FLOAT;
3523 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3524 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3525 atomic_type = ATOMIC_TYPE_DOUBLE;
3527 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3528 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3529 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3532 /* invalid specifier combination, give an error message */
3533 if (type_specifiers == 0) {
3535 specifiers->type = type_error_type;
3540 if (warning.implicit_int) {
3541 warningf(HERE, "no type specifiers in declaration, using 'int'");
3543 atomic_type = ATOMIC_TYPE_INT;
3546 errorf(HERE, "no type specifiers given in declaration");
3548 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3549 (type_specifiers & SPECIFIER_UNSIGNED)) {
3550 errorf(HERE, "signed and unsigned specifiers given");
3551 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3552 errorf(HERE, "only integer types can be signed or unsigned");
3554 errorf(HERE, "multiple datatypes in declaration");
3556 atomic_type = ATOMIC_TYPE_INVALID;
3559 if (type_specifiers & SPECIFIER_COMPLEX &&
3560 atomic_type != ATOMIC_TYPE_INVALID) {
3561 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3562 type->complex.akind = atomic_type;
3563 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3564 atomic_type != ATOMIC_TYPE_INVALID) {
3565 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3566 type->imaginary.akind = atomic_type;
3568 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3569 type->atomic.akind = atomic_type;
3572 } else if (type_specifiers != 0) {
3573 errorf(HERE, "multiple datatypes in declaration");
3576 /* FIXME: check type qualifiers here */
3578 type->base.qualifiers = qualifiers;
3579 type->base.modifiers = modifiers;
3581 type_t *result = typehash_insert(type);
3582 if (newtype && result != type) {
3586 specifiers->type = result;
3591 static type_qualifiers_t parse_type_qualifiers(void)
3593 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3596 switch(token.type) {
3597 /* type qualifiers */
3598 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3599 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3600 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3601 /* microsoft extended type modifiers */
3602 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3603 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3604 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3605 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3606 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3614 static declaration_t *parse_identifier_list(void)
3616 declaration_t *declarations = NULL;
3617 declaration_t *last_declaration = NULL;
3619 declaration_t *const declaration = allocate_declaration_zero();
3620 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3621 declaration->source_position = token.source_position;
3622 declaration->symbol = token.v.symbol;
3625 if (last_declaration != NULL) {
3626 last_declaration->next = declaration;
3628 declarations = declaration;
3630 last_declaration = declaration;
3632 if (token.type != ',') {
3636 } while (token.type == T_IDENTIFIER);
3638 return declarations;
3641 static type_t *automatic_type_conversion(type_t *orig_type);
3643 static void semantic_parameter(declaration_t *declaration)
3645 /* TODO: improve error messages */
3646 source_position_t const* const pos = &declaration->source_position;
3648 switch (declaration->declared_storage_class) {
3649 case STORAGE_CLASS_TYPEDEF:
3650 errorf(pos, "typedef not allowed in parameter list");
3653 /* Allowed storage classes */
3654 case STORAGE_CLASS_NONE:
3655 case STORAGE_CLASS_REGISTER:
3659 errorf(pos, "parameter may only have none or register storage class");
3663 type_t *const orig_type = declaration->type;
3664 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3665 * sugar. Turn it into a pointer.
3666 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3667 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3669 type_t *const type = automatic_type_conversion(orig_type);
3670 declaration->type = type;
3672 if (is_type_incomplete(skip_typeref(type))) {
3673 errorf(pos, "parameter '%#T' is of incomplete type",
3674 orig_type, declaration->symbol);
3678 static declaration_t *parse_parameter(void)
3680 declaration_specifiers_t specifiers;
3681 memset(&specifiers, 0, sizeof(specifiers));
3683 parse_declaration_specifiers(&specifiers);
3685 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3690 static declaration_t *parse_parameters(function_type_t *type)
3692 declaration_t *declarations = NULL;
3695 add_anchor_token(')');
3696 int saved_comma_state = save_and_reset_anchor_state(',');
3698 if (token.type == T_IDENTIFIER &&
3699 !is_typedef_symbol(token.v.symbol)) {
3700 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3701 if (la1_type == ',' || la1_type == ')') {
3702 type->kr_style_parameters = true;
3703 declarations = parse_identifier_list();
3704 goto parameters_finished;
3708 if (token.type == ')') {
3709 type->unspecified_parameters = 1;
3710 goto parameters_finished;
3713 declaration_t *declaration;
3714 declaration_t *last_declaration = NULL;
3715 function_parameter_t *parameter;
3716 function_parameter_t *last_parameter = NULL;
3719 switch(token.type) {
3723 goto parameters_finished;
3726 case T___extension__:
3728 declaration = parse_parameter();
3730 /* func(void) is not a parameter */
3731 if (last_parameter == NULL
3732 && token.type == ')'
3733 && declaration->symbol == NULL
3734 && skip_typeref(declaration->type) == type_void) {
3735 goto parameters_finished;
3737 semantic_parameter(declaration);
3739 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3740 memset(parameter, 0, sizeof(parameter[0]));
3741 parameter->type = declaration->type;
3743 if (last_parameter != NULL) {
3744 last_declaration->next = declaration;
3745 last_parameter->next = parameter;
3747 type->parameters = parameter;
3748 declarations = declaration;
3750 last_parameter = parameter;
3751 last_declaration = declaration;
3755 goto parameters_finished;
3757 if (token.type != ',') {
3758 goto parameters_finished;
3764 parameters_finished:
3765 rem_anchor_token(')');
3768 restore_anchor_state(',', saved_comma_state);
3769 return declarations;
3772 restore_anchor_state(',', saved_comma_state);
3776 typedef enum construct_type_kind_t {
3781 } construct_type_kind_t;
3783 typedef struct construct_type_t construct_type_t;
3784 struct construct_type_t {
3785 construct_type_kind_t kind;
3786 construct_type_t *next;
3789 typedef struct parsed_pointer_t parsed_pointer_t;
3790 struct parsed_pointer_t {
3791 construct_type_t construct_type;
3792 type_qualifiers_t type_qualifiers;
3795 typedef struct construct_function_type_t construct_function_type_t;
3796 struct construct_function_type_t {
3797 construct_type_t construct_type;
3798 type_t *function_type;
3801 typedef struct parsed_array_t parsed_array_t;
3802 struct parsed_array_t {
3803 construct_type_t construct_type;
3804 type_qualifiers_t type_qualifiers;
3810 typedef struct construct_base_type_t construct_base_type_t;
3811 struct construct_base_type_t {
3812 construct_type_t construct_type;
3816 static construct_type_t *parse_pointer_declarator(void)
3820 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3821 memset(pointer, 0, sizeof(pointer[0]));
3822 pointer->construct_type.kind = CONSTRUCT_POINTER;
3823 pointer->type_qualifiers = parse_type_qualifiers();
3825 return (construct_type_t*) pointer;
3828 static construct_type_t *parse_array_declarator(void)
3831 add_anchor_token(']');
3833 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3834 memset(array, 0, sizeof(array[0]));
3835 array->construct_type.kind = CONSTRUCT_ARRAY;
3837 if (token.type == T_static) {
3838 array->is_static = true;
3842 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3843 if (type_qualifiers != 0) {
3844 if (token.type == T_static) {
3845 array->is_static = true;
3849 array->type_qualifiers = type_qualifiers;
3851 if (token.type == '*' && look_ahead(1)->type == ']') {
3852 array->is_variable = true;
3854 } else if (token.type != ']') {
3855 array->size = parse_assignment_expression();
3858 rem_anchor_token(']');
3861 return (construct_type_t*) array;
3866 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3869 if (declaration != NULL) {
3870 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3872 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3874 if (mask & (mask-1)) {
3875 const char *first = NULL, *second = NULL;
3877 /* more than one calling convention set */
3878 if (declaration->modifiers & DM_CDECL) {
3879 if (first == NULL) first = "cdecl";
3880 else if (second == NULL) second = "cdecl";
3882 if (declaration->modifiers & DM_STDCALL) {
3883 if (first == NULL) first = "stdcall";
3884 else if (second == NULL) second = "stdcall";
3886 if (declaration->modifiers & DM_FASTCALL) {
3887 if (first == NULL) first = "fastcall";
3888 else if (second == NULL) second = "fastcall";
3890 if (declaration->modifiers & DM_THISCALL) {
3891 if (first == NULL) first = "thiscall";
3892 else if (second == NULL) second = "thiscall";
3894 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3897 if (declaration->modifiers & DM_CDECL)
3898 type->function.calling_convention = CC_CDECL;
3899 else if (declaration->modifiers & DM_STDCALL)
3900 type->function.calling_convention = CC_STDCALL;
3901 else if (declaration->modifiers & DM_FASTCALL)
3902 type->function.calling_convention = CC_FASTCALL;
3903 else if (declaration->modifiers & DM_THISCALL)
3904 type->function.calling_convention = CC_THISCALL;
3906 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3909 declaration_t *parameters = parse_parameters(&type->function);
3910 if (declaration != NULL) {
3911 declaration->scope.declarations = parameters;
3914 construct_function_type_t *construct_function_type =
3915 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3916 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3917 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3918 construct_function_type->function_type = type;
3920 return &construct_function_type->construct_type;
3923 static void fix_declaration_type(declaration_t *declaration)
3925 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3926 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3928 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3929 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3931 if (declaration->type->base.modifiers == type_modifiers)
3934 type_t *copy = duplicate_type(declaration->type);
3935 copy->base.modifiers = type_modifiers;
3937 type_t *result = typehash_insert(copy);
3938 if (result != copy) {
3939 obstack_free(type_obst, copy);
3942 declaration->type = result;
3945 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3946 bool may_be_abstract)
3948 /* construct a single linked list of construct_type_t's which describe
3949 * how to construct the final declarator type */
3950 construct_type_t *first = NULL;
3951 construct_type_t *last = NULL;
3952 gnu_attribute_t *attributes = NULL;
3954 decl_modifiers_t modifiers = parse_attributes(&attributes);
3957 while (token.type == '*') {
3958 construct_type_t *type = parse_pointer_declarator();
3968 /* TODO: find out if this is correct */
3969 modifiers |= parse_attributes(&attributes);
3972 if (declaration != NULL)
3973 declaration->modifiers |= modifiers;
3975 construct_type_t *inner_types = NULL;
3977 switch(token.type) {
3979 if (declaration == NULL) {
3980 errorf(HERE, "no identifier expected in typename");
3982 declaration->symbol = token.v.symbol;
3983 declaration->source_position = token.source_position;
3989 add_anchor_token(')');
3990 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3991 /* All later declarators only modify the return type, not declaration */
3993 rem_anchor_token(')');
3997 if (may_be_abstract)
3999 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4000 /* avoid a loop in the outermost scope, because eat_statement doesn't
4002 if (token.type == '}' && current_function == NULL) {
4010 construct_type_t *p = last;
4013 construct_type_t *type;
4014 switch(token.type) {
4016 type = parse_function_declarator(declaration);
4019 type = parse_array_declarator();
4022 goto declarator_finished;
4025 /* insert in the middle of the list (behind p) */
4027 type->next = p->next;
4038 declarator_finished:
4039 /* append inner_types at the end of the list, we don't to set last anymore
4040 * as it's not needed anymore */
4042 assert(first == NULL);
4043 first = inner_types;
4045 last->next = inner_types;
4053 static void parse_declaration_attributes(declaration_t *declaration)
4055 gnu_attribute_t *attributes = NULL;
4056 decl_modifiers_t modifiers = parse_attributes(&attributes);
4058 if (declaration == NULL)
4061 declaration->modifiers |= modifiers;
4062 /* check if we have these stupid mode attributes... */
4063 type_t *old_type = declaration->type;
4064 if (old_type == NULL)
4067 gnu_attribute_t *attribute = attributes;
4068 for ( ; attribute != NULL; attribute = attribute->next) {
4069 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4072 atomic_type_kind_t akind = attribute->u.akind;
4073 if (!is_type_signed(old_type)) {
4075 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4076 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4077 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4078 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4080 panic("invalid akind in mode attribute");
4084 = make_atomic_type(akind, old_type->base.qualifiers);
4088 static type_t *construct_declarator_type(construct_type_t *construct_list,
4091 construct_type_t *iter = construct_list;
4092 for( ; iter != NULL; iter = iter->next) {
4093 switch(iter->kind) {
4094 case CONSTRUCT_INVALID:
4095 internal_errorf(HERE, "invalid type construction found");
4096 case CONSTRUCT_FUNCTION: {
4097 construct_function_type_t *construct_function_type
4098 = (construct_function_type_t*) iter;
4100 type_t *function_type = construct_function_type->function_type;
4102 function_type->function.return_type = type;
4104 type_t *skipped_return_type = skip_typeref(type);
4105 if (is_type_function(skipped_return_type)) {
4106 errorf(HERE, "function returning function is not allowed");
4107 type = type_error_type;
4108 } else if (is_type_array(skipped_return_type)) {
4109 errorf(HERE, "function returning array is not allowed");
4110 type = type_error_type;
4112 type = function_type;
4117 case CONSTRUCT_POINTER: {
4118 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4119 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4120 pointer_type->pointer.points_to = type;
4121 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4123 type = pointer_type;
4127 case CONSTRUCT_ARRAY: {
4128 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4129 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4131 expression_t *size_expression = parsed_array->size;
4132 if (size_expression != NULL) {
4134 = create_implicit_cast(size_expression, type_size_t);
4137 array_type->base.qualifiers = parsed_array->type_qualifiers;
4138 array_type->array.element_type = type;
4139 array_type->array.is_static = parsed_array->is_static;
4140 array_type->array.is_variable = parsed_array->is_variable;
4141 array_type->array.size_expression = size_expression;
4143 if (size_expression != NULL) {
4144 if (is_constant_expression(size_expression)) {
4145 array_type->array.size_constant = true;
4146 array_type->array.size
4147 = fold_constant(size_expression);
4149 array_type->array.is_vla = true;
4153 type_t *skipped_type = skip_typeref(type);
4154 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4155 errorf(HERE, "array of void is not allowed");
4156 type = type_error_type;
4164 type_t *hashed_type = typehash_insert(type);
4165 if (hashed_type != type) {
4166 /* the function type was constructed earlier freeing it here will
4167 * destroy other types... */
4168 if (iter->kind != CONSTRUCT_FUNCTION) {
4178 static declaration_t *parse_declarator(
4179 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4181 declaration_t *const declaration = allocate_declaration_zero();
4182 declaration->source_position = specifiers->source_position;
4183 declaration->declared_storage_class = specifiers->declared_storage_class;
4184 declaration->modifiers = specifiers->modifiers;
4185 declaration->deprecated_string = specifiers->deprecated_string;
4186 declaration->get_property_sym = specifiers->get_property_sym;
4187 declaration->put_property_sym = specifiers->put_property_sym;
4188 declaration->is_inline = specifiers->is_inline;
4190 declaration->storage_class = specifiers->declared_storage_class;
4191 if (declaration->storage_class == STORAGE_CLASS_NONE
4192 && scope != global_scope) {
4193 declaration->storage_class = STORAGE_CLASS_AUTO;
4196 if (specifiers->alignment != 0) {
4197 /* TODO: add checks here */
4198 declaration->alignment = specifiers->alignment;
4201 construct_type_t *construct_type
4202 = parse_inner_declarator(declaration, may_be_abstract);
4203 type_t *const type = specifiers->type;
4204 declaration->type = construct_declarator_type(construct_type, type);
4206 parse_declaration_attributes(declaration);
4208 fix_declaration_type(declaration);
4210 if (construct_type != NULL) {
4211 obstack_free(&temp_obst, construct_type);
4217 static type_t *parse_abstract_declarator(type_t *base_type)
4219 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4221 type_t *result = construct_declarator_type(construct_type, base_type);
4222 if (construct_type != NULL) {
4223 obstack_free(&temp_obst, construct_type);
4229 static declaration_t *append_declaration(declaration_t* const declaration)
4231 if (last_declaration != NULL) {
4232 last_declaration->next = declaration;
4234 scope->declarations = declaration;
4236 last_declaration = declaration;
4241 * Check if the declaration of main is suspicious. main should be a
4242 * function with external linkage, returning int, taking either zero
4243 * arguments, two, or three arguments of appropriate types, ie.
4245 * int main([ int argc, char **argv [, char **env ] ]).
4247 * @param decl the declaration to check
4248 * @param type the function type of the declaration
4250 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4252 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4253 warningf(&decl->source_position,
4254 "'main' is normally a non-static function");
4256 if (skip_typeref(func_type->return_type) != type_int) {
4257 warningf(&decl->source_position,
4258 "return type of 'main' should be 'int', but is '%T'",
4259 func_type->return_type);
4261 const function_parameter_t *parm = func_type->parameters;
4263 type_t *const first_type = parm->type;
4264 if (!types_compatible(skip_typeref(first_type), type_int)) {
4265 warningf(&decl->source_position,
4266 "first argument of 'main' should be 'int', but is '%T'", first_type);
4270 type_t *const second_type = parm->type;
4271 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4272 warningf(&decl->source_position,
4273 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4277 type_t *const third_type = parm->type;
4278 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4279 warningf(&decl->source_position,
4280 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4284 goto warn_arg_count;
4288 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4294 * Check if a symbol is the equal to "main".
4296 static bool is_sym_main(const symbol_t *const sym)
4298 return strcmp(sym->string, "main") == 0;
4301 static declaration_t *record_declaration(
4302 declaration_t *const declaration,
4303 const bool is_definition)
4305 const symbol_t *const symbol = declaration->symbol;
4306 const namespace_t namespc = (namespace_t)declaration->namespc;
4308 assert(symbol != NULL);
4309 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4311 type_t *const orig_type = declaration->type;
4312 type_t *const type = skip_typeref(orig_type);
4313 if (is_type_function(type) &&
4314 type->function.unspecified_parameters &&
4315 warning.strict_prototypes &&
4316 previous_declaration == NULL) {
4317 warningf(&declaration->source_position,
4318 "function declaration '%#T' is not a prototype",
4319 orig_type, declaration->symbol);
4322 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4323 check_type_of_main(declaration, &type->function);
4326 if (warning.nested_externs &&
4327 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4328 scope != global_scope) {
4329 warningf(&declaration->source_position,
4330 "nested extern declaration of '%#T'", declaration->type, symbol);
4333 assert(declaration != previous_declaration);
4334 if (previous_declaration != NULL
4335 && previous_declaration->parent_scope == scope) {
4336 /* can happen for K&R style declarations */
4337 if (previous_declaration->type == NULL) {
4338 previous_declaration->type = declaration->type;
4341 const type_t *prev_type = skip_typeref(previous_declaration->type);
4342 if (!types_compatible(type, prev_type)) {
4343 errorf(&declaration->source_position,
4344 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4345 orig_type, symbol, previous_declaration->type, symbol,
4346 &previous_declaration->source_position);
4348 unsigned old_storage_class = previous_declaration->storage_class;
4349 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4350 errorf(&declaration->source_position,
4351 "redeclaration of enum entry '%Y' (declared %P)",
4352 symbol, &previous_declaration->source_position);
4353 return previous_declaration;
4356 if (warning.redundant_decls &&
4358 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4359 !(previous_declaration->modifiers & DM_USED) &&
4360 !previous_declaration->used) {
4361 warningf(&previous_declaration->source_position,
4362 "unnecessary static forward declaration for '%#T'",
4363 previous_declaration->type, symbol);
4366 unsigned new_storage_class = declaration->storage_class;
4368 if (is_type_incomplete(prev_type)) {
4369 previous_declaration->type = type;
4373 /* pretend no storage class means extern for function
4374 * declarations (except if the previous declaration is neither
4375 * none nor extern) */
4376 if (is_type_function(type)) {
4377 if (prev_type->function.unspecified_parameters) {
4378 previous_declaration->type = type;
4382 switch (old_storage_class) {
4383 case STORAGE_CLASS_NONE:
4384 old_storage_class = STORAGE_CLASS_EXTERN;
4387 case STORAGE_CLASS_EXTERN:
4388 if (is_definition) {
4389 if (warning.missing_prototypes &&
4390 prev_type->function.unspecified_parameters &&
4391 !is_sym_main(symbol)) {
4392 warningf(&declaration->source_position,
4393 "no previous prototype for '%#T'",
4396 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4397 new_storage_class = STORAGE_CLASS_EXTERN;
4406 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4407 new_storage_class == STORAGE_CLASS_EXTERN) {
4408 warn_redundant_declaration:
4409 if (!is_definition &&
4410 warning.redundant_decls &&
4411 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4412 warningf(&declaration->source_position,
4413 "redundant declaration for '%Y' (declared %P)",
4414 symbol, &previous_declaration->source_position);
4416 } else if (current_function == NULL) {
4417 if (old_storage_class != STORAGE_CLASS_STATIC &&
4418 new_storage_class == STORAGE_CLASS_STATIC) {
4419 errorf(&declaration->source_position,
4420 "static declaration of '%Y' follows non-static declaration (declared %P)",
4421 symbol, &previous_declaration->source_position);
4422 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4423 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4424 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4426 goto warn_redundant_declaration;
4428 } else if (old_storage_class == new_storage_class) {
4429 errorf(&declaration->source_position,
4430 "redeclaration of '%Y' (declared %P)",
4431 symbol, &previous_declaration->source_position);
4433 errorf(&declaration->source_position,
4434 "redeclaration of '%Y' with different linkage (declared %P)",
4435 symbol, &previous_declaration->source_position);
4439 previous_declaration->modifiers |= declaration->modifiers;
4440 previous_declaration->is_inline |= declaration->is_inline;
4441 return previous_declaration;
4442 } else if (is_type_function(type)) {
4443 if (is_definition &&
4444 declaration->storage_class != STORAGE_CLASS_STATIC) {
4445 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4446 warningf(&declaration->source_position,
4447 "no previous prototype for '%#T'", orig_type, symbol);
4448 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4449 warningf(&declaration->source_position,
4450 "no previous declaration for '%#T'", orig_type,
4455 if (warning.missing_declarations &&
4456 scope == global_scope && (
4457 declaration->storage_class == STORAGE_CLASS_NONE ||
4458 declaration->storage_class == STORAGE_CLASS_THREAD
4460 warningf(&declaration->source_position,
4461 "no previous declaration for '%#T'", orig_type, symbol);
4465 assert(declaration->parent_scope == NULL);
4466 assert(scope != NULL);
4468 declaration->parent_scope = scope;
4470 environment_push(declaration);
4471 return append_declaration(declaration);
4474 static void parser_error_multiple_definition(declaration_t *declaration,
4475 const source_position_t *source_position)
4477 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4478 declaration->symbol, &declaration->source_position);
4481 static bool is_declaration_specifier(const token_t *token,
4482 bool only_specifiers_qualifiers)
4484 switch(token->type) {
4489 return is_typedef_symbol(token->v.symbol);
4491 case T___extension__:
4493 return !only_specifiers_qualifiers;
4500 static void parse_init_declarator_rest(declaration_t *declaration)
4504 type_t *orig_type = declaration->type;
4505 type_t *type = skip_typeref(orig_type);
4507 if (declaration->init.initializer != NULL) {
4508 parser_error_multiple_definition(declaration, HERE);
4511 bool must_be_constant = false;
4512 if (declaration->storage_class == STORAGE_CLASS_STATIC
4513 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4514 || declaration->parent_scope == global_scope) {
4515 must_be_constant = true;
4518 if (is_type_function(type)) {
4519 errorf(&declaration->source_position,
4520 "function '%#T' is initialized like a variable",
4521 orig_type, declaration->symbol);
4522 orig_type = type_error_type;
4525 parse_initializer_env_t env;
4526 env.type = orig_type;
4527 env.must_be_constant = must_be_constant;
4528 env.declaration = current_init_decl = declaration;
4530 initializer_t *initializer = parse_initializer(&env);
4531 current_init_decl = NULL;
4533 if (!is_type_function(type)) {
4534 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4535 * the array type size */
4536 declaration->type = env.type;
4537 declaration->init.initializer = initializer;
4541 /* parse rest of a declaration without any declarator */
4542 static void parse_anonymous_declaration_rest(
4543 const declaration_specifiers_t *specifiers)
4547 declaration_t *const declaration = allocate_declaration_zero();
4548 declaration->type = specifiers->type;
4549 declaration->declared_storage_class = specifiers->declared_storage_class;
4550 declaration->source_position = specifiers->source_position;
4551 declaration->modifiers = specifiers->modifiers;
4553 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4554 warningf(&declaration->source_position,
4555 "useless storage class in empty declaration");
4557 declaration->storage_class = STORAGE_CLASS_NONE;
4559 type_t *type = declaration->type;
4560 switch (type->kind) {
4561 case TYPE_COMPOUND_STRUCT:
4562 case TYPE_COMPOUND_UNION: {
4563 if (type->compound.declaration->symbol == NULL) {
4564 warningf(&declaration->source_position,
4565 "unnamed struct/union that defines no instances");
4574 warningf(&declaration->source_position, "empty declaration");
4578 append_declaration(declaration);
4581 static void parse_declaration_rest(declaration_t *ndeclaration,
4582 const declaration_specifiers_t *specifiers,
4583 parsed_declaration_func finished_declaration)
4585 add_anchor_token(';');
4586 add_anchor_token('=');
4587 add_anchor_token(',');
4589 declaration_t *declaration =
4590 finished_declaration(ndeclaration, token.type == '=');
4592 type_t *orig_type = declaration->type;
4593 type_t *type = skip_typeref(orig_type);
4595 if (type->kind != TYPE_FUNCTION &&
4596 declaration->is_inline &&
4597 is_type_valid(type)) {
4598 warningf(&declaration->source_position,
4599 "variable '%Y' declared 'inline'\n", declaration->symbol);
4602 if (token.type == '=') {
4603 parse_init_declarator_rest(declaration);
4606 if (token.type != ',')
4610 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4615 rem_anchor_token(';');
4616 rem_anchor_token('=');
4617 rem_anchor_token(',');
4620 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4622 symbol_t *symbol = declaration->symbol;
4623 if (symbol == NULL) {
4624 errorf(HERE, "anonymous declaration not valid as function parameter");
4627 namespace_t namespc = (namespace_t) declaration->namespc;
4628 if (namespc != NAMESPACE_NORMAL) {
4629 return record_declaration(declaration, false);
4632 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4633 if (previous_declaration == NULL ||
4634 previous_declaration->parent_scope != scope) {
4635 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4640 if (is_definition) {
4641 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4644 if (previous_declaration->type == NULL) {
4645 previous_declaration->type = declaration->type;
4646 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4647 previous_declaration->storage_class = declaration->storage_class;
4648 previous_declaration->parent_scope = scope;
4649 return previous_declaration;
4651 return record_declaration(declaration, false);
4655 static void parse_declaration(parsed_declaration_func finished_declaration)
4657 declaration_specifiers_t specifiers;
4658 memset(&specifiers, 0, sizeof(specifiers));
4659 parse_declaration_specifiers(&specifiers);
4661 if (token.type == ';') {
4662 parse_anonymous_declaration_rest(&specifiers);
4664 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4665 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4669 static type_t *get_default_promoted_type(type_t *orig_type)
4671 type_t *result = orig_type;
4673 type_t *type = skip_typeref(orig_type);
4674 if (is_type_integer(type)) {
4675 result = promote_integer(type);
4676 } else if (type == type_float) {
4677 result = type_double;
4683 static void parse_kr_declaration_list(declaration_t *declaration)
4685 type_t *type = skip_typeref(declaration->type);
4686 if (!is_type_function(type))
4689 if (!type->function.kr_style_parameters)
4692 /* push function parameters */
4693 int top = environment_top();
4694 scope_t *last_scope = scope;
4695 set_scope(&declaration->scope);
4697 declaration_t *parameter = declaration->scope.declarations;
4698 for ( ; parameter != NULL; parameter = parameter->next) {
4699 assert(parameter->parent_scope == NULL);
4700 parameter->parent_scope = scope;
4701 environment_push(parameter);
4704 /* parse declaration list */
4705 while (is_declaration_specifier(&token, false)) {
4706 parse_declaration(finished_kr_declaration);
4709 /* pop function parameters */
4710 assert(scope == &declaration->scope);
4711 set_scope(last_scope);
4712 environment_pop_to(top);
4714 /* update function type */
4715 type_t *new_type = duplicate_type(type);
4717 function_parameter_t *parameters = NULL;
4718 function_parameter_t *last_parameter = NULL;
4720 declaration_t *parameter_declaration = declaration->scope.declarations;
4721 for( ; parameter_declaration != NULL;
4722 parameter_declaration = parameter_declaration->next) {
4723 type_t *parameter_type = parameter_declaration->type;
4724 if (parameter_type == NULL) {
4726 errorf(HERE, "no type specified for function parameter '%Y'",
4727 parameter_declaration->symbol);
4729 if (warning.implicit_int) {
4730 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4731 parameter_declaration->symbol);
4733 parameter_type = type_int;
4734 parameter_declaration->type = parameter_type;
4738 semantic_parameter(parameter_declaration);
4739 parameter_type = parameter_declaration->type;
4742 * we need the default promoted types for the function type
4744 parameter_type = get_default_promoted_type(parameter_type);
4746 function_parameter_t *function_parameter
4747 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4748 memset(function_parameter, 0, sizeof(function_parameter[0]));
4750 function_parameter->type = parameter_type;
4751 if (last_parameter != NULL) {
4752 last_parameter->next = function_parameter;
4754 parameters = function_parameter;
4756 last_parameter = function_parameter;
4759 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4761 new_type->function.parameters = parameters;
4762 new_type->function.unspecified_parameters = true;
4764 type = typehash_insert(new_type);
4765 if (type != new_type) {
4766 obstack_free(type_obst, new_type);
4769 declaration->type = type;
4772 static bool first_err = true;
4775 * When called with first_err set, prints the name of the current function,
4778 static void print_in_function(void)
4782 diagnosticf("%s: In function '%Y':\n",
4783 current_function->source_position.input_name,
4784 current_function->symbol);
4789 * Check if all labels are defined in the current function.
4790 * Check if all labels are used in the current function.
4792 static void check_labels(void)
4794 for (const goto_statement_t *goto_statement = goto_first;
4795 goto_statement != NULL;
4796 goto_statement = goto_statement->next) {
4797 declaration_t *label = goto_statement->label;
4800 if (label->source_position.input_name == NULL) {
4801 print_in_function();
4802 errorf(&goto_statement->base.source_position,
4803 "label '%Y' used but not defined", label->symbol);
4806 goto_first = goto_last = NULL;
4808 if (warning.unused_label) {
4809 for (const label_statement_t *label_statement = label_first;
4810 label_statement != NULL;
4811 label_statement = label_statement->next) {
4812 const declaration_t *label = label_statement->label;
4814 if (! label->used) {
4815 print_in_function();
4816 warningf(&label_statement->base.source_position,
4817 "label '%Y' defined but not used", label->symbol);
4821 label_first = label_last = NULL;
4825 * Check declarations of current_function for unused entities.
4827 static void check_declarations(void)
4829 if (warning.unused_parameter) {
4830 const scope_t *scope = ¤t_function->scope;
4832 if (is_sym_main(current_function->symbol)) {
4833 /* do not issue unused warnings for main */
4836 const declaration_t *parameter = scope->declarations;
4837 for (; parameter != NULL; parameter = parameter->next) {
4838 if (! parameter->used) {
4839 print_in_function();
4840 warningf(¶meter->source_position,
4841 "unused parameter '%Y'", parameter->symbol);
4845 if (warning.unused_variable) {
4849 static int determine_truth(expression_t const* const cond)
4852 !is_constant_expression(cond) ? 0 :
4853 fold_constant(cond) != 0 ? 1 :
4857 static bool noreturn_candidate;
4859 static void check_reachable(statement_t *const stmt)
4861 if (stmt->base.reachable)
4863 if (stmt->kind != STATEMENT_DO_WHILE)
4864 stmt->base.reachable = true;
4866 statement_t *last = stmt;
4868 switch (stmt->kind) {
4869 case STATEMENT_INVALID:
4870 case STATEMENT_EMPTY:
4871 case STATEMENT_DECLARATION:
4873 next = stmt->base.next;
4876 case STATEMENT_COMPOUND:
4877 next = stmt->compound.statements;
4880 case STATEMENT_RETURN:
4881 noreturn_candidate = false;
4884 case STATEMENT_IF: {
4885 if_statement_t const* const ifs = &stmt->ifs;
4886 int const val = determine_truth(ifs->condition);
4889 check_reachable(ifs->true_statement);
4894 if (ifs->false_statement != NULL) {
4895 check_reachable(ifs->false_statement);
4899 next = stmt->base.next;
4903 case STATEMENT_SWITCH: {
4904 switch_statement_t const *const switchs = &stmt->switchs;
4905 expression_t const *const expr = switchs->expression;
4907 if (is_constant_expression(expr)) {
4908 long const val = fold_constant(expr);
4909 case_label_statement_t * defaults = NULL;
4910 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4911 if (i->expression == NULL) {
4916 if (i->first_case <= val && val <= i->last_case) {
4917 check_reachable((statement_t*)i);
4922 if (defaults != NULL) {
4923 check_reachable((statement_t*)defaults);
4927 bool has_default = false;
4928 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4929 if (i->expression == NULL)
4932 check_reachable((statement_t*)i);
4939 next = stmt->base.next;
4943 case STATEMENT_EXPRESSION: {
4944 /* Check for noreturn function call */
4945 expression_t const *const expr = stmt->expression.expression;
4946 if (expr->kind == EXPR_CALL) {
4947 expression_t const *const func = expr->call.function;
4948 if (func->kind == EXPR_REFERENCE) {
4949 declaration_t const *const decl = func->reference.declaration;
4950 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4956 next = stmt->base.next;
4960 case STATEMENT_CONTINUE: {
4961 statement_t *parent = stmt;
4963 parent = parent->base.parent;
4964 if (parent == NULL) /* continue not within loop */
4968 switch (parent->kind) {
4969 case STATEMENT_WHILE: goto continue_while;
4970 case STATEMENT_DO_WHILE: goto continue_do_while;
4971 case STATEMENT_FOR: goto continue_for;
4978 case STATEMENT_BREAK: {
4979 statement_t *parent = stmt;
4981 parent = parent->base.parent;
4982 if (parent == NULL) /* break not within loop/switch */
4985 switch (parent->kind) {
4986 case STATEMENT_SWITCH:
4987 case STATEMENT_WHILE:
4988 case STATEMENT_DO_WHILE:
4991 next = parent->base.next;
4992 goto found_break_parent;
5001 case STATEMENT_GOTO:
5002 next = stmt->gotos.label->init.statement;
5003 if (next == NULL) /* missing label */
5007 case STATEMENT_LABEL:
5008 next = stmt->label.statement;
5011 case STATEMENT_CASE_LABEL:
5012 next = stmt->case_label.statement;
5015 case STATEMENT_WHILE: {
5016 while_statement_t const *const whiles = &stmt->whiles;
5017 int const val = determine_truth(whiles->condition);
5020 check_reachable(whiles->body);
5025 next = stmt->base.next;
5029 case STATEMENT_DO_WHILE:
5030 next = stmt->do_while.body;
5033 case STATEMENT_FOR: {
5034 for_statement_t *const fors = &stmt->fors;
5036 if (fors->condition_reachable)
5038 fors->condition_reachable = true;
5040 expression_t const *const cond = fors->condition;
5042 cond == NULL ? 1 : determine_truth(cond);
5045 check_reachable(fors->body);
5050 next = stmt->base.next;
5054 case STATEMENT_MS_TRY: {
5055 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5056 check_reachable(ms_try->try_statement);
5057 next = ms_try->final_statement;
5061 case STATEMENT_LEAVE: {
5062 statement_t *parent = stmt;
5064 parent = parent->base.parent;
5065 if (parent == NULL) /* __leave not within __try */
5068 if (parent->kind == STATEMENT_MS_TRY) {
5070 next = parent->ms_try.final_statement;
5078 while (next == NULL) {
5079 next = last->base.parent;
5081 noreturn_candidate = false;
5083 type_t *const type = current_function->type;
5084 assert(is_type_function(type));
5085 type_t *const ret = skip_typeref(type->function.return_type);
5086 if (warning.return_type &&
5087 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5088 is_type_valid(ret) &&
5089 !is_sym_main(current_function->symbol)) {
5090 warningf(&stmt->base.source_position,
5091 "control reaches end of non-void function");
5096 switch (next->kind) {
5097 case STATEMENT_INVALID:
5098 case STATEMENT_EMPTY:
5099 case STATEMENT_DECLARATION:
5100 case STATEMENT_EXPRESSION:
5102 case STATEMENT_RETURN:
5103 case STATEMENT_CONTINUE:
5104 case STATEMENT_BREAK:
5105 case STATEMENT_GOTO:
5106 case STATEMENT_LEAVE:
5107 panic("invalid control flow in function");
5109 case STATEMENT_COMPOUND:
5111 case STATEMENT_SWITCH:
5112 case STATEMENT_LABEL:
5113 case STATEMENT_CASE_LABEL:
5115 next = next->base.next;
5118 case STATEMENT_WHILE: {
5120 if (next->base.reachable)
5122 next->base.reachable = true;
5124 while_statement_t const *const whiles = &next->whiles;
5125 int const val = determine_truth(whiles->condition);
5128 check_reachable(whiles->body);
5134 next = next->base.next;
5138 case STATEMENT_DO_WHILE: {
5140 if (next->base.reachable)
5142 next->base.reachable = true;
5144 do_while_statement_t const *const dw = &next->do_while;
5145 int const val = determine_truth(dw->condition);
5148 check_reachable(dw->body);
5154 next = next->base.next;
5158 case STATEMENT_FOR: {
5160 for_statement_t *const fors = &next->fors;
5162 fors->step_reachable = true;
5164 if (fors->condition_reachable)
5166 fors->condition_reachable = true;
5168 expression_t const *const cond = fors->condition;
5170 cond == NULL ? 1 : determine_truth(cond);
5173 check_reachable(fors->body);
5179 next = next->base.next;
5183 case STATEMENT_MS_TRY:
5185 next = next->ms_try.final_statement;
5191 next = stmt->base.parent;
5193 warningf(&stmt->base.source_position,
5194 "control reaches end of non-void function");
5198 check_reachable(next);
5201 static void check_unreachable(statement_t const* const stmt)
5203 if (!stmt->base.reachable &&
5204 stmt->kind != STATEMENT_DO_WHILE &&
5205 stmt->kind != STATEMENT_FOR &&
5206 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5207 warningf(&stmt->base.source_position, "statement is unreachable");
5210 switch (stmt->kind) {
5211 case STATEMENT_INVALID:
5212 case STATEMENT_EMPTY:
5213 case STATEMENT_RETURN:
5214 case STATEMENT_DECLARATION:
5215 case STATEMENT_EXPRESSION:
5216 case STATEMENT_CONTINUE:
5217 case STATEMENT_BREAK:
5218 case STATEMENT_GOTO:
5220 case STATEMENT_LEAVE:
5223 case STATEMENT_COMPOUND:
5224 if (stmt->compound.statements)
5225 check_unreachable(stmt->compound.statements);
5229 check_unreachable(stmt->ifs.true_statement);
5230 if (stmt->ifs.false_statement != NULL)
5231 check_unreachable(stmt->ifs.false_statement);
5234 case STATEMENT_SWITCH:
5235 check_unreachable(stmt->switchs.body);
5238 case STATEMENT_LABEL:
5239 check_unreachable(stmt->label.statement);
5242 case STATEMENT_CASE_LABEL:
5243 check_unreachable(stmt->case_label.statement);
5246 case STATEMENT_WHILE:
5247 check_unreachable(stmt->whiles.body);
5250 case STATEMENT_DO_WHILE:
5251 check_unreachable(stmt->do_while.body);
5252 if (!stmt->base.reachable) {
5253 expression_t const *const cond = stmt->do_while.condition;
5254 if (determine_truth(cond) >= 0) {
5255 warningf(&cond->base.source_position,
5256 "condition of do-while-loop is unreachable");
5261 case STATEMENT_FOR: {
5262 for_statement_t const* const fors = &stmt->fors;
5264 // if init and step are unreachable, cond is unreachable, too
5265 if (!stmt->base.reachable && !fors->step_reachable) {
5266 warningf(&stmt->base.source_position, "statement is unreachable");
5268 if (!stmt->base.reachable && fors->initialisation != NULL) {
5269 warningf(&fors->initialisation->base.source_position,
5270 "initialisation of for-statement is unreachable");
5273 if (!fors->condition_reachable && fors->condition != NULL) {
5274 warningf(&fors->condition->base.source_position,
5275 "condition of for-statement is unreachable");
5278 if (!fors->step_reachable && fors->step != NULL) {
5279 warningf(&fors->step->base.source_position,
5280 "step of for-statement is unreachable");
5284 check_unreachable(fors->body);
5288 case STATEMENT_MS_TRY: {
5289 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5290 check_unreachable(ms_try->try_statement);
5291 check_unreachable(ms_try->final_statement);
5295 if (stmt->base.next)
5296 check_unreachable(stmt->base.next);
5299 static void parse_external_declaration(void)
5301 /* function-definitions and declarations both start with declaration
5303 declaration_specifiers_t specifiers;
5304 memset(&specifiers, 0, sizeof(specifiers));
5306 add_anchor_token(';');
5307 parse_declaration_specifiers(&specifiers);
5308 rem_anchor_token(';');
5310 /* must be a declaration */
5311 if (token.type == ';') {
5312 parse_anonymous_declaration_rest(&specifiers);
5316 add_anchor_token(',');
5317 add_anchor_token('=');
5318 rem_anchor_token(';');
5320 /* declarator is common to both function-definitions and declarations */
5321 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5323 rem_anchor_token(',');
5324 rem_anchor_token('=');
5325 rem_anchor_token(';');
5327 /* must be a declaration */
5328 switch (token.type) {
5332 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5336 /* must be a function definition */
5337 parse_kr_declaration_list(ndeclaration);
5339 if (token.type != '{') {
5340 parse_error_expected("while parsing function definition", '{', NULL);
5341 eat_until_matching_token(';');
5345 type_t *type = ndeclaration->type;
5347 /* note that we don't skip typerefs: the standard doesn't allow them here
5348 * (so we can't use is_type_function here) */
5349 if (type->kind != TYPE_FUNCTION) {
5350 if (is_type_valid(type)) {
5351 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5352 type, ndeclaration->symbol);
5358 if (warning.aggregate_return &&
5359 is_type_compound(skip_typeref(type->function.return_type))) {
5360 warningf(HERE, "function '%Y' returns an aggregate",
5361 ndeclaration->symbol);
5363 if (warning.traditional && !type->function.unspecified_parameters) {
5364 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5365 ndeclaration->symbol);
5367 if (warning.old_style_definition && type->function.unspecified_parameters) {
5368 warningf(HERE, "old-style function definition '%Y'",
5369 ndeclaration->symbol);
5372 /* § 6.7.5.3 (14) a function definition with () means no
5373 * parameters (and not unspecified parameters) */
5374 if (type->function.unspecified_parameters
5375 && type->function.parameters == NULL
5376 && !type->function.kr_style_parameters) {
5377 type_t *duplicate = duplicate_type(type);
5378 duplicate->function.unspecified_parameters = false;
5380 type = typehash_insert(duplicate);
5381 if (type != duplicate) {
5382 obstack_free(type_obst, duplicate);
5384 ndeclaration->type = type;
5387 declaration_t *const declaration = record_declaration(ndeclaration, true);
5388 if (ndeclaration != declaration) {
5389 declaration->scope = ndeclaration->scope;
5391 type = skip_typeref(declaration->type);
5393 /* push function parameters and switch scope */
5394 int top = environment_top();
5395 scope_t *last_scope = scope;
5396 set_scope(&declaration->scope);
5398 declaration_t *parameter = declaration->scope.declarations;
5399 for( ; parameter != NULL; parameter = parameter->next) {
5400 if (parameter->parent_scope == &ndeclaration->scope) {
5401 parameter->parent_scope = scope;
5403 assert(parameter->parent_scope == NULL
5404 || parameter->parent_scope == scope);
5405 parameter->parent_scope = scope;
5406 if (parameter->symbol == NULL) {
5407 errorf(¶meter->source_position, "parameter name omitted");
5410 environment_push(parameter);
5413 if (declaration->init.statement != NULL) {
5414 parser_error_multiple_definition(declaration, HERE);
5417 /* parse function body */
5418 int label_stack_top = label_top();
5419 declaration_t *old_current_function = current_function;
5420 current_function = declaration;
5421 current_parent = NULL;
5423 statement_t *const body = parse_compound_statement(false);
5424 declaration->init.statement = body;
5427 check_declarations();
5428 if (warning.return_type ||
5429 warning.unreachable_code ||
5430 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5431 noreturn_candidate = true;
5432 check_reachable(body);
5433 if (warning.unreachable_code)
5434 check_unreachable(body);
5435 if (warning.missing_noreturn &&
5436 noreturn_candidate &&
5437 !(declaration->modifiers & DM_NORETURN)) {
5438 warningf(&body->base.source_position,
5439 "function '%#T' is candidate for attribute 'noreturn'",
5440 type, declaration->symbol);
5444 assert(current_parent == NULL);
5445 assert(current_function == declaration);
5446 current_function = old_current_function;
5447 label_pop_to(label_stack_top);
5450 assert(scope == &declaration->scope);
5451 set_scope(last_scope);
5452 environment_pop_to(top);
5455 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5456 source_position_t *source_position)
5458 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5460 type->bitfield.base_type = base_type;
5461 type->bitfield.size = size;
5466 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5469 declaration_t *iter = compound_declaration->scope.declarations;
5470 for( ; iter != NULL; iter = iter->next) {
5471 if (iter->namespc != NAMESPACE_NORMAL)
5474 if (iter->symbol == NULL) {
5475 type_t *type = skip_typeref(iter->type);
5476 if (is_type_compound(type)) {
5477 declaration_t *result
5478 = find_compound_entry(type->compound.declaration, symbol);
5485 if (iter->symbol == symbol) {
5493 static void parse_compound_declarators(declaration_t *struct_declaration,
5494 const declaration_specifiers_t *specifiers)
5496 declaration_t *last_declaration = struct_declaration->scope.declarations;
5497 if (last_declaration != NULL) {
5498 while (last_declaration->next != NULL) {
5499 last_declaration = last_declaration->next;
5504 declaration_t *declaration;
5506 if (token.type == ':') {
5507 source_position_t source_position = *HERE;
5510 type_t *base_type = specifiers->type;
5511 expression_t *size = parse_constant_expression();
5513 if (!is_type_integer(skip_typeref(base_type))) {
5514 errorf(HERE, "bitfield base type '%T' is not an integer type",
5518 type_t *type = make_bitfield_type(base_type, size, &source_position);
5520 declaration = allocate_declaration_zero();
5521 declaration->namespc = NAMESPACE_NORMAL;
5522 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5523 declaration->storage_class = STORAGE_CLASS_NONE;
5524 declaration->source_position = source_position;
5525 declaration->modifiers = specifiers->modifiers;
5526 declaration->type = type;
5528 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5530 type_t *orig_type = declaration->type;
5531 type_t *type = skip_typeref(orig_type);
5533 if (token.type == ':') {
5534 source_position_t source_position = *HERE;
5536 expression_t *size = parse_constant_expression();
5538 if (!is_type_integer(type)) {
5539 errorf(HERE, "bitfield base type '%T' is not an integer type",
5543 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5544 declaration->type = bitfield_type;
5546 /* TODO we ignore arrays for now... what is missing is a check
5547 * that they're at the end of the struct */
5548 if (is_type_incomplete(type) && !is_type_array(type)) {
5550 "compound member '%Y' has incomplete type '%T'",
5551 declaration->symbol, orig_type);
5552 } else if (is_type_function(type)) {
5553 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5554 declaration->symbol, orig_type);
5559 /* make sure we don't define a symbol multiple times */
5560 symbol_t *symbol = declaration->symbol;
5561 if (symbol != NULL) {
5562 declaration_t *prev_decl
5563 = find_compound_entry(struct_declaration, symbol);
5565 if (prev_decl != NULL) {
5566 assert(prev_decl->symbol == symbol);
5567 errorf(&declaration->source_position,
5568 "multiple declarations of symbol '%Y' (declared %P)",
5569 symbol, &prev_decl->source_position);
5573 /* append declaration */
5574 if (last_declaration != NULL) {
5575 last_declaration->next = declaration;
5577 struct_declaration->scope.declarations = declaration;
5579 last_declaration = declaration;
5581 if (token.type != ',')
5591 static void parse_compound_type_entries(declaration_t *compound_declaration)
5594 add_anchor_token('}');
5596 while (token.type != '}' && token.type != T_EOF) {
5597 declaration_specifiers_t specifiers;
5598 memset(&specifiers, 0, sizeof(specifiers));
5599 parse_declaration_specifiers(&specifiers);
5601 parse_compound_declarators(compound_declaration, &specifiers);
5603 rem_anchor_token('}');
5605 if (token.type == T_EOF) {
5606 errorf(HERE, "EOF while parsing struct");
5611 static type_t *parse_typename(void)
5613 declaration_specifiers_t specifiers;
5614 memset(&specifiers, 0, sizeof(specifiers));
5615 parse_declaration_specifiers(&specifiers);
5616 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5617 /* TODO: improve error message, user does probably not know what a
5618 * storage class is...
5620 errorf(HERE, "typename may not have a storage class");
5623 type_t *result = parse_abstract_declarator(specifiers.type);
5631 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5632 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5633 expression_t *left);
5635 typedef struct expression_parser_function_t expression_parser_function_t;
5636 struct expression_parser_function_t {
5637 unsigned precedence;
5638 parse_expression_function parser;
5639 unsigned infix_precedence;
5640 parse_expression_infix_function infix_parser;
5643 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5646 * Prints an error message if an expression was expected but not read
5648 static expression_t *expected_expression_error(void)
5650 /* skip the error message if the error token was read */
5651 if (token.type != T_ERROR) {
5652 errorf(HERE, "expected expression, got token '%K'", &token);
5656 return create_invalid_expression();
5660 * Parse a string constant.
5662 static expression_t *parse_string_const(void)
5665 if (token.type == T_STRING_LITERAL) {
5666 string_t res = token.v.string;
5668 while (token.type == T_STRING_LITERAL) {
5669 res = concat_strings(&res, &token.v.string);
5672 if (token.type != T_WIDE_STRING_LITERAL) {
5673 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5674 /* note: that we use type_char_ptr here, which is already the
5675 * automatic converted type. revert_automatic_type_conversion
5676 * will construct the array type */
5677 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5678 cnst->string.value = res;
5682 wres = concat_string_wide_string(&res, &token.v.wide_string);
5684 wres = token.v.wide_string;
5689 switch (token.type) {
5690 case T_WIDE_STRING_LITERAL:
5691 wres = concat_wide_strings(&wres, &token.v.wide_string);
5694 case T_STRING_LITERAL:
5695 wres = concat_wide_string_string(&wres, &token.v.string);
5699 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5700 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5701 cnst->wide_string.value = wres;
5710 * Parse an integer constant.
5712 static expression_t *parse_int_const(void)
5714 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5715 cnst->base.source_position = *HERE;
5716 cnst->base.type = token.datatype;
5717 cnst->conste.v.int_value = token.v.intvalue;
5725 * Parse a character constant.
5727 static expression_t *parse_character_constant(void)
5729 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5731 cnst->base.source_position = *HERE;
5732 cnst->base.type = token.datatype;
5733 cnst->conste.v.character = token.v.string;
5735 if (cnst->conste.v.character.size != 1) {
5736 if (warning.multichar && (c_mode & _GNUC)) {
5738 warningf(HERE, "multi-character character constant");
5740 errorf(HERE, "more than 1 characters in character constant");
5749 * Parse a wide character constant.
5751 static expression_t *parse_wide_character_constant(void)
5753 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5755 cnst->base.source_position = *HERE;
5756 cnst->base.type = token.datatype;
5757 cnst->conste.v.wide_character = token.v.wide_string;
5759 if (cnst->conste.v.wide_character.size != 1) {
5760 if (warning.multichar && (c_mode & _GNUC)) {
5762 warningf(HERE, "multi-character character constant");
5764 errorf(HERE, "more than 1 characters in character constant");
5773 * Parse a float constant.
5775 static expression_t *parse_float_const(void)
5777 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5778 cnst->base.type = token.datatype;
5779 cnst->conste.v.float_value = token.v.floatvalue;
5786 static declaration_t *create_implicit_function(symbol_t *symbol,
5787 const source_position_t *source_position)
5789 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5790 ntype->function.return_type = type_int;
5791 ntype->function.unspecified_parameters = true;
5793 type_t *type = typehash_insert(ntype);
5794 if (type != ntype) {
5798 declaration_t *const declaration = allocate_declaration_zero();
5799 declaration->storage_class = STORAGE_CLASS_EXTERN;
5800 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5801 declaration->type = type;
5802 declaration->symbol = symbol;
5803 declaration->source_position = *source_position;
5804 declaration->implicit = true;
5806 bool strict_prototypes_old = warning.strict_prototypes;
5807 warning.strict_prototypes = false;
5808 record_declaration(declaration, false);
5809 warning.strict_prototypes = strict_prototypes_old;
5815 * Creates a return_type (func)(argument_type) function type if not
5818 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5819 type_t *argument_type2)
5821 function_parameter_t *parameter2
5822 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5823 memset(parameter2, 0, sizeof(parameter2[0]));
5824 parameter2->type = argument_type2;
5826 function_parameter_t *parameter1
5827 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5828 memset(parameter1, 0, sizeof(parameter1[0]));
5829 parameter1->type = argument_type1;
5830 parameter1->next = parameter2;
5832 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5833 type->function.return_type = return_type;
5834 type->function.parameters = parameter1;
5836 type_t *result = typehash_insert(type);
5837 if (result != type) {
5845 * Creates a return_type (func)(argument_type) function type if not
5848 * @param return_type the return type
5849 * @param argument_type the argument type
5851 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5853 function_parameter_t *parameter
5854 = obstack_alloc(type_obst, sizeof(parameter[0]));
5855 memset(parameter, 0, sizeof(parameter[0]));
5856 parameter->type = argument_type;
5858 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5859 type->function.return_type = return_type;
5860 type->function.parameters = parameter;
5862 type_t *result = typehash_insert(type);
5863 if (result != type) {
5870 static type_t *make_function_0_type(type_t *return_type)
5872 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5873 type->function.return_type = return_type;
5874 type->function.parameters = NULL;
5876 type_t *result = typehash_insert(type);
5877 if (result != type) {
5885 * Creates a function type for some function like builtins.
5887 * @param symbol the symbol describing the builtin
5889 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5891 switch(symbol->ID) {
5892 case T___builtin_alloca:
5893 return make_function_1_type(type_void_ptr, type_size_t);
5894 case T___builtin_huge_val:
5895 return make_function_0_type(type_double);
5896 case T___builtin_nan:
5897 return make_function_1_type(type_double, type_char_ptr);
5898 case T___builtin_nanf:
5899 return make_function_1_type(type_float, type_char_ptr);
5900 case T___builtin_nand:
5901 return make_function_1_type(type_long_double, type_char_ptr);
5902 case T___builtin_va_end:
5903 return make_function_1_type(type_void, type_valist);
5904 case T___builtin_expect:
5905 return make_function_2_type(type_long, type_long, type_long);
5907 internal_errorf(HERE, "not implemented builtin symbol found");
5912 * Performs automatic type cast as described in § 6.3.2.1.
5914 * @param orig_type the original type
5916 static type_t *automatic_type_conversion(type_t *orig_type)
5918 type_t *type = skip_typeref(orig_type);
5919 if (is_type_array(type)) {
5920 array_type_t *array_type = &type->array;
5921 type_t *element_type = array_type->element_type;
5922 unsigned qualifiers = array_type->base.qualifiers;
5924 return make_pointer_type(element_type, qualifiers);
5927 if (is_type_function(type)) {
5928 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5935 * reverts the automatic casts of array to pointer types and function
5936 * to function-pointer types as defined § 6.3.2.1
5938 type_t *revert_automatic_type_conversion(const expression_t *expression)
5940 switch (expression->kind) {
5941 case EXPR_REFERENCE: return expression->reference.declaration->type;
5944 return get_qualified_type(expression->select.compound_entry->type,
5945 expression->base.type->base.qualifiers);
5947 case EXPR_UNARY_DEREFERENCE: {
5948 const expression_t *const value = expression->unary.value;
5949 type_t *const type = skip_typeref(value->base.type);
5950 assert(is_type_pointer(type));
5951 return type->pointer.points_to;
5954 case EXPR_BUILTIN_SYMBOL:
5955 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5957 case EXPR_ARRAY_ACCESS: {
5958 const expression_t *array_ref = expression->array_access.array_ref;
5959 type_t *type_left = skip_typeref(array_ref->base.type);
5960 if (!is_type_valid(type_left))
5962 assert(is_type_pointer(type_left));
5963 return type_left->pointer.points_to;
5966 case EXPR_STRING_LITERAL: {
5967 size_t size = expression->string.value.size;
5968 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5971 case EXPR_WIDE_STRING_LITERAL: {
5972 size_t size = expression->wide_string.value.size;
5973 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5976 case EXPR_COMPOUND_LITERAL:
5977 return expression->compound_literal.type;
5982 return expression->base.type;
5985 static expression_t *parse_reference(void)
5987 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5989 reference_expression_t *ref = &expression->reference;
5990 symbol_t *const symbol = token.v.symbol;
5992 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5994 source_position_t source_position = token.source_position;
5997 if (declaration == NULL) {
5998 if (token.type == '(') {
5999 /* an implicitly declared function */
6001 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6002 } else if (warning.implicit_function_declaration) {
6003 warningf(HERE, "implicit declaration of function '%Y'",
6007 declaration = create_implicit_function(symbol,
6010 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6011 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6015 type_t *type = declaration->type;
6017 /* we always do the auto-type conversions; the & and sizeof parser contains
6018 * code to revert this! */
6019 type = automatic_type_conversion(type);
6021 ref->declaration = declaration;
6022 ref->base.type = type;
6024 /* this declaration is used */
6025 declaration->used = true;
6027 /* check for deprecated functions */
6028 if (warning.deprecated_declarations &&
6029 declaration->modifiers & DM_DEPRECATED) {
6030 char const *const prefix = is_type_function(declaration->type) ?
6031 "function" : "variable";
6033 if (declaration->deprecated_string != NULL) {
6034 warningf(&source_position,
6035 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
6036 declaration->symbol, &declaration->source_position,
6037 declaration->deprecated_string);
6039 warningf(&source_position,
6040 "%s '%Y' is deprecated (declared %P)", prefix,
6041 declaration->symbol, &declaration->source_position);
6044 if (warning.init_self && declaration == current_init_decl) {
6045 current_init_decl = NULL;
6046 warningf(&source_position,
6047 "variable '%#T' is initialized by itself",
6048 declaration->type, declaration->symbol);
6054 static bool semantic_cast(expression_t *cast)
6056 expression_t *expression = cast->unary.value;
6057 type_t *orig_dest_type = cast->base.type;
6058 type_t *orig_type_right = expression->base.type;
6059 type_t const *dst_type = skip_typeref(orig_dest_type);
6060 type_t const *src_type = skip_typeref(orig_type_right);
6061 source_position_t const *pos = &cast->base.source_position;
6063 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6064 if (dst_type == type_void)
6067 /* only integer and pointer can be casted to pointer */
6068 if (is_type_pointer(dst_type) &&
6069 !is_type_pointer(src_type) &&
6070 !is_type_integer(src_type) &&
6071 is_type_valid(src_type)) {
6072 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6076 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6077 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6081 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6082 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6086 if (warning.cast_qual &&
6087 is_type_pointer(src_type) &&
6088 is_type_pointer(dst_type)) {
6089 type_t *src = skip_typeref(src_type->pointer.points_to);
6090 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6091 unsigned missing_qualifiers =
6092 src->base.qualifiers & ~dst->base.qualifiers;
6093 if (missing_qualifiers != 0) {
6095 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6096 missing_qualifiers, orig_type_right);
6102 static expression_t *parse_compound_literal(type_t *type)
6104 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6106 parse_initializer_env_t env;
6108 env.declaration = NULL;
6109 env.must_be_constant = false;
6110 initializer_t *initializer = parse_initializer(&env);
6113 expression->compound_literal.initializer = initializer;
6114 expression->compound_literal.type = type;
6115 expression->base.type = automatic_type_conversion(type);
6121 * Parse a cast expression.
6123 static expression_t *parse_cast(void)
6125 source_position_t source_position = token.source_position;
6127 type_t *type = parse_typename();
6129 /* matching add_anchor_token() is at call site */
6130 rem_anchor_token(')');
6133 if (token.type == '{') {
6134 return parse_compound_literal(type);
6137 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6138 cast->base.source_position = source_position;
6140 expression_t *value = parse_sub_expression(20);
6141 cast->base.type = type;
6142 cast->unary.value = value;
6144 if (! semantic_cast(cast)) {
6145 /* TODO: record the error in the AST. else it is impossible to detect it */
6150 return create_invalid_expression();
6154 * Parse a statement expression.
6156 static expression_t *parse_statement_expression(void)
6158 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6160 statement_t *statement = parse_compound_statement(true);
6161 expression->statement.statement = statement;
6162 expression->base.source_position = statement->base.source_position;
6164 /* find last statement and use its type */
6165 type_t *type = type_void;
6166 const statement_t *stmt = statement->compound.statements;
6168 while (stmt->base.next != NULL)
6169 stmt = stmt->base.next;
6171 if (stmt->kind == STATEMENT_EXPRESSION) {
6172 type = stmt->expression.expression->base.type;
6175 warningf(&expression->base.source_position, "empty statement expression ({})");
6177 expression->base.type = type;
6183 return create_invalid_expression();
6187 * Parse a parenthesized expression.
6189 static expression_t *parse_parenthesized_expression(void)
6192 add_anchor_token(')');
6194 switch(token.type) {
6196 /* gcc extension: a statement expression */
6197 return parse_statement_expression();
6201 return parse_cast();
6203 if (is_typedef_symbol(token.v.symbol)) {
6204 return parse_cast();
6208 expression_t *result = parse_expression();
6209 rem_anchor_token(')');
6214 return create_invalid_expression();
6217 static expression_t *parse_function_keyword(void)
6222 if (current_function == NULL) {
6223 errorf(HERE, "'__func__' used outside of a function");
6226 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6227 expression->base.type = type_char_ptr;
6228 expression->funcname.kind = FUNCNAME_FUNCTION;
6233 static expression_t *parse_pretty_function_keyword(void)
6235 eat(T___PRETTY_FUNCTION__);
6237 if (current_function == NULL) {
6238 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6241 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6242 expression->base.type = type_char_ptr;
6243 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6248 static expression_t *parse_funcsig_keyword(void)
6252 if (current_function == NULL) {
6253 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6256 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6257 expression->base.type = type_char_ptr;
6258 expression->funcname.kind = FUNCNAME_FUNCSIG;
6263 static expression_t *parse_funcdname_keyword(void)
6265 eat(T___FUNCDNAME__);
6267 if (current_function == NULL) {
6268 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6271 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6272 expression->base.type = type_char_ptr;
6273 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6278 static designator_t *parse_designator(void)
6280 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6281 result->source_position = *HERE;
6283 if (token.type != T_IDENTIFIER) {
6284 parse_error_expected("while parsing member designator",
6285 T_IDENTIFIER, NULL);
6288 result->symbol = token.v.symbol;
6291 designator_t *last_designator = result;
6293 if (token.type == '.') {
6295 if (token.type != T_IDENTIFIER) {
6296 parse_error_expected("while parsing member designator",
6297 T_IDENTIFIER, NULL);
6300 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6301 designator->source_position = *HERE;
6302 designator->symbol = token.v.symbol;
6305 last_designator->next = designator;
6306 last_designator = designator;
6309 if (token.type == '[') {
6311 add_anchor_token(']');
6312 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6313 designator->source_position = *HERE;
6314 designator->array_index = parse_expression();
6315 rem_anchor_token(']');
6317 if (designator->array_index == NULL) {
6321 last_designator->next = designator;
6322 last_designator = designator;
6334 * Parse the __builtin_offsetof() expression.
6336 static expression_t *parse_offsetof(void)
6338 eat(T___builtin_offsetof);
6340 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6341 expression->base.type = type_size_t;
6344 add_anchor_token(',');
6345 type_t *type = parse_typename();
6346 rem_anchor_token(',');
6348 add_anchor_token(')');
6349 designator_t *designator = parse_designator();
6350 rem_anchor_token(')');
6353 expression->offsetofe.type = type;
6354 expression->offsetofe.designator = designator;
6357 memset(&path, 0, sizeof(path));
6358 path.top_type = type;
6359 path.path = NEW_ARR_F(type_path_entry_t, 0);
6361 descend_into_subtype(&path);
6363 if (!walk_designator(&path, designator, true)) {
6364 return create_invalid_expression();
6367 DEL_ARR_F(path.path);
6371 return create_invalid_expression();
6375 * Parses a _builtin_va_start() expression.
6377 static expression_t *parse_va_start(void)
6379 eat(T___builtin_va_start);
6381 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6384 add_anchor_token(',');
6385 expression->va_starte.ap = parse_assignment_expression();
6386 rem_anchor_token(',');
6388 expression_t *const expr = parse_assignment_expression();
6389 if (expr->kind == EXPR_REFERENCE) {
6390 declaration_t *const decl = expr->reference.declaration;
6392 return create_invalid_expression();
6393 if (decl->parent_scope == ¤t_function->scope &&
6394 decl->next == NULL) {
6395 expression->va_starte.parameter = decl;
6400 errorf(&expr->base.source_position,
6401 "second argument of 'va_start' must be last parameter of the current function");
6403 return create_invalid_expression();
6407 * Parses a _builtin_va_arg() expression.
6409 static expression_t *parse_va_arg(void)
6411 eat(T___builtin_va_arg);
6413 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6416 expression->va_arge.ap = parse_assignment_expression();
6418 expression->base.type = parse_typename();
6423 return create_invalid_expression();
6426 static expression_t *parse_builtin_symbol(void)
6428 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6430 symbol_t *symbol = token.v.symbol;
6432 expression->builtin_symbol.symbol = symbol;
6435 type_t *type = get_builtin_symbol_type(symbol);
6436 type = automatic_type_conversion(type);
6438 expression->base.type = type;
6443 * Parses a __builtin_constant() expression.
6445 static expression_t *parse_builtin_constant(void)
6447 eat(T___builtin_constant_p);
6449 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6452 add_anchor_token(')');
6453 expression->builtin_constant.value = parse_assignment_expression();
6454 rem_anchor_token(')');
6456 expression->base.type = type_int;
6460 return create_invalid_expression();
6464 * Parses a __builtin_prefetch() expression.
6466 static expression_t *parse_builtin_prefetch(void)
6468 eat(T___builtin_prefetch);
6470 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6473 add_anchor_token(')');
6474 expression->builtin_prefetch.adr = parse_assignment_expression();
6475 if (token.type == ',') {
6477 expression->builtin_prefetch.rw = parse_assignment_expression();
6479 if (token.type == ',') {
6481 expression->builtin_prefetch.locality = parse_assignment_expression();
6483 rem_anchor_token(')');
6485 expression->base.type = type_void;
6489 return create_invalid_expression();
6493 * Parses a __builtin_is_*() compare expression.
6495 static expression_t *parse_compare_builtin(void)
6497 expression_t *expression;
6499 switch(token.type) {
6500 case T___builtin_isgreater:
6501 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6503 case T___builtin_isgreaterequal:
6504 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6506 case T___builtin_isless:
6507 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6509 case T___builtin_islessequal:
6510 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6512 case T___builtin_islessgreater:
6513 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6515 case T___builtin_isunordered:
6516 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6519 internal_errorf(HERE, "invalid compare builtin found");
6522 expression->base.source_position = *HERE;
6526 expression->binary.left = parse_assignment_expression();
6528 expression->binary.right = parse_assignment_expression();
6531 type_t *const orig_type_left = expression->binary.left->base.type;
6532 type_t *const orig_type_right = expression->binary.right->base.type;
6534 type_t *const type_left = skip_typeref(orig_type_left);
6535 type_t *const type_right = skip_typeref(orig_type_right);
6536 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6537 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6538 type_error_incompatible("invalid operands in comparison",
6539 &expression->base.source_position, orig_type_left, orig_type_right);
6542 semantic_comparison(&expression->binary);
6547 return create_invalid_expression();
6552 * Parses a __builtin_expect() expression.
6554 static expression_t *parse_builtin_expect(void)
6556 eat(T___builtin_expect);
6558 expression_t *expression
6559 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6562 expression->binary.left = parse_assignment_expression();
6564 expression->binary.right = parse_constant_expression();
6567 expression->base.type = expression->binary.left->base.type;
6571 return create_invalid_expression();
6576 * Parses a MS assume() expression.
6578 static expression_t *parse_assume(void)
6582 expression_t *expression
6583 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6586 add_anchor_token(')');
6587 expression->unary.value = parse_assignment_expression();
6588 rem_anchor_token(')');
6591 expression->base.type = type_void;
6594 return create_invalid_expression();
6598 * Parse a microsoft __noop expression.
6600 static expression_t *parse_noop_expression(void)
6602 source_position_t source_position = *HERE;
6605 if (token.type == '(') {
6606 /* parse arguments */
6608 add_anchor_token(')');
6609 add_anchor_token(',');
6611 if (token.type != ')') {
6613 (void)parse_assignment_expression();
6614 if (token.type != ',')
6620 rem_anchor_token(',');
6621 rem_anchor_token(')');
6624 /* the result is a (int)0 */
6625 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6626 cnst->base.source_position = source_position;
6627 cnst->base.type = type_int;
6628 cnst->conste.v.int_value = 0;
6629 cnst->conste.is_ms_noop = true;
6634 return create_invalid_expression();
6638 * Parses a primary expression.
6640 static expression_t *parse_primary_expression(void)
6642 switch (token.type) {
6643 case T_INTEGER: return parse_int_const();
6644 case T_CHARACTER_CONSTANT: return parse_character_constant();
6645 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6646 case T_FLOATINGPOINT: return parse_float_const();
6647 case T_STRING_LITERAL:
6648 case T_WIDE_STRING_LITERAL: return parse_string_const();
6649 case T_IDENTIFIER: return parse_reference();
6650 case T___FUNCTION__:
6651 case T___func__: return parse_function_keyword();
6652 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6653 case T___FUNCSIG__: return parse_funcsig_keyword();
6654 case T___FUNCDNAME__: return parse_funcdname_keyword();
6655 case T___builtin_offsetof: return parse_offsetof();
6656 case T___builtin_va_start: return parse_va_start();
6657 case T___builtin_va_arg: return parse_va_arg();
6658 case T___builtin_expect:
6659 case T___builtin_alloca:
6660 case T___builtin_nan:
6661 case T___builtin_nand:
6662 case T___builtin_nanf:
6663 case T___builtin_huge_val:
6664 case T___builtin_va_end: return parse_builtin_symbol();
6665 case T___builtin_isgreater:
6666 case T___builtin_isgreaterequal:
6667 case T___builtin_isless:
6668 case T___builtin_islessequal:
6669 case T___builtin_islessgreater:
6670 case T___builtin_isunordered: return parse_compare_builtin();
6671 case T___builtin_constant_p: return parse_builtin_constant();
6672 case T___builtin_prefetch: return parse_builtin_prefetch();
6673 case T__assume: return parse_assume();
6675 case '(': return parse_parenthesized_expression();
6676 case T___noop: return parse_noop_expression();
6679 errorf(HERE, "unexpected token %K, expected an expression", &token);
6680 return create_invalid_expression();
6684 * Check if the expression has the character type and issue a warning then.
6686 static void check_for_char_index_type(const expression_t *expression)
6688 type_t *const type = expression->base.type;
6689 const type_t *const base_type = skip_typeref(type);
6691 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6692 warning.char_subscripts) {
6693 warningf(&expression->base.source_position,
6694 "array subscript has type '%T'", type);
6698 static expression_t *parse_array_expression(unsigned precedence,
6704 add_anchor_token(']');
6706 expression_t *inside = parse_expression();
6708 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6710 array_access_expression_t *array_access = &expression->array_access;
6712 type_t *const orig_type_left = left->base.type;
6713 type_t *const orig_type_inside = inside->base.type;
6715 type_t *const type_left = skip_typeref(orig_type_left);
6716 type_t *const type_inside = skip_typeref(orig_type_inside);
6718 type_t *return_type;
6719 if (is_type_pointer(type_left)) {
6720 return_type = type_left->pointer.points_to;
6721 array_access->array_ref = left;
6722 array_access->index = inside;
6723 check_for_char_index_type(inside);
6724 } else if (is_type_pointer(type_inside)) {
6725 return_type = type_inside->pointer.points_to;
6726 array_access->array_ref = inside;
6727 array_access->index = left;
6728 array_access->flipped = true;
6729 check_for_char_index_type(left);
6731 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6733 "array access on object with non-pointer types '%T', '%T'",
6734 orig_type_left, orig_type_inside);
6736 return_type = type_error_type;
6737 array_access->array_ref = create_invalid_expression();
6740 rem_anchor_token(']');
6741 if (token.type != ']') {
6742 parse_error_expected("Problem while parsing array access", ']', NULL);
6747 return_type = automatic_type_conversion(return_type);
6748 expression->base.type = return_type;
6753 static expression_t *parse_typeprop(expression_kind_t const kind,
6754 source_position_t const pos,
6755 unsigned const precedence)
6757 expression_t *tp_expression = allocate_expression_zero(kind);
6758 tp_expression->base.type = type_size_t;
6759 tp_expression->base.source_position = pos;
6761 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6763 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6765 add_anchor_token(')');
6766 type_t* const orig_type = parse_typename();
6767 tp_expression->typeprop.type = orig_type;
6769 type_t const* const type = skip_typeref(orig_type);
6770 char const* const wrong_type =
6771 is_type_incomplete(type) ? "incomplete" :
6772 type->kind == TYPE_FUNCTION ? "function designator" :
6773 type->kind == TYPE_BITFIELD ? "bitfield" :
6775 if (wrong_type != NULL) {
6776 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6777 what, wrong_type, type);
6780 rem_anchor_token(')');
6783 expression_t *expression = parse_sub_expression(precedence);
6785 type_t* const orig_type = revert_automatic_type_conversion(expression);
6786 expression->base.type = orig_type;
6788 type_t const* const type = skip_typeref(orig_type);
6789 char const* const wrong_type =
6790 is_type_incomplete(type) ? "incomplete" :
6791 type->kind == TYPE_FUNCTION ? "function designator" :
6792 type->kind == TYPE_BITFIELD ? "bitfield" :
6794 if (wrong_type != NULL) {
6795 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6798 tp_expression->typeprop.type = expression->base.type;
6799 tp_expression->typeprop.tp_expression = expression;
6802 return tp_expression;
6804 return create_invalid_expression();
6807 static expression_t *parse_sizeof(unsigned precedence)
6809 source_position_t pos = *HERE;
6811 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6814 static expression_t *parse_alignof(unsigned precedence)
6816 source_position_t pos = *HERE;
6818 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6821 static expression_t *parse_select_expression(unsigned precedence,
6822 expression_t *compound)
6825 assert(token.type == '.' || token.type == T_MINUSGREATER);
6827 bool is_pointer = (token.type == T_MINUSGREATER);
6830 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6831 select->select.compound = compound;
6833 if (token.type != T_IDENTIFIER) {
6834 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6837 symbol_t *symbol = token.v.symbol;
6840 type_t *const orig_type = compound->base.type;
6841 type_t *const type = skip_typeref(orig_type);
6844 bool saw_error = false;
6845 if (is_type_pointer(type)) {
6848 "request for member '%Y' in something not a struct or union, but '%T'",
6852 type_left = skip_typeref(type->pointer.points_to);
6854 if (is_pointer && is_type_valid(type)) {
6855 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6861 declaration_t *entry;
6862 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
6863 type_left->kind == TYPE_COMPOUND_UNION) {
6864 declaration_t *const declaration = type_left->compound.declaration;
6866 if (!declaration->init.complete) {
6867 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6869 return create_invalid_expression();
6872 entry = find_compound_entry(declaration, symbol);
6873 if (entry == NULL) {
6874 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6875 goto create_error_entry;
6878 if (is_type_valid(type_left) && !saw_error) {
6880 "request for member '%Y' in something not a struct or union, but '%T'",
6884 entry = allocate_declaration_zero();
6885 entry->symbol = symbol;
6888 select->select.compound_entry = entry;
6890 type_t *const res_type =
6891 get_qualified_type(entry->type, type_left->base.qualifiers);
6893 /* we always do the auto-type conversions; the & and sizeof parser contains
6894 * code to revert this! */
6895 select->base.type = automatic_type_conversion(res_type);
6897 type_t *skipped = skip_typeref(res_type);
6898 if (skipped->kind == TYPE_BITFIELD) {
6899 select->base.type = skipped->bitfield.base_type;
6905 static void check_call_argument(const function_parameter_t *parameter,
6906 call_argument_t *argument, unsigned pos)
6908 type_t *expected_type = parameter->type;
6909 type_t *expected_type_skip = skip_typeref(expected_type);
6910 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6911 expression_t *arg_expr = argument->expression;
6912 type_t *arg_type = skip_typeref(arg_expr->base.type);
6914 /* handle transparent union gnu extension */
6915 if (is_type_union(expected_type_skip)
6916 && (expected_type_skip->base.modifiers
6917 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6918 declaration_t *union_decl = expected_type_skip->compound.declaration;
6920 declaration_t *declaration = union_decl->scope.declarations;
6921 type_t *best_type = NULL;
6922 for ( ; declaration != NULL; declaration = declaration->next) {
6923 type_t *decl_type = declaration->type;
6924 error = semantic_assign(decl_type, arg_expr);
6925 if (error == ASSIGN_ERROR_INCOMPATIBLE
6926 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6929 if (error == ASSIGN_SUCCESS) {
6930 best_type = decl_type;
6931 } else if (best_type == NULL) {
6932 best_type = decl_type;
6936 if (best_type != NULL) {
6937 expected_type = best_type;
6941 error = semantic_assign(expected_type, arg_expr);
6942 argument->expression = create_implicit_cast(argument->expression,
6945 if (error != ASSIGN_SUCCESS) {
6946 /* report exact scope in error messages (like "in argument 3") */
6948 snprintf(buf, sizeof(buf), "call argument %u", pos);
6949 report_assign_error(error, expected_type, arg_expr, buf,
6950 &arg_expr->base.source_position);
6951 } else if (warning.traditional | warning.conversion) {
6953 /* passing as integer instead of float or complex */
6954 (is_type_integer(expected_type) &&
6955 (is_type_float(arg_type) || is_type_complex(arg_type))) ||
6956 /* passing as complex instead of integer or float */
6957 (is_type_complex(expected_type) &&
6958 (is_type_integer(arg_type) || is_type_float(arg_type))) ||
6959 /* passing as float instead of integer or complex */
6960 (is_type_float(expected_type) &&
6961 (is_type_integer(arg_type) || is_type_complex(arg_type))) ||
6962 /* passing as float instead of double */
6963 (is_type_float(expected_type) && expected_type != type_double &&
6964 is_type_float(arg_type))) {
6965 warningf(&arg_expr->base.source_position,
6966 "passing call argument %u as '%T' rather than '%T' due to prototype",
6967 pos, expected_type, arg_type);
6969 if (is_type_integer(expected_type) && is_type_integer(arg_type)) {
6970 /* TODO check for size HERE */
6976 * Parse a call expression, ie. expression '( ... )'.
6978 * @param expression the function address
6980 static expression_t *parse_call_expression(unsigned precedence,
6981 expression_t *expression)
6984 expression_t *result = allocate_expression_zero(EXPR_CALL);
6985 result->base.source_position = expression->base.source_position;
6987 call_expression_t *call = &result->call;
6988 call->function = expression;
6990 type_t *const orig_type = expression->base.type;
6991 type_t *const type = skip_typeref(orig_type);
6993 function_type_t *function_type = NULL;
6994 if (is_type_pointer(type)) {
6995 type_t *const to_type = skip_typeref(type->pointer.points_to);
6997 if (is_type_function(to_type)) {
6998 function_type = &to_type->function;
6999 call->base.type = function_type->return_type;
7003 if (function_type == NULL && is_type_valid(type)) {
7004 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7007 /* parse arguments */
7009 add_anchor_token(')');
7010 add_anchor_token(',');
7012 if (token.type != ')') {
7013 call_argument_t *last_argument = NULL;
7016 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7018 argument->expression = parse_assignment_expression();
7019 if (last_argument == NULL) {
7020 call->arguments = argument;
7022 last_argument->next = argument;
7024 last_argument = argument;
7026 if (token.type != ',')
7031 rem_anchor_token(',');
7032 rem_anchor_token(')');
7035 if (function_type == NULL)
7038 function_parameter_t *parameter = function_type->parameters;
7039 call_argument_t *argument = call->arguments;
7040 if (!function_type->unspecified_parameters) {
7041 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7042 parameter = parameter->next, argument = argument->next) {
7043 check_call_argument(parameter, argument, ++pos);
7046 if (parameter != NULL) {
7047 errorf(HERE, "too few arguments to function '%E'", expression);
7048 } else if (argument != NULL && !function_type->variadic) {
7049 errorf(HERE, "too many arguments to function '%E'", expression);
7053 /* do default promotion */
7054 for( ; argument != NULL; argument = argument->next) {
7055 type_t *type = argument->expression->base.type;
7057 type = get_default_promoted_type(type);
7059 argument->expression
7060 = create_implicit_cast(argument->expression, type);
7063 check_format(&result->call);
7065 if (warning.aggregate_return &&
7066 is_type_compound(skip_typeref(function_type->return_type))) {
7067 warningf(&result->base.source_position,
7068 "function call has aggregate value");
7073 return create_invalid_expression();
7076 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7078 static bool same_compound_type(const type_t *type1, const type_t *type2)
7081 is_type_compound(type1) &&
7082 type1->kind == type2->kind &&
7083 type1->compound.declaration == type2->compound.declaration;
7087 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7089 * @param expression the conditional expression
7091 static expression_t *parse_conditional_expression(unsigned precedence,
7092 expression_t *expression)
7094 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7096 conditional_expression_t *conditional = &result->conditional;
7097 conditional->base.source_position = *HERE;
7098 conditional->condition = expression;
7101 add_anchor_token(':');
7104 type_t *const condition_type_orig = expression->base.type;
7105 type_t *const condition_type = skip_typeref(condition_type_orig);
7106 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7107 type_error("expected a scalar type in conditional condition",
7108 &expression->base.source_position, condition_type_orig);
7111 expression_t *true_expression = expression;
7112 bool gnu_cond = false;
7113 if ((c_mode & _GNUC) && token.type == ':') {
7116 true_expression = parse_expression();
7117 rem_anchor_token(':');
7119 expression_t *false_expression = parse_sub_expression(precedence);
7121 type_t *const orig_true_type = true_expression->base.type;
7122 type_t *const orig_false_type = false_expression->base.type;
7123 type_t *const true_type = skip_typeref(orig_true_type);
7124 type_t *const false_type = skip_typeref(orig_false_type);
7127 type_t *result_type;
7128 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7129 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7130 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7131 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7132 warningf(&conditional->base.source_position,
7133 "ISO C forbids conditional expression with only one void side");
7135 result_type = type_void;
7136 } else if (is_type_arithmetic(true_type)
7137 && is_type_arithmetic(false_type)) {
7138 result_type = semantic_arithmetic(true_type, false_type);
7140 true_expression = create_implicit_cast(true_expression, result_type);
7141 false_expression = create_implicit_cast(false_expression, result_type);
7143 conditional->true_expression = true_expression;
7144 conditional->false_expression = false_expression;
7145 conditional->base.type = result_type;
7146 } else if (same_compound_type(true_type, false_type)) {
7147 /* just take 1 of the 2 types */
7148 result_type = true_type;
7149 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7150 type_t *pointer_type;
7152 expression_t *other_expression;
7153 if (is_type_pointer(true_type) &&
7154 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7155 pointer_type = true_type;
7156 other_type = false_type;
7157 other_expression = false_expression;
7159 pointer_type = false_type;
7160 other_type = true_type;
7161 other_expression = true_expression;
7164 if (is_null_pointer_constant(other_expression)) {
7165 result_type = pointer_type;
7166 } else if (is_type_pointer(other_type)) {
7167 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7168 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7171 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7172 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7174 } else if (types_compatible(get_unqualified_type(to1),
7175 get_unqualified_type(to2))) {
7178 warningf(&conditional->base.source_position,
7179 "pointer types '%T' and '%T' in conditional expression are incompatible",
7180 true_type, false_type);
7184 type_t *const type =
7185 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7186 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7187 } else if (is_type_integer(other_type)) {
7188 warningf(&conditional->base.source_position,
7189 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7190 result_type = pointer_type;
7192 type_error_incompatible("while parsing conditional",
7193 &expression->base.source_position, true_type, false_type);
7194 result_type = type_error_type;
7197 /* TODO: one pointer to void*, other some pointer */
7199 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7200 type_error_incompatible("while parsing conditional",
7201 &conditional->base.source_position, true_type,
7204 result_type = type_error_type;
7207 conditional->true_expression
7208 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7209 conditional->false_expression
7210 = create_implicit_cast(false_expression, result_type);
7211 conditional->base.type = result_type;
7214 return create_invalid_expression();
7218 * Parse an extension expression.
7220 static expression_t *parse_extension(unsigned precedence)
7222 eat(T___extension__);
7224 /* TODO enable extensions */
7225 expression_t *expression = parse_sub_expression(precedence);
7226 /* TODO disable extensions */
7231 * Parse a __builtin_classify_type() expression.
7233 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7235 eat(T___builtin_classify_type);
7237 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7238 result->base.type = type_int;
7241 add_anchor_token(')');
7242 expression_t *expression = parse_sub_expression(precedence);
7243 rem_anchor_token(')');
7245 result->classify_type.type_expression = expression;
7249 return create_invalid_expression();
7252 static bool check_pointer_arithmetic(const source_position_t *source_position,
7253 type_t *pointer_type,
7254 type_t *orig_pointer_type)
7256 type_t *points_to = pointer_type->pointer.points_to;
7257 points_to = skip_typeref(points_to);
7259 if (is_type_incomplete(points_to)) {
7260 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7261 errorf(source_position,
7262 "arithmetic with pointer to incomplete type '%T' not allowed",
7265 } else if (warning.pointer_arith) {
7266 warningf(source_position,
7267 "pointer of type '%T' used in arithmetic",
7270 } else if (is_type_function(points_to)) {
7271 if (!(c_mode && _GNUC)) {
7272 errorf(source_position,
7273 "arithmetic with pointer to function type '%T' not allowed",
7276 } else if (warning.pointer_arith) {
7277 warningf(source_position,
7278 "pointer to a function '%T' used in arithmetic",
7285 static bool is_lvalue(const expression_t *expression)
7287 switch (expression->kind) {
7288 case EXPR_REFERENCE:
7289 case EXPR_ARRAY_ACCESS:
7291 case EXPR_UNARY_DEREFERENCE:
7299 static void semantic_incdec(unary_expression_t *expression)
7301 type_t *const orig_type = expression->value->base.type;
7302 type_t *const type = skip_typeref(orig_type);
7303 if (is_type_pointer(type)) {
7304 if (!check_pointer_arithmetic(&expression->base.source_position,
7308 } else if (!is_type_real(type) && is_type_valid(type)) {
7309 /* TODO: improve error message */
7310 errorf(&expression->base.source_position,
7311 "operation needs an arithmetic or pointer type");
7314 if (!is_lvalue(expression->value)) {
7315 /* TODO: improve error message */
7316 errorf(&expression->base.source_position, "lvalue required as operand");
7318 expression->base.type = orig_type;
7321 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7323 type_t *const orig_type = expression->value->base.type;
7324 type_t *const type = skip_typeref(orig_type);
7325 if (!is_type_arithmetic(type)) {
7326 if (is_type_valid(type)) {
7327 /* TODO: improve error message */
7328 errorf(&expression->base.source_position,
7329 "operation needs an arithmetic type");
7334 expression->base.type = orig_type;
7337 static void semantic_unexpr_plus(unary_expression_t *expression)
7339 semantic_unexpr_arithmetic(expression);
7340 if (warning.traditional)
7341 warningf(&expression->base.source_position,
7342 "traditional C rejects the unary plus operator");
7345 static void semantic_not(unary_expression_t *expression)
7347 type_t *const orig_type = expression->value->base.type;
7348 type_t *const type = skip_typeref(orig_type);
7349 if (!is_type_scalar(type) && is_type_valid(type)) {
7350 errorf(&expression->base.source_position,
7351 "operand of ! must be of scalar type");
7354 expression->base.type = type_int;
7357 static void semantic_unexpr_integer(unary_expression_t *expression)
7359 type_t *const orig_type = expression->value->base.type;
7360 type_t *const type = skip_typeref(orig_type);
7361 if (!is_type_integer(type)) {
7362 if (is_type_valid(type)) {
7363 errorf(&expression->base.source_position,
7364 "operand of ~ must be of integer type");
7369 expression->base.type = orig_type;
7372 static void semantic_dereference(unary_expression_t *expression)
7374 type_t *const orig_type = expression->value->base.type;
7375 type_t *const type = skip_typeref(orig_type);
7376 if (!is_type_pointer(type)) {
7377 if (is_type_valid(type)) {
7378 errorf(&expression->base.source_position,
7379 "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
7384 type_t *result_type = type->pointer.points_to;
7385 result_type = automatic_type_conversion(result_type);
7386 expression->base.type = result_type;
7390 * Record that an address is taken (expression represents an lvalue).
7392 * @param expression the expression
7393 * @param may_be_register if true, the expression might be an register
7395 static void set_address_taken(expression_t *expression, bool may_be_register)
7397 if (expression->kind != EXPR_REFERENCE)
7400 declaration_t *const declaration = expression->reference.declaration;
7401 /* happens for parse errors */
7402 if (declaration == NULL)
7405 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7406 errorf(&expression->base.source_position,
7407 "address of register variable '%Y' requested",
7408 declaration->symbol);
7410 declaration->address_taken = 1;
7415 * Check the semantic of the address taken expression.
7417 static void semantic_take_addr(unary_expression_t *expression)
7419 expression_t *value = expression->value;
7420 value->base.type = revert_automatic_type_conversion(value);
7422 type_t *orig_type = value->base.type;
7423 if (!is_type_valid(orig_type))
7426 set_address_taken(value, false);
7428 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7431 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7432 static expression_t *parse_##unexpression_type(unsigned precedence) \
7434 expression_t *unary_expression \
7435 = allocate_expression_zero(unexpression_type); \
7436 unary_expression->base.source_position = *HERE; \
7438 unary_expression->unary.value = parse_sub_expression(precedence); \
7440 sfunc(&unary_expression->unary); \
7442 return unary_expression; \
7445 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7446 semantic_unexpr_arithmetic)
7447 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7448 semantic_unexpr_plus)
7449 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7451 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7452 semantic_dereference)
7453 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7455 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7456 semantic_unexpr_integer)
7457 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7459 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7462 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7464 static expression_t *parse_##unexpression_type(unsigned precedence, \
7465 expression_t *left) \
7467 (void) precedence; \
7469 expression_t *unary_expression \
7470 = allocate_expression_zero(unexpression_type); \
7471 unary_expression->base.source_position = *HERE; \
7473 unary_expression->unary.value = left; \
7475 sfunc(&unary_expression->unary); \
7477 return unary_expression; \
7480 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7481 EXPR_UNARY_POSTFIX_INCREMENT,
7483 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7484 EXPR_UNARY_POSTFIX_DECREMENT,
7487 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7489 /* TODO: handle complex + imaginary types */
7491 /* § 6.3.1.8 Usual arithmetic conversions */
7492 if (type_left == type_long_double || type_right == type_long_double) {
7493 return type_long_double;
7494 } else if (type_left == type_double || type_right == type_double) {
7496 } else if (type_left == type_float || type_right == type_float) {
7500 type_left = promote_integer(type_left);
7501 type_right = promote_integer(type_right);
7503 if (type_left == type_right)
7506 bool const signed_left = is_type_signed(type_left);
7507 bool const signed_right = is_type_signed(type_right);
7508 int const rank_left = get_rank(type_left);
7509 int const rank_right = get_rank(type_right);
7511 if (signed_left == signed_right)
7512 return rank_left >= rank_right ? type_left : type_right;
7521 u_rank = rank_right;
7522 u_type = type_right;
7524 s_rank = rank_right;
7525 s_type = type_right;
7530 if (u_rank >= s_rank)
7533 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7535 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7536 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7540 case ATOMIC_TYPE_INT: return type_unsigned_int;
7541 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7542 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7544 default: panic("invalid atomic type");
7549 * Check the semantic restrictions for a binary expression.
7551 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7553 expression_t *const left = expression->left;
7554 expression_t *const right = expression->right;
7555 type_t *const orig_type_left = left->base.type;
7556 type_t *const orig_type_right = right->base.type;
7557 type_t *const type_left = skip_typeref(orig_type_left);
7558 type_t *const type_right = skip_typeref(orig_type_right);
7560 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7561 /* TODO: improve error message */
7562 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7563 errorf(&expression->base.source_position,
7564 "operation needs arithmetic types");
7569 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7570 expression->left = create_implicit_cast(left, arithmetic_type);
7571 expression->right = create_implicit_cast(right, arithmetic_type);
7572 expression->base.type = arithmetic_type;
7575 static void warn_div_by_zero(binary_expression_t const *const expression)
7577 if (warning.div_by_zero &&
7578 is_type_integer(expression->base.type) &&
7579 is_constant_expression(expression->right) &&
7580 fold_constant(expression->right) == 0) {
7581 warningf(&expression->base.source_position, "division by zero");
7586 * Check the semantic restrictions for a div/mod expression.
7588 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7589 semantic_binexpr_arithmetic(expression);
7590 warn_div_by_zero(expression);
7593 static void semantic_shift_op(binary_expression_t *expression)
7595 expression_t *const left = expression->left;
7596 expression_t *const right = expression->right;
7597 type_t *const orig_type_left = left->base.type;
7598 type_t *const orig_type_right = right->base.type;
7599 type_t * type_left = skip_typeref(orig_type_left);
7600 type_t * type_right = skip_typeref(orig_type_right);
7602 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7603 /* TODO: improve error message */
7604 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7605 errorf(&expression->base.source_position,
7606 "operands of shift operation must have integer types");
7611 type_left = promote_integer(type_left);
7612 type_right = promote_integer(type_right);
7614 expression->left = create_implicit_cast(left, type_left);
7615 expression->right = create_implicit_cast(right, type_right);
7616 expression->base.type = type_left;
7619 static void semantic_add(binary_expression_t *expression)
7621 expression_t *const left = expression->left;
7622 expression_t *const right = expression->right;
7623 type_t *const orig_type_left = left->base.type;
7624 type_t *const orig_type_right = right->base.type;
7625 type_t *const type_left = skip_typeref(orig_type_left);
7626 type_t *const type_right = skip_typeref(orig_type_right);
7629 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7630 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7631 expression->left = create_implicit_cast(left, arithmetic_type);
7632 expression->right = create_implicit_cast(right, arithmetic_type);
7633 expression->base.type = arithmetic_type;
7635 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7636 check_pointer_arithmetic(&expression->base.source_position,
7637 type_left, orig_type_left);
7638 expression->base.type = type_left;
7639 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7640 check_pointer_arithmetic(&expression->base.source_position,
7641 type_right, orig_type_right);
7642 expression->base.type = type_right;
7643 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7644 errorf(&expression->base.source_position,
7645 "invalid operands to binary + ('%T', '%T')",
7646 orig_type_left, orig_type_right);
7650 static void semantic_sub(binary_expression_t *expression)
7652 expression_t *const left = expression->left;
7653 expression_t *const right = expression->right;
7654 type_t *const orig_type_left = left->base.type;
7655 type_t *const orig_type_right = right->base.type;
7656 type_t *const type_left = skip_typeref(orig_type_left);
7657 type_t *const type_right = skip_typeref(orig_type_right);
7658 source_position_t const *const pos = &expression->base.source_position;
7661 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7662 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7663 expression->left = create_implicit_cast(left, arithmetic_type);
7664 expression->right = create_implicit_cast(right, arithmetic_type);
7665 expression->base.type = arithmetic_type;
7667 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7668 check_pointer_arithmetic(&expression->base.source_position,
7669 type_left, orig_type_left);
7670 expression->base.type = type_left;
7671 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7672 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7673 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7674 if (!types_compatible(unqual_left, unqual_right)) {
7676 "subtracting pointers to incompatible types '%T' and '%T'",
7677 orig_type_left, orig_type_right);
7678 } else if (!is_type_object(unqual_left)) {
7679 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7680 warningf(pos, "subtracting pointers to void");
7682 errorf(pos, "subtracting pointers to non-object types '%T'",
7686 expression->base.type = type_ptrdiff_t;
7687 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7688 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7689 orig_type_left, orig_type_right);
7694 * Check the semantics of comparison expressions.
7696 * @param expression The expression to check.
7698 static void semantic_comparison(binary_expression_t *expression)
7700 expression_t *left = expression->left;
7701 expression_t *right = expression->right;
7702 type_t *orig_type_left = left->base.type;
7703 type_t *orig_type_right = right->base.type;
7705 type_t *type_left = skip_typeref(orig_type_left);
7706 type_t *type_right = skip_typeref(orig_type_right);
7708 /* TODO non-arithmetic types */
7709 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7710 /* test for signed vs unsigned compares */
7711 if (warning.sign_compare &&
7712 (expression->base.kind != EXPR_BINARY_EQUAL &&
7713 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7714 (is_type_signed(type_left) != is_type_signed(type_right))) {
7716 /* check if 1 of the operands is a constant, in this case we just
7717 * check wether we can safely represent the resulting constant in
7718 * the type of the other operand. */
7719 expression_t *const_expr = NULL;
7720 expression_t *other_expr = NULL;
7722 if (is_constant_expression(left)) {
7725 } else if (is_constant_expression(right)) {
7730 if (const_expr != NULL) {
7731 type_t *other_type = skip_typeref(other_expr->base.type);
7732 long val = fold_constant(const_expr);
7733 /* TODO: check if val can be represented by other_type */
7737 warningf(&expression->base.source_position,
7738 "comparison between signed and unsigned");
7740 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7741 expression->left = create_implicit_cast(left, arithmetic_type);
7742 expression->right = create_implicit_cast(right, arithmetic_type);
7743 expression->base.type = arithmetic_type;
7744 if (warning.float_equal &&
7745 (expression->base.kind == EXPR_BINARY_EQUAL ||
7746 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7747 is_type_float(arithmetic_type)) {
7748 warningf(&expression->base.source_position,
7749 "comparing floating point with == or != is unsafe");
7751 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7752 /* TODO check compatibility */
7753 } else if (is_type_pointer(type_left)) {
7754 expression->right = create_implicit_cast(right, type_left);
7755 } else if (is_type_pointer(type_right)) {
7756 expression->left = create_implicit_cast(left, type_right);
7757 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7758 type_error_incompatible("invalid operands in comparison",
7759 &expression->base.source_position,
7760 type_left, type_right);
7762 expression->base.type = type_int;
7766 * Checks if a compound type has constant fields.
7768 static bool has_const_fields(const compound_type_t *type)
7770 const scope_t *scope = &type->declaration->scope;
7771 const declaration_t *declaration = scope->declarations;
7773 for (; declaration != NULL; declaration = declaration->next) {
7774 if (declaration->namespc != NAMESPACE_NORMAL)
7777 const type_t *decl_type = skip_typeref(declaration->type);
7778 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7785 static bool is_valid_assignment_lhs(expression_t const* const left)
7787 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7788 type_t *const type_left = skip_typeref(orig_type_left);
7790 if (!is_lvalue(left)) {
7791 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7796 if (is_type_array(type_left)) {
7797 errorf(HERE, "cannot assign to arrays ('%E')", left);
7800 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7801 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7805 if (is_type_incomplete(type_left)) {
7806 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7807 left, orig_type_left);
7810 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7811 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7812 left, orig_type_left);
7819 static void semantic_arithmetic_assign(binary_expression_t *expression)
7821 expression_t *left = expression->left;
7822 expression_t *right = expression->right;
7823 type_t *orig_type_left = left->base.type;
7824 type_t *orig_type_right = right->base.type;
7826 if (!is_valid_assignment_lhs(left))
7829 type_t *type_left = skip_typeref(orig_type_left);
7830 type_t *type_right = skip_typeref(orig_type_right);
7832 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7833 /* TODO: improve error message */
7834 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7835 errorf(&expression->base.source_position,
7836 "operation needs arithmetic types");
7841 /* combined instructions are tricky. We can't create an implicit cast on
7842 * the left side, because we need the uncasted form for the store.
7843 * The ast2firm pass has to know that left_type must be right_type
7844 * for the arithmetic operation and create a cast by itself */
7845 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7846 expression->right = create_implicit_cast(right, arithmetic_type);
7847 expression->base.type = type_left;
7850 static void semantic_divmod_assign(binary_expression_t *expression)
7852 semantic_arithmetic_assign(expression);
7853 warn_div_by_zero(expression);
7856 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7858 expression_t *const left = expression->left;
7859 expression_t *const right = expression->right;
7860 type_t *const orig_type_left = left->base.type;
7861 type_t *const orig_type_right = right->base.type;
7862 type_t *const type_left = skip_typeref(orig_type_left);
7863 type_t *const type_right = skip_typeref(orig_type_right);
7865 if (!is_valid_assignment_lhs(left))
7868 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7869 /* combined instructions are tricky. We can't create an implicit cast on
7870 * the left side, because we need the uncasted form for the store.
7871 * The ast2firm pass has to know that left_type must be right_type
7872 * for the arithmetic operation and create a cast by itself */
7873 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7874 expression->right = create_implicit_cast(right, arithmetic_type);
7875 expression->base.type = type_left;
7876 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7877 check_pointer_arithmetic(&expression->base.source_position,
7878 type_left, orig_type_left);
7879 expression->base.type = type_left;
7880 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7881 errorf(&expression->base.source_position,
7882 "incompatible types '%T' and '%T' in assignment",
7883 orig_type_left, orig_type_right);
7888 * Check the semantic restrictions of a logical expression.
7890 static void semantic_logical_op(binary_expression_t *expression)
7892 expression_t *const left = expression->left;
7893 expression_t *const right = expression->right;
7894 type_t *const orig_type_left = left->base.type;
7895 type_t *const orig_type_right = right->base.type;
7896 type_t *const type_left = skip_typeref(orig_type_left);
7897 type_t *const type_right = skip_typeref(orig_type_right);
7899 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7900 /* TODO: improve error message */
7901 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7902 errorf(&expression->base.source_position,
7903 "operation needs scalar types");
7908 expression->base.type = type_int;
7912 * Check the semantic restrictions of a binary assign expression.
7914 static void semantic_binexpr_assign(binary_expression_t *expression)
7916 expression_t *left = expression->left;
7917 type_t *orig_type_left = left->base.type;
7919 if (!is_valid_assignment_lhs(left))
7922 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7923 report_assign_error(error, orig_type_left, expression->right,
7924 "assignment", &left->base.source_position);
7925 expression->right = create_implicit_cast(expression->right, orig_type_left);
7926 expression->base.type = orig_type_left;
7930 * Determine if the outermost operation (or parts thereof) of the given
7931 * expression has no effect in order to generate a warning about this fact.
7932 * Therefore in some cases this only examines some of the operands of the
7933 * expression (see comments in the function and examples below).
7935 * f() + 23; // warning, because + has no effect
7936 * x || f(); // no warning, because x controls execution of f()
7937 * x ? y : f(); // warning, because y has no effect
7938 * (void)x; // no warning to be able to suppress the warning
7939 * This function can NOT be used for an "expression has definitely no effect"-
7941 static bool expression_has_effect(const expression_t *const expr)
7943 switch (expr->kind) {
7944 case EXPR_UNKNOWN: break;
7945 case EXPR_INVALID: return true; /* do NOT warn */
7946 case EXPR_REFERENCE: return false;
7947 /* suppress the warning for microsoft __noop operations */
7948 case EXPR_CONST: return expr->conste.is_ms_noop;
7949 case EXPR_CHARACTER_CONSTANT: return false;
7950 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
7951 case EXPR_STRING_LITERAL: return false;
7952 case EXPR_WIDE_STRING_LITERAL: return false;
7955 const call_expression_t *const call = &expr->call;
7956 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7959 switch (call->function->builtin_symbol.symbol->ID) {
7960 case T___builtin_va_end: return true;
7961 default: return false;
7965 /* Generate the warning if either the left or right hand side of a
7966 * conditional expression has no effect */
7967 case EXPR_CONDITIONAL: {
7968 const conditional_expression_t *const cond = &expr->conditional;
7970 expression_has_effect(cond->true_expression) &&
7971 expression_has_effect(cond->false_expression);
7974 case EXPR_SELECT: return false;
7975 case EXPR_ARRAY_ACCESS: return false;
7976 case EXPR_SIZEOF: return false;
7977 case EXPR_CLASSIFY_TYPE: return false;
7978 case EXPR_ALIGNOF: return false;
7980 case EXPR_FUNCNAME: return false;
7981 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7982 case EXPR_BUILTIN_CONSTANT_P: return false;
7983 case EXPR_BUILTIN_PREFETCH: return true;
7984 case EXPR_OFFSETOF: return false;
7985 case EXPR_VA_START: return true;
7986 case EXPR_VA_ARG: return true;
7987 case EXPR_STATEMENT: return true; // TODO
7988 case EXPR_COMPOUND_LITERAL: return false;
7990 case EXPR_UNARY_NEGATE: return false;
7991 case EXPR_UNARY_PLUS: return false;
7992 case EXPR_UNARY_BITWISE_NEGATE: return false;
7993 case EXPR_UNARY_NOT: return false;
7994 case EXPR_UNARY_DEREFERENCE: return false;
7995 case EXPR_UNARY_TAKE_ADDRESS: return false;
7996 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7997 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7998 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7999 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8001 /* Treat void casts as if they have an effect in order to being able to
8002 * suppress the warning */
8003 case EXPR_UNARY_CAST: {
8004 type_t *const type = skip_typeref(expr->base.type);
8005 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8008 case EXPR_UNARY_CAST_IMPLICIT: return true;
8009 case EXPR_UNARY_ASSUME: return true;
8011 case EXPR_BINARY_ADD: return false;
8012 case EXPR_BINARY_SUB: return false;
8013 case EXPR_BINARY_MUL: return false;
8014 case EXPR_BINARY_DIV: return false;
8015 case EXPR_BINARY_MOD: return false;
8016 case EXPR_BINARY_EQUAL: return false;
8017 case EXPR_BINARY_NOTEQUAL: return false;
8018 case EXPR_BINARY_LESS: return false;
8019 case EXPR_BINARY_LESSEQUAL: return false;
8020 case EXPR_BINARY_GREATER: return false;
8021 case EXPR_BINARY_GREATEREQUAL: return false;
8022 case EXPR_BINARY_BITWISE_AND: return false;
8023 case EXPR_BINARY_BITWISE_OR: return false;
8024 case EXPR_BINARY_BITWISE_XOR: return false;
8025 case EXPR_BINARY_SHIFTLEFT: return false;
8026 case EXPR_BINARY_SHIFTRIGHT: return false;
8027 case EXPR_BINARY_ASSIGN: return true;
8028 case EXPR_BINARY_MUL_ASSIGN: return true;
8029 case EXPR_BINARY_DIV_ASSIGN: return true;
8030 case EXPR_BINARY_MOD_ASSIGN: return true;
8031 case EXPR_BINARY_ADD_ASSIGN: return true;
8032 case EXPR_BINARY_SUB_ASSIGN: return true;
8033 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8034 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8035 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8036 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8037 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8039 /* Only examine the right hand side of && and ||, because the left hand
8040 * side already has the effect of controlling the execution of the right
8042 case EXPR_BINARY_LOGICAL_AND:
8043 case EXPR_BINARY_LOGICAL_OR:
8044 /* Only examine the right hand side of a comma expression, because the left
8045 * hand side has a separate warning */
8046 case EXPR_BINARY_COMMA:
8047 return expression_has_effect(expr->binary.right);
8049 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8050 case EXPR_BINARY_ISGREATER: return false;
8051 case EXPR_BINARY_ISGREATEREQUAL: return false;
8052 case EXPR_BINARY_ISLESS: return false;
8053 case EXPR_BINARY_ISLESSEQUAL: return false;
8054 case EXPR_BINARY_ISLESSGREATER: return false;
8055 case EXPR_BINARY_ISUNORDERED: return false;
8058 internal_errorf(HERE, "unexpected expression");
8061 static void semantic_comma(binary_expression_t *expression)
8063 if (warning.unused_value) {
8064 const expression_t *const left = expression->left;
8065 if (!expression_has_effect(left)) {
8066 warningf(&left->base.source_position,
8067 "left-hand operand of comma expression has no effect");
8070 expression->base.type = expression->right->base.type;
8073 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8074 static expression_t *parse_##binexpression_type(unsigned precedence, \
8075 expression_t *left) \
8077 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8078 binexpr->base.source_position = *HERE; \
8079 binexpr->binary.left = left; \
8082 expression_t *right = parse_sub_expression(precedence + lr); \
8084 binexpr->binary.right = right; \
8085 sfunc(&binexpr->binary); \
8090 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8091 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8092 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8093 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8094 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8095 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8096 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8097 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8098 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8100 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8101 semantic_comparison, 1)
8102 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8103 semantic_comparison, 1)
8104 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8105 semantic_comparison, 1)
8106 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8107 semantic_comparison, 1)
8109 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8110 semantic_binexpr_arithmetic, 1)
8111 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8112 semantic_binexpr_arithmetic, 1)
8113 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8114 semantic_binexpr_arithmetic, 1)
8115 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8116 semantic_logical_op, 1)
8117 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8118 semantic_logical_op, 1)
8119 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8120 semantic_shift_op, 1)
8121 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8122 semantic_shift_op, 1)
8123 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8124 semantic_arithmetic_addsubb_assign, 0)
8125 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8126 semantic_arithmetic_addsubb_assign, 0)
8127 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8128 semantic_arithmetic_assign, 0)
8129 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8130 semantic_divmod_assign, 0)
8131 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8132 semantic_divmod_assign, 0)
8133 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8134 semantic_arithmetic_assign, 0)
8135 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8136 semantic_arithmetic_assign, 0)
8137 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8138 semantic_arithmetic_assign, 0)
8139 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8140 semantic_arithmetic_assign, 0)
8141 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8142 semantic_arithmetic_assign, 0)
8144 static expression_t *parse_sub_expression(unsigned precedence)
8146 if (token.type < 0) {
8147 return expected_expression_error();
8150 expression_parser_function_t *parser
8151 = &expression_parsers[token.type];
8152 source_position_t source_position = token.source_position;
8155 if (parser->parser != NULL) {
8156 left = parser->parser(parser->precedence);
8158 left = parse_primary_expression();
8160 assert(left != NULL);
8161 left->base.source_position = source_position;
8164 if (token.type < 0) {
8165 return expected_expression_error();
8168 parser = &expression_parsers[token.type];
8169 if (parser->infix_parser == NULL)
8171 if (parser->infix_precedence < precedence)
8174 left = parser->infix_parser(parser->infix_precedence, left);
8176 assert(left != NULL);
8177 assert(left->kind != EXPR_UNKNOWN);
8178 left->base.source_position = source_position;
8185 * Parse an expression.
8187 static expression_t *parse_expression(void)
8189 return parse_sub_expression(1);
8193 * Register a parser for a prefix-like operator with given precedence.
8195 * @param parser the parser function
8196 * @param token_type the token type of the prefix token
8197 * @param precedence the precedence of the operator
8199 static void register_expression_parser(parse_expression_function parser,
8200 int token_type, unsigned precedence)
8202 expression_parser_function_t *entry = &expression_parsers[token_type];
8204 if (entry->parser != NULL) {
8205 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8206 panic("trying to register multiple expression parsers for a token");
8208 entry->parser = parser;
8209 entry->precedence = precedence;
8213 * Register a parser for an infix operator with given precedence.
8215 * @param parser the parser function
8216 * @param token_type the token type of the infix operator
8217 * @param precedence the precedence of the operator
8219 static void register_infix_parser(parse_expression_infix_function parser,
8220 int token_type, unsigned precedence)
8222 expression_parser_function_t *entry = &expression_parsers[token_type];
8224 if (entry->infix_parser != NULL) {
8225 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8226 panic("trying to register multiple infix expression parsers for a "
8229 entry->infix_parser = parser;
8230 entry->infix_precedence = precedence;
8234 * Initialize the expression parsers.
8236 static void init_expression_parsers(void)
8238 memset(&expression_parsers, 0, sizeof(expression_parsers));
8240 register_infix_parser(parse_array_expression, '[', 30);
8241 register_infix_parser(parse_call_expression, '(', 30);
8242 register_infix_parser(parse_select_expression, '.', 30);
8243 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8244 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8246 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8249 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8250 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8251 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8252 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8253 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8254 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8255 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8256 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8257 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8258 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8259 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8260 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8261 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8262 T_EXCLAMATIONMARKEQUAL, 13);
8263 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8264 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8265 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8266 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8267 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8268 register_infix_parser(parse_conditional_expression, '?', 7);
8269 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8270 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8271 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8272 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8273 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8274 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8275 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8276 T_LESSLESSEQUAL, 2);
8277 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8278 T_GREATERGREATEREQUAL, 2);
8279 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8281 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8283 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8286 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8288 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8289 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8290 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8291 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8292 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8293 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8294 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8296 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8298 register_expression_parser(parse_sizeof, T_sizeof, 25);
8299 register_expression_parser(parse_alignof, T___alignof__, 25);
8300 register_expression_parser(parse_extension, T___extension__, 25);
8301 register_expression_parser(parse_builtin_classify_type,
8302 T___builtin_classify_type, 25);
8306 * Parse a asm statement arguments specification.
8308 static asm_argument_t *parse_asm_arguments(bool is_out)
8310 asm_argument_t *result = NULL;
8311 asm_argument_t *last = NULL;
8313 while (token.type == T_STRING_LITERAL || token.type == '[') {
8314 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8315 memset(argument, 0, sizeof(argument[0]));
8317 if (token.type == '[') {
8319 if (token.type != T_IDENTIFIER) {
8320 parse_error_expected("while parsing asm argument",
8321 T_IDENTIFIER, NULL);
8324 argument->symbol = token.v.symbol;
8329 argument->constraints = parse_string_literals();
8331 add_anchor_token(')');
8332 expression_t *expression = parse_expression();
8333 rem_anchor_token(')');
8335 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8336 * change size or type representation (e.g. int -> long is ok, but
8337 * int -> float is not) */
8338 if (expression->kind == EXPR_UNARY_CAST) {
8339 type_t *const type = expression->base.type;
8340 type_kind_t const kind = type->kind;
8341 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8344 if (kind == TYPE_ATOMIC) {
8345 atomic_type_kind_t const akind = type->atomic.akind;
8346 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8347 size = get_atomic_type_size(akind);
8349 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8350 size = get_atomic_type_size(get_intptr_kind());
8354 expression_t *const value = expression->unary.value;
8355 type_t *const value_type = value->base.type;
8356 type_kind_t const value_kind = value_type->kind;
8358 unsigned value_flags;
8359 unsigned value_size;
8360 if (value_kind == TYPE_ATOMIC) {
8361 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8362 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8363 value_size = get_atomic_type_size(value_akind);
8364 } else if (value_kind == TYPE_POINTER) {
8365 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8366 value_size = get_atomic_type_size(get_intptr_kind());
8371 if (value_flags != flags || value_size != size)
8375 } while (expression->kind == EXPR_UNARY_CAST);
8379 if (!is_lvalue(expression)) {
8380 errorf(&expression->base.source_position,
8381 "asm output argument is not an lvalue");
8384 argument->expression = expression;
8387 set_address_taken(expression, true);
8390 last->next = argument;
8396 if (token.type != ',')
8407 * Parse a asm statement clobber specification.
8409 static asm_clobber_t *parse_asm_clobbers(void)
8411 asm_clobber_t *result = NULL;
8412 asm_clobber_t *last = NULL;
8414 while(token.type == T_STRING_LITERAL) {
8415 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8416 clobber->clobber = parse_string_literals();
8419 last->next = clobber;
8425 if (token.type != ',')
8434 * Parse an asm statement.
8436 static statement_t *parse_asm_statement(void)
8440 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8441 statement->base.source_position = token.source_position;
8443 asm_statement_t *asm_statement = &statement->asms;
8445 if (token.type == T_volatile) {
8447 asm_statement->is_volatile = true;
8451 add_anchor_token(')');
8452 add_anchor_token(':');
8453 asm_statement->asm_text = parse_string_literals();
8455 if (token.type != ':') {
8456 rem_anchor_token(':');
8461 asm_statement->outputs = parse_asm_arguments(true);
8462 if (token.type != ':') {
8463 rem_anchor_token(':');
8468 asm_statement->inputs = parse_asm_arguments(false);
8469 if (token.type != ':') {
8470 rem_anchor_token(':');
8473 rem_anchor_token(':');
8476 asm_statement->clobbers = parse_asm_clobbers();
8479 rem_anchor_token(')');
8483 if (asm_statement->outputs == NULL) {
8484 /* GCC: An 'asm' instruction without any output operands will be treated
8485 * identically to a volatile 'asm' instruction. */
8486 asm_statement->is_volatile = true;
8491 return create_invalid_statement();
8495 * Parse a case statement.
8497 static statement_t *parse_case_statement(void)
8501 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8502 source_position_t *const pos = &statement->base.source_position;
8504 *pos = token.source_position;
8505 statement->case_label.expression = parse_expression();
8506 if (! is_constant_expression(statement->case_label.expression)) {
8507 errorf(pos, "case label does not reduce to an integer constant");
8508 statement->case_label.is_bad = true;
8510 long const val = fold_constant(statement->case_label.expression);
8511 statement->case_label.first_case = val;
8512 statement->case_label.last_case = val;
8515 if (c_mode & _GNUC) {
8516 if (token.type == T_DOTDOTDOT) {
8518 statement->case_label.end_range = parse_expression();
8519 if (! is_constant_expression(statement->case_label.end_range)) {
8520 errorf(pos, "case range does not reduce to an integer constant");
8521 statement->case_label.is_bad = true;
8523 long const val = fold_constant(statement->case_label.end_range);
8524 statement->case_label.last_case = val;
8526 if (val < statement->case_label.first_case) {
8527 statement->case_label.is_empty = true;
8528 warningf(pos, "empty range specified");
8534 PUSH_PARENT(statement);
8538 if (current_switch != NULL) {
8539 if (! statement->case_label.is_bad) {
8540 /* Check for duplicate case values */
8541 case_label_statement_t *c = &statement->case_label;
8542 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8543 if (l->is_bad || l->is_empty || l->expression == NULL)
8546 if (c->last_case < l->first_case || c->first_case > l->last_case)
8549 errorf(pos, "duplicate case value (previously used %P)",
8550 &l->base.source_position);
8554 /* link all cases into the switch statement */
8555 if (current_switch->last_case == NULL) {
8556 current_switch->first_case = &statement->case_label;
8558 current_switch->last_case->next = &statement->case_label;
8560 current_switch->last_case = &statement->case_label;
8562 errorf(pos, "case label not within a switch statement");
8565 statement_t *const inner_stmt = parse_statement();
8566 statement->case_label.statement = inner_stmt;
8567 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8568 errorf(&inner_stmt->base.source_position, "declaration after case label");
8575 return create_invalid_statement();
8579 * Parse a default statement.
8581 static statement_t *parse_default_statement(void)
8585 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8586 statement->base.source_position = token.source_position;
8588 PUSH_PARENT(statement);
8591 if (current_switch != NULL) {
8592 const case_label_statement_t *def_label = current_switch->default_label;
8593 if (def_label != NULL) {
8594 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8595 &def_label->base.source_position);
8597 current_switch->default_label = &statement->case_label;
8599 /* link all cases into the switch statement */
8600 if (current_switch->last_case == NULL) {
8601 current_switch->first_case = &statement->case_label;
8603 current_switch->last_case->next = &statement->case_label;
8605 current_switch->last_case = &statement->case_label;
8608 errorf(&statement->base.source_position,
8609 "'default' label not within a switch statement");
8612 statement_t *const inner_stmt = parse_statement();
8613 statement->case_label.statement = inner_stmt;
8614 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8615 errorf(&inner_stmt->base.source_position, "declaration after default label");
8622 return create_invalid_statement();
8626 * Return the declaration for a given label symbol or create a new one.
8628 * @param symbol the symbol of the label
8630 static declaration_t *get_label(symbol_t *symbol)
8632 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
8633 assert(current_function != NULL);
8634 /* if we found a label in the same function, then we already created the
8636 if (candidate != NULL
8637 && candidate->parent_scope == ¤t_function->scope) {
8641 /* otherwise we need to create a new one */
8642 declaration_t *const declaration = allocate_declaration_zero();
8643 declaration->namespc = NAMESPACE_LABEL;
8644 declaration->symbol = symbol;
8646 label_push(declaration);
8652 * Parse a label statement.
8654 static statement_t *parse_label_statement(void)
8656 assert(token.type == T_IDENTIFIER);
8657 symbol_t *symbol = token.v.symbol;
8660 declaration_t *label = get_label(symbol);
8662 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8663 statement->base.source_position = token.source_position;
8664 statement->label.label = label;
8666 PUSH_PARENT(statement);
8668 /* if source position is already set then the label is defined twice,
8669 * otherwise it was just mentioned in a goto so far */
8670 if (label->source_position.input_name != NULL) {
8671 errorf(HERE, "duplicate label '%Y' (declared %P)",
8672 symbol, &label->source_position);
8674 label->source_position = token.source_position;
8675 label->init.statement = statement;
8680 if (token.type == '}') {
8681 /* TODO only warn? */
8683 warningf(HERE, "label at end of compound statement");
8684 statement->label.statement = create_empty_statement();
8686 errorf(HERE, "label at end of compound statement");
8687 statement->label.statement = create_invalid_statement();
8689 } else if (token.type == ';') {
8690 /* Eat an empty statement here, to avoid the warning about an empty
8691 * statement after a label. label:; is commonly used to have a label
8692 * before a closing brace. */
8693 statement->label.statement = create_empty_statement();
8696 statement_t *const inner_stmt = parse_statement();
8697 statement->label.statement = inner_stmt;
8698 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8699 errorf(&inner_stmt->base.source_position, "declaration after label");
8703 /* remember the labels in a list for later checking */
8704 if (label_last == NULL) {
8705 label_first = &statement->label;
8707 label_last->next = &statement->label;
8709 label_last = &statement->label;
8716 * Parse an if statement.
8718 static statement_t *parse_if(void)
8722 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8723 statement->base.source_position = token.source_position;
8725 PUSH_PARENT(statement);
8728 add_anchor_token(')');
8729 statement->ifs.condition = parse_expression();
8730 rem_anchor_token(')');
8733 add_anchor_token(T_else);
8734 statement->ifs.true_statement = parse_statement();
8735 rem_anchor_token(T_else);
8737 if (token.type == T_else) {
8739 statement->ifs.false_statement = parse_statement();
8746 return create_invalid_statement();
8750 * Check that all enums are handled in a switch.
8752 * @param statement the switch statement to check
8754 static void check_enum_cases(const switch_statement_t *statement) {
8755 const type_t *type = skip_typeref(statement->expression->base.type);
8756 if (! is_type_enum(type))
8758 const enum_type_t *enumt = &type->enumt;
8760 /* if we have a default, no warnings */
8761 if (statement->default_label != NULL)
8764 /* FIXME: calculation of value should be done while parsing */
8765 const declaration_t *declaration;
8766 long last_value = -1;
8767 for (declaration = enumt->declaration->next;
8768 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8769 declaration = declaration->next) {
8770 const expression_t *expression = declaration->init.enum_value;
8771 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8773 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8774 if (l->expression == NULL)
8776 if (l->first_case <= value && value <= l->last_case) {
8782 warningf(&statement->base.source_position,
8783 "enumeration value '%Y' not handled in switch", declaration->symbol);
8790 * Parse a switch statement.
8792 static statement_t *parse_switch(void)
8796 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8797 statement->base.source_position = token.source_position;
8799 PUSH_PARENT(statement);
8802 add_anchor_token(')');
8803 expression_t *const expr = parse_expression();
8804 type_t * type = skip_typeref(expr->base.type);
8805 if (is_type_integer(type)) {
8806 type = promote_integer(type);
8807 if (warning.traditional) {
8808 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8809 warningf(&expr->base.source_position,
8810 "'%T' switch expression not converted to '%T' in ISO C",
8814 } else if (is_type_valid(type)) {
8815 errorf(&expr->base.source_position,
8816 "switch quantity is not an integer, but '%T'", type);
8817 type = type_error_type;
8819 statement->switchs.expression = create_implicit_cast(expr, type);
8821 rem_anchor_token(')');
8823 switch_statement_t *rem = current_switch;
8824 current_switch = &statement->switchs;
8825 statement->switchs.body = parse_statement();
8826 current_switch = rem;
8828 if (warning.switch_default &&
8829 statement->switchs.default_label == NULL) {
8830 warningf(&statement->base.source_position, "switch has no default case");
8832 if (warning.switch_enum)
8833 check_enum_cases(&statement->switchs);
8839 return create_invalid_statement();
8842 static statement_t *parse_loop_body(statement_t *const loop)
8844 statement_t *const rem = current_loop;
8845 current_loop = loop;
8847 statement_t *const body = parse_statement();
8854 * Parse a while statement.
8856 static statement_t *parse_while(void)
8860 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8861 statement->base.source_position = token.source_position;
8863 PUSH_PARENT(statement);
8866 add_anchor_token(')');
8867 statement->whiles.condition = parse_expression();
8868 rem_anchor_token(')');
8871 statement->whiles.body = parse_loop_body(statement);
8877 return create_invalid_statement();
8881 * Parse a do statement.
8883 static statement_t *parse_do(void)
8887 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8888 statement->base.source_position = token.source_position;
8890 PUSH_PARENT(statement)
8892 add_anchor_token(T_while);
8893 statement->do_while.body = parse_loop_body(statement);
8894 rem_anchor_token(T_while);
8898 add_anchor_token(')');
8899 statement->do_while.condition = parse_expression();
8900 rem_anchor_token(')');
8908 return create_invalid_statement();
8912 * Parse a for statement.
8914 static statement_t *parse_for(void)
8918 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8919 statement->base.source_position = token.source_position;
8921 PUSH_PARENT(statement);
8923 int top = environment_top();
8924 scope_t *last_scope = scope;
8925 set_scope(&statement->fors.scope);
8928 add_anchor_token(')');
8930 if (token.type != ';') {
8931 if (is_declaration_specifier(&token, false)) {
8932 parse_declaration(record_declaration);
8934 add_anchor_token(';');
8935 expression_t *const init = parse_expression();
8936 statement->fors.initialisation = init;
8937 if (warning.unused_value && !expression_has_effect(init)) {
8938 warningf(&init->base.source_position,
8939 "initialisation of 'for'-statement has no effect");
8941 rem_anchor_token(';');
8948 if (token.type != ';') {
8949 add_anchor_token(';');
8950 statement->fors.condition = parse_expression();
8951 rem_anchor_token(';');
8954 if (token.type != ')') {
8955 expression_t *const step = parse_expression();
8956 statement->fors.step = step;
8957 if (warning.unused_value && !expression_has_effect(step)) {
8958 warningf(&step->base.source_position,
8959 "step of 'for'-statement has no effect");
8962 rem_anchor_token(')');
8964 statement->fors.body = parse_loop_body(statement);
8966 assert(scope == &statement->fors.scope);
8967 set_scope(last_scope);
8968 environment_pop_to(top);
8975 rem_anchor_token(')');
8976 assert(scope == &statement->fors.scope);
8977 set_scope(last_scope);
8978 environment_pop_to(top);
8980 return create_invalid_statement();
8984 * Parse a goto statement.
8986 static statement_t *parse_goto(void)
8990 if (token.type != T_IDENTIFIER) {
8991 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
8995 symbol_t *symbol = token.v.symbol;
8998 declaration_t *label = get_label(symbol);
9000 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9001 statement->base.source_position = token.source_position;
9003 statement->gotos.label = label;
9005 /* remember the goto's in a list for later checking */
9006 if (goto_last == NULL) {
9007 goto_first = &statement->gotos;
9009 goto_last->next = &statement->gotos;
9011 goto_last = &statement->gotos;
9017 return create_invalid_statement();
9021 * Parse a continue statement.
9023 static statement_t *parse_continue(void)
9025 if (current_loop == NULL) {
9026 errorf(HERE, "continue statement not within loop");
9029 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9030 statement->base.source_position = token.source_position;
9040 * Parse a break statement.
9042 static statement_t *parse_break(void)
9044 if (current_switch == NULL && current_loop == NULL) {
9045 errorf(HERE, "break statement not within loop or switch");
9048 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9049 statement->base.source_position = token.source_position;
9059 * Parse a __leave statement.
9061 static statement_t *parse_leave(void)
9063 if (current_try == NULL) {
9064 errorf(HERE, "__leave statement not within __try");
9067 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9068 statement->base.source_position = token.source_position;
9078 * Check if a given declaration represents a local variable.
9080 static bool is_local_var_declaration(const declaration_t *declaration)
9082 switch ((storage_class_tag_t) declaration->storage_class) {
9083 case STORAGE_CLASS_AUTO:
9084 case STORAGE_CLASS_REGISTER: {
9085 const type_t *type = skip_typeref(declaration->type);
9086 if (is_type_function(type)) {
9098 * Check if a given declaration represents a variable.
9100 static bool is_var_declaration(const declaration_t *declaration)
9102 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9105 const type_t *type = skip_typeref(declaration->type);
9106 return !is_type_function(type);
9110 * Check if a given expression represents a local variable.
9112 static bool is_local_variable(const expression_t *expression)
9114 if (expression->base.kind != EXPR_REFERENCE) {
9117 const declaration_t *declaration = expression->reference.declaration;
9118 return is_local_var_declaration(declaration);
9122 * Check if a given expression represents a local variable and
9123 * return its declaration then, else return NULL.
9125 declaration_t *expr_is_variable(const expression_t *expression)
9127 if (expression->base.kind != EXPR_REFERENCE) {
9130 declaration_t *declaration = expression->reference.declaration;
9131 if (is_var_declaration(declaration))
9137 * Parse a return statement.
9139 static statement_t *parse_return(void)
9141 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9142 statement->base.source_position = token.source_position;
9146 expression_t *return_value = NULL;
9147 if (token.type != ';') {
9148 return_value = parse_expression();
9151 const type_t *const func_type = current_function->type;
9152 assert(is_type_function(func_type));
9153 type_t *const return_type = skip_typeref(func_type->function.return_type);
9155 if (return_value != NULL) {
9156 type_t *return_value_type = skip_typeref(return_value->base.type);
9158 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9159 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9160 warningf(&statement->base.source_position,
9161 "'return' with a value, in function returning void");
9162 return_value = NULL;
9164 assign_error_t error = semantic_assign(return_type, return_value);
9165 report_assign_error(error, return_type, return_value, "'return'",
9166 &statement->base.source_position);
9167 return_value = create_implicit_cast(return_value, return_type);
9169 /* check for returning address of a local var */
9170 if (return_value != NULL &&
9171 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9172 const expression_t *expression = return_value->unary.value;
9173 if (is_local_variable(expression)) {
9174 warningf(&statement->base.source_position,
9175 "function returns address of local variable");
9179 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9180 warningf(&statement->base.source_position,
9181 "'return' without value, in function returning non-void");
9184 statement->returns.value = return_value;
9193 * Parse a declaration statement.
9195 static statement_t *parse_declaration_statement(void)
9197 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9199 statement->base.source_position = token.source_position;
9201 declaration_t *before = last_declaration;
9202 parse_declaration(record_declaration);
9204 if (before == NULL) {
9205 statement->declaration.declarations_begin = scope->declarations;
9207 statement->declaration.declarations_begin = before->next;
9209 statement->declaration.declarations_end = last_declaration;
9215 * Parse an expression statement, ie. expr ';'.
9217 static statement_t *parse_expression_statement(void)
9219 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9221 statement->base.source_position = token.source_position;
9222 expression_t *const expr = parse_expression();
9223 statement->expression.expression = expr;
9232 * Parse a microsoft __try { } __finally { } or
9233 * __try{ } __except() { }
9235 static statement_t *parse_ms_try_statment(void)
9237 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9238 statement->base.source_position = token.source_position;
9241 PUSH_PARENT(statement);
9243 ms_try_statement_t *rem = current_try;
9244 current_try = &statement->ms_try;
9245 statement->ms_try.try_statement = parse_compound_statement(false);
9250 if (token.type == T___except) {
9253 add_anchor_token(')');
9254 expression_t *const expr = parse_expression();
9255 type_t * type = skip_typeref(expr->base.type);
9256 if (is_type_integer(type)) {
9257 type = promote_integer(type);
9258 } else if (is_type_valid(type)) {
9259 errorf(&expr->base.source_position,
9260 "__expect expression is not an integer, but '%T'", type);
9261 type = type_error_type;
9263 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9264 rem_anchor_token(')');
9266 statement->ms_try.final_statement = parse_compound_statement(false);
9267 } else if (token.type == T__finally) {
9269 statement->ms_try.final_statement = parse_compound_statement(false);
9271 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9272 return create_invalid_statement();
9276 return create_invalid_statement();
9279 static statement_t *parse_empty_statement(void)
9281 if (warning.empty_statement) {
9282 warningf(HERE, "statement is empty");
9284 statement_t *const statement = create_empty_statement();
9290 * Parse a statement.
9291 * There's also parse_statement() which additionally checks for
9292 * "statement has no effect" warnings
9294 static statement_t *intern_parse_statement(void)
9296 statement_t *statement = NULL;
9298 /* declaration or statement */
9299 add_anchor_token(';');
9300 switch (token.type) {
9301 case T_IDENTIFIER: {
9302 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9303 if (la1_type == ':') {
9304 statement = parse_label_statement();
9305 } else if (is_typedef_symbol(token.v.symbol)) {
9306 statement = parse_declaration_statement();
9307 } else switch (la1_type) {
9311 statement = parse_declaration_statement();
9315 statement = parse_expression_statement();
9321 case T___extension__:
9322 /* This can be a prefix to a declaration or an expression statement.
9323 * We simply eat it now and parse the rest with tail recursion. */
9326 } while (token.type == T___extension__);
9327 statement = parse_statement();
9331 statement = parse_declaration_statement();
9334 case ';': statement = parse_empty_statement(); break;
9335 case '{': statement = parse_compound_statement(false); break;
9336 case T___leave: statement = parse_leave(); break;
9337 case T___try: statement = parse_ms_try_statment(); break;
9338 case T_asm: statement = parse_asm_statement(); break;
9339 case T_break: statement = parse_break(); break;
9340 case T_case: statement = parse_case_statement(); break;
9341 case T_continue: statement = parse_continue(); break;
9342 case T_default: statement = parse_default_statement(); break;
9343 case T_do: statement = parse_do(); break;
9344 case T_for: statement = parse_for(); break;
9345 case T_goto: statement = parse_goto(); break;
9346 case T_if: statement = parse_if (); break;
9347 case T_return: statement = parse_return(); break;
9348 case T_switch: statement = parse_switch(); break;
9349 case T_while: statement = parse_while(); break;
9350 default: statement = parse_expression_statement(); break;
9352 rem_anchor_token(';');
9354 assert(statement != NULL
9355 && statement->base.source_position.input_name != NULL);
9361 * parse a statement and emits "statement has no effect" warning if needed
9362 * (This is really a wrapper around intern_parse_statement with check for 1
9363 * single warning. It is needed, because for statement expressions we have
9364 * to avoid the warning on the last statement)
9366 static statement_t *parse_statement(void)
9368 statement_t *statement = intern_parse_statement();
9370 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9371 expression_t *expression = statement->expression.expression;
9372 if (!expression_has_effect(expression)) {
9373 warningf(&expression->base.source_position,
9374 "statement has no effect");
9382 * Parse a compound statement.
9384 static statement_t *parse_compound_statement(bool inside_expression_statement)
9386 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9387 statement->base.source_position = token.source_position;
9389 PUSH_PARENT(statement);
9392 add_anchor_token('}');
9394 int top = environment_top();
9395 scope_t *last_scope = scope;
9396 set_scope(&statement->compound.scope);
9398 statement_t **anchor = &statement->compound.statements;
9399 bool only_decls_so_far = true;
9400 while (token.type != '}' && token.type != T_EOF) {
9401 statement_t *sub_statement = intern_parse_statement();
9402 if (is_invalid_statement(sub_statement)) {
9403 /* an error occurred. if we are at an anchor, return */
9409 if (warning.declaration_after_statement) {
9410 if (sub_statement->kind != STATEMENT_DECLARATION) {
9411 only_decls_so_far = false;
9412 } else if (!only_decls_so_far) {
9413 warningf(&sub_statement->base.source_position,
9414 "ISO C90 forbids mixed declarations and code");
9418 *anchor = sub_statement;
9420 while (sub_statement->base.next != NULL)
9421 sub_statement = sub_statement->base.next;
9423 anchor = &sub_statement->base.next;
9426 if (token.type == '}') {
9429 errorf(&statement->base.source_position,
9430 "end of file while looking for closing '}'");
9433 /* look over all statements again to produce no effect warnings */
9434 if (warning.unused_value) {
9435 statement_t *sub_statement = statement->compound.statements;
9436 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9437 if (sub_statement->kind != STATEMENT_EXPRESSION)
9439 /* don't emit a warning for the last expression in an expression
9440 * statement as it has always an effect */
9441 if (inside_expression_statement && sub_statement->base.next == NULL)
9444 expression_t *expression = sub_statement->expression.expression;
9445 if (!expression_has_effect(expression)) {
9446 warningf(&expression->base.source_position,
9447 "statement has no effect");
9453 rem_anchor_token('}');
9454 assert(scope == &statement->compound.scope);
9455 set_scope(last_scope);
9456 environment_pop_to(top);
9463 * Initialize builtin types.
9465 static void initialize_builtin_types(void)
9467 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9468 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9469 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9470 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9471 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9472 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9473 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9474 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9476 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9477 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9478 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9479 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9481 /* const version of wchar_t */
9482 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9483 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9484 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9486 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9490 * Check for unused global static functions and variables
9492 static void check_unused_globals(void)
9494 if (!warning.unused_function && !warning.unused_variable)
9497 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9499 decl->modifiers & DM_UNUSED ||
9500 decl->modifiers & DM_USED ||
9501 decl->storage_class != STORAGE_CLASS_STATIC)
9504 type_t *const type = decl->type;
9506 if (is_type_function(skip_typeref(type))) {
9507 if (!warning.unused_function || decl->is_inline)
9510 s = (decl->init.statement != NULL ? "defined" : "declared");
9512 if (!warning.unused_variable)
9518 warningf(&decl->source_position, "'%#T' %s but not used",
9519 type, decl->symbol, s);
9523 static void parse_global_asm(void)
9528 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9529 statement->base.source_position = token.source_position;
9530 statement->asms.asm_text = parse_string_literals();
9531 statement->base.next = unit->global_asm;
9532 unit->global_asm = statement;
9541 * Parse a translation unit.
9543 static void parse_translation_unit(void)
9545 for (;;) switch (token.type) {
9548 case T___extension__:
9549 parse_external_declaration();
9560 /* TODO error in strict mode */
9561 warningf(HERE, "stray ';' outside of function");
9566 errorf(HERE, "stray %K outside of function", &token);
9567 if (token.type == '(' || token.type == '{' || token.type == '[')
9568 eat_until_matching_token(token.type);
9577 * @return the translation unit or NULL if errors occurred.
9579 void start_parsing(void)
9581 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9582 label_stack = NEW_ARR_F(stack_entry_t, 0);
9583 diagnostic_count = 0;
9587 type_set_output(stderr);
9588 ast_set_output(stderr);
9590 assert(unit == NULL);
9591 unit = allocate_ast_zero(sizeof(unit[0]));
9593 assert(global_scope == NULL);
9594 global_scope = &unit->scope;
9596 assert(scope == NULL);
9597 set_scope(&unit->scope);
9599 initialize_builtin_types();
9602 translation_unit_t *finish_parsing(void)
9604 assert(scope == &unit->scope);
9606 last_declaration = NULL;
9608 assert(global_scope == &unit->scope);
9609 check_unused_globals();
9610 global_scope = NULL;
9612 DEL_ARR_F(environment_stack);
9613 DEL_ARR_F(label_stack);
9615 translation_unit_t *result = unit;
9622 lookahead_bufpos = 0;
9623 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9626 parse_translation_unit();
9630 * Initialize the parser.
9632 void init_parser(void)
9635 /* add predefined symbols for extended-decl-modifier */
9636 sym_align = symbol_table_insert("align");
9637 sym_allocate = symbol_table_insert("allocate");
9638 sym_dllimport = symbol_table_insert("dllimport");
9639 sym_dllexport = symbol_table_insert("dllexport");
9640 sym_naked = symbol_table_insert("naked");
9641 sym_noinline = symbol_table_insert("noinline");
9642 sym_noreturn = symbol_table_insert("noreturn");
9643 sym_nothrow = symbol_table_insert("nothrow");
9644 sym_novtable = symbol_table_insert("novtable");
9645 sym_property = symbol_table_insert("property");
9646 sym_get = symbol_table_insert("get");
9647 sym_put = symbol_table_insert("put");
9648 sym_selectany = symbol_table_insert("selectany");
9649 sym_thread = symbol_table_insert("thread");
9650 sym_uuid = symbol_table_insert("uuid");
9651 sym_deprecated = symbol_table_insert("deprecated");
9652 sym_restrict = symbol_table_insert("restrict");
9653 sym_noalias = symbol_table_insert("noalias");
9655 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9657 init_expression_parsers();
9658 obstack_init(&temp_obst);
9660 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9661 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9665 * Terminate the parser.
9667 void exit_parser(void)
9669 obstack_free(&temp_obst, NULL);