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),
318 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
320 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
321 return sizes[EXPR_UNARY_FIRST];
323 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
324 return sizes[EXPR_BINARY_FIRST];
326 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
327 assert(sizes[kind] != 0);
332 * Allocate a statement node of given kind and initialize all
335 static statement_t *allocate_statement_zero(statement_kind_t kind)
337 size_t size = get_statement_struct_size(kind);
338 statement_t *res = allocate_ast_zero(size);
340 res->base.kind = kind;
341 res->base.parent = current_parent;
346 * Allocate an expression node of given kind and initialize all
349 static expression_t *allocate_expression_zero(expression_kind_t kind)
351 size_t size = get_expression_struct_size(kind);
352 expression_t *res = allocate_ast_zero(size);
354 res->base.kind = kind;
355 res->base.type = type_error_type;
360 * Creates a new invalid expression.
362 static expression_t *create_invalid_expression(void)
364 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
365 expression->base.source_position = token.source_position;
370 * Creates a new invalid statement.
372 static statement_t *create_invalid_statement(void)
374 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
375 statement->base.source_position = token.source_position;
380 * Allocate a new empty statement.
382 static statement_t *create_empty_statement(void)
384 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
385 statement->base.source_position = token.source_position;
390 * Returns the size of a type node.
392 * @param kind the type kind
394 static size_t get_type_struct_size(type_kind_t kind)
396 static const size_t sizes[] = {
397 [TYPE_ATOMIC] = sizeof(atomic_type_t),
398 [TYPE_COMPLEX] = sizeof(complex_type_t),
399 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
400 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
401 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
402 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
403 [TYPE_ENUM] = sizeof(enum_type_t),
404 [TYPE_FUNCTION] = sizeof(function_type_t),
405 [TYPE_POINTER] = sizeof(pointer_type_t),
406 [TYPE_ARRAY] = sizeof(array_type_t),
407 [TYPE_BUILTIN] = sizeof(builtin_type_t),
408 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
409 [TYPE_TYPEOF] = sizeof(typeof_type_t),
411 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
412 assert(kind <= TYPE_TYPEOF);
413 assert(sizes[kind] != 0);
418 * Allocate a type node of given kind and initialize all
421 * @param kind type kind to allocate
422 * @param source_position the source position of the type definition
424 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
426 size_t size = get_type_struct_size(kind);
427 type_t *res = obstack_alloc(type_obst, size);
428 memset(res, 0, size);
430 res->base.kind = kind;
431 res->base.source_position = *source_position;
436 * Returns the size of an initializer node.
438 * @param kind the initializer kind
440 static size_t get_initializer_size(initializer_kind_t kind)
442 static const size_t sizes[] = {
443 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
444 [INITIALIZER_STRING] = sizeof(initializer_string_t),
445 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
446 [INITIALIZER_LIST] = sizeof(initializer_list_t),
447 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
449 assert(kind < sizeof(sizes) / sizeof(*sizes));
450 assert(sizes[kind] != 0);
455 * Allocate an initializer node of given kind and initialize all
458 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
460 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
467 * Free a type from the type obstack.
469 static void free_type(void *type)
471 obstack_free(type_obst, type);
475 * Returns the index of the top element of the environment stack.
477 static size_t environment_top(void)
479 return ARR_LEN(environment_stack);
483 * Returns the index of the top element of the label stack.
485 static size_t label_top(void)
487 return ARR_LEN(label_stack);
491 * Return the next token.
493 static inline void next_token(void)
495 token = lookahead_buffer[lookahead_bufpos];
496 lookahead_buffer[lookahead_bufpos] = lexer_token;
499 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
502 print_token(stderr, &token);
503 fprintf(stderr, "\n");
508 * Return the next token with a given lookahead.
510 static inline const token_t *look_ahead(int num)
512 assert(num > 0 && num <= MAX_LOOKAHEAD);
513 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
514 return &lookahead_buffer[pos];
518 * Adds a token to the token anchor set (a multi-set).
520 static void add_anchor_token(int token_type)
522 assert(0 <= token_type && token_type < T_LAST_TOKEN);
523 ++token_anchor_set[token_type];
526 static int save_and_reset_anchor_state(int token_type)
528 assert(0 <= token_type && token_type < T_LAST_TOKEN);
529 int count = token_anchor_set[token_type];
530 token_anchor_set[token_type] = 0;
534 static void restore_anchor_state(int token_type, int count)
536 assert(0 <= token_type && token_type < T_LAST_TOKEN);
537 token_anchor_set[token_type] = count;
541 * Remove a token from the token anchor set (a multi-set).
543 static void rem_anchor_token(int token_type)
545 assert(0 <= token_type && token_type < T_LAST_TOKEN);
546 --token_anchor_set[token_type];
549 static bool at_anchor(void)
553 return token_anchor_set[token.type];
557 * Eat tokens until a matching token is found.
559 static void eat_until_matching_token(int type)
563 case '(': end_token = ')'; break;
564 case '{': end_token = '}'; break;
565 case '[': end_token = ']'; break;
566 default: end_token = type; break;
569 unsigned parenthesis_count = 0;
570 unsigned brace_count = 0;
571 unsigned bracket_count = 0;
572 while (token.type != end_token ||
573 parenthesis_count != 0 ||
575 bracket_count != 0) {
576 switch (token.type) {
578 case '(': ++parenthesis_count; break;
579 case '{': ++brace_count; break;
580 case '[': ++bracket_count; break;
583 if (parenthesis_count > 0)
593 if (bracket_count > 0)
596 if (token.type == end_token &&
597 parenthesis_count == 0 &&
611 * Eat input tokens until an anchor is found.
613 static void eat_until_anchor(void)
615 if (token.type == T_EOF)
617 while (token_anchor_set[token.type] == 0) {
618 if (token.type == '(' || token.type == '{' || token.type == '[')
619 eat_until_matching_token(token.type);
620 if (token.type == T_EOF)
626 static void eat_block(void)
628 eat_until_matching_token('{');
629 if (token.type == '}')
634 * eat all token until a ';' is reached or a stop token is found.
636 static void eat_statement(void)
638 eat_until_matching_token(';');
639 if (token.type == ';')
643 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while (0)
646 * Report a parse error because an expected token was not found.
649 #if defined __GNUC__ && __GNUC__ >= 4
650 __attribute__((sentinel))
652 void parse_error_expected(const char *message, ...)
654 if (message != NULL) {
655 errorf(HERE, "%s", message);
658 va_start(ap, message);
659 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
664 * Report a type error.
666 static void type_error(const char *msg, const source_position_t *source_position,
669 errorf(source_position, "%s, but found type '%T'", msg, type);
673 * Report an incompatible type.
675 static void type_error_incompatible(const char *msg,
676 const source_position_t *source_position, type_t *type1, type_t *type2)
678 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
683 * Expect the the current token is the expected token.
684 * If not, generate an error, eat the current statement,
685 * and goto the end_error label.
687 #define expect(expected) \
689 if (UNLIKELY(token.type != (expected))) { \
690 parse_error_expected(NULL, (expected), NULL); \
691 add_anchor_token(expected); \
692 eat_until_anchor(); \
693 if (token.type == expected) \
695 rem_anchor_token(expected); \
701 static void set_scope(scope_t *new_scope)
704 scope->last_declaration = last_declaration;
708 last_declaration = new_scope->last_declaration;
712 * Search a symbol in a given namespace and returns its declaration or
713 * NULL if this symbol was not found.
715 static declaration_t *get_declaration(const symbol_t *const symbol,
716 const namespace_t namespc)
718 declaration_t *declaration = symbol->declaration;
719 for( ; declaration != NULL; declaration = declaration->symbol_next) {
720 if (declaration->namespc == namespc)
728 * pushs an environment_entry on the environment stack and links the
729 * corresponding symbol to the new entry
731 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
733 symbol_t *symbol = declaration->symbol;
734 namespace_t namespc = (namespace_t) declaration->namespc;
736 /* replace/add declaration into declaration list of the symbol */
737 declaration_t *iter = symbol->declaration;
739 symbol->declaration = declaration;
741 declaration_t *iter_last = NULL;
742 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
743 /* replace an entry? */
744 if (iter->namespc == namespc) {
745 if (iter_last == NULL) {
746 symbol->declaration = declaration;
748 iter_last->symbol_next = declaration;
750 declaration->symbol_next = iter->symbol_next;
755 assert(iter_last->symbol_next == NULL);
756 iter_last->symbol_next = declaration;
760 /* remember old declaration */
762 entry.symbol = symbol;
763 entry.old_declaration = iter;
764 entry.namespc = (unsigned short) namespc;
765 ARR_APP1(stack_entry_t, *stack_ptr, entry);
768 static void environment_push(declaration_t *declaration)
770 assert(declaration->source_position.input_name != NULL);
771 assert(declaration->parent_scope != NULL);
772 stack_push(&environment_stack, declaration);
776 * Push a declaration of the label stack.
778 * @param declaration the declaration
780 static void label_push(declaration_t *declaration)
782 declaration->parent_scope = ¤t_function->scope;
783 stack_push(&label_stack, declaration);
787 * pops symbols from the environment stack until @p new_top is the top element
789 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
791 stack_entry_t *stack = *stack_ptr;
792 size_t top = ARR_LEN(stack);
795 assert(new_top <= top);
799 for(i = top; i > new_top; --i) {
800 stack_entry_t *entry = &stack[i - 1];
802 declaration_t *old_declaration = entry->old_declaration;
803 symbol_t *symbol = entry->symbol;
804 namespace_t namespc = (namespace_t)entry->namespc;
806 /* replace/remove declaration */
807 declaration_t *declaration = symbol->declaration;
808 assert(declaration != NULL);
809 if (declaration->namespc == namespc) {
810 if (old_declaration == NULL) {
811 symbol->declaration = declaration->symbol_next;
813 symbol->declaration = old_declaration;
816 declaration_t *iter_last = declaration;
817 declaration_t *iter = declaration->symbol_next;
818 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
819 /* replace an entry? */
820 if (iter->namespc == namespc) {
821 assert(iter_last != NULL);
822 iter_last->symbol_next = old_declaration;
823 if (old_declaration != NULL) {
824 old_declaration->symbol_next = iter->symbol_next;
829 assert(iter != NULL);
833 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
836 static void environment_pop_to(size_t new_top)
838 stack_pop_to(&environment_stack, new_top);
842 * Pop all entries on the label stack until the new_top
845 * @param new_top the new stack top
847 static void label_pop_to(size_t new_top)
849 stack_pop_to(&label_stack, new_top);
852 static int get_akind_rank(atomic_type_kind_t akind)
857 static int get_rank(const type_t *type)
859 assert(!is_typeref(type));
860 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
861 * and esp. footnote 108). However we can't fold constants (yet), so we
862 * can't decide whether unsigned int is possible, while int always works.
863 * (unsigned int would be preferable when possible... for stuff like
864 * struct { enum { ... } bla : 4; } ) */
865 if (type->kind == TYPE_ENUM)
866 return get_akind_rank(ATOMIC_TYPE_INT);
868 assert(type->kind == TYPE_ATOMIC);
869 return get_akind_rank(type->atomic.akind);
872 static type_t *promote_integer(type_t *type)
874 if (type->kind == TYPE_BITFIELD)
875 type = type->bitfield.base_type;
877 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
884 * Create a cast expression.
886 * @param expression the expression to cast
887 * @param dest_type the destination type
889 static expression_t *create_cast_expression(expression_t *expression,
892 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
894 cast->unary.value = expression;
895 cast->base.type = dest_type;
901 * Check if a given expression represents the 0 pointer constant.
903 static bool is_null_pointer_constant(const expression_t *expression)
905 /* skip void* cast */
906 if (expression->kind == EXPR_UNARY_CAST
907 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
908 expression = expression->unary.value;
911 /* TODO: not correct yet, should be any constant integer expression
912 * which evaluates to 0 */
913 if (expression->kind != EXPR_CONST)
916 type_t *const type = skip_typeref(expression->base.type);
917 if (!is_type_integer(type))
920 return expression->conste.v.int_value == 0;
924 * Create an implicit cast expression.
926 * @param expression the expression to cast
927 * @param dest_type the destination type
929 static expression_t *create_implicit_cast(expression_t *expression,
932 type_t *const source_type = expression->base.type;
934 if (source_type == dest_type)
937 return create_cast_expression(expression, dest_type);
940 typedef enum assign_error_t {
942 ASSIGN_ERROR_INCOMPATIBLE,
943 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
944 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
945 ASSIGN_WARNING_POINTER_FROM_INT,
946 ASSIGN_WARNING_INT_FROM_POINTER
949 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
950 const expression_t *const right,
952 const source_position_t *source_position)
954 type_t *const orig_type_right = right->base.type;
955 type_t *const type_left = skip_typeref(orig_type_left);
956 type_t *const type_right = skip_typeref(orig_type_right);
961 case ASSIGN_ERROR_INCOMPATIBLE:
962 errorf(source_position,
963 "destination type '%T' in %s is incompatible with type '%T'",
964 orig_type_left, context, orig_type_right);
967 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
968 type_t *points_to_left
969 = skip_typeref(type_left->pointer.points_to);
970 type_t *points_to_right
971 = skip_typeref(type_right->pointer.points_to);
973 /* the left type has all qualifiers from the right type */
974 unsigned missing_qualifiers
975 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
976 warningf(source_position,
977 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
978 orig_type_left, context, orig_type_right, missing_qualifiers);
982 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
983 warningf(source_position,
984 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
985 orig_type_left, context, right, orig_type_right);
988 case ASSIGN_WARNING_POINTER_FROM_INT:
989 warningf(source_position,
990 "%s makes integer '%T' from pointer '%T' without a cast",
991 context, orig_type_left, orig_type_right);
994 case ASSIGN_WARNING_INT_FROM_POINTER:
995 warningf(source_position,
996 "%s makes integer '%T' from pointer '%T' without a cast",
997 context, orig_type_left, orig_type_right);
1001 panic("invalid error value");
1005 /** Implements the rules from § 6.5.16.1 */
1006 static assign_error_t semantic_assign(type_t *orig_type_left,
1007 const expression_t *const right)
1009 type_t *const orig_type_right = right->base.type;
1010 type_t *const type_left = skip_typeref(orig_type_left);
1011 type_t *const type_right = skip_typeref(orig_type_right);
1013 if (is_type_pointer(type_left)) {
1014 if (is_null_pointer_constant(right)) {
1015 return ASSIGN_SUCCESS;
1016 } else if (is_type_pointer(type_right)) {
1017 type_t *points_to_left
1018 = skip_typeref(type_left->pointer.points_to);
1019 type_t *points_to_right
1020 = skip_typeref(type_right->pointer.points_to);
1021 assign_error_t res = ASSIGN_SUCCESS;
1023 /* the left type has all qualifiers from the right type */
1024 unsigned missing_qualifiers
1025 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1026 if (missing_qualifiers != 0) {
1027 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1030 points_to_left = get_unqualified_type(points_to_left);
1031 points_to_right = get_unqualified_type(points_to_right);
1033 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
1034 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1038 if (!types_compatible(points_to_left, points_to_right)) {
1039 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1043 } else if (is_type_integer(type_right)) {
1044 return ASSIGN_WARNING_POINTER_FROM_INT;
1046 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1047 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1048 && is_type_pointer(type_right))) {
1049 return ASSIGN_SUCCESS;
1050 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1051 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1052 type_t *const unqual_type_left = get_unqualified_type(type_left);
1053 type_t *const unqual_type_right = get_unqualified_type(type_right);
1054 if (types_compatible(unqual_type_left, unqual_type_right)) {
1055 return ASSIGN_SUCCESS;
1057 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1058 return ASSIGN_WARNING_INT_FROM_POINTER;
1061 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1062 return ASSIGN_SUCCESS;
1064 return ASSIGN_ERROR_INCOMPATIBLE;
1067 static expression_t *parse_constant_expression(void)
1069 /* start parsing at precedence 7 (conditional expression) */
1070 expression_t *result = parse_sub_expression(7);
1072 if (!is_constant_expression(result)) {
1073 errorf(&result->base.source_position,
1074 "expression '%E' is not constant\n", result);
1080 static expression_t *parse_assignment_expression(void)
1082 /* start parsing at precedence 2 (assignment expression) */
1083 return parse_sub_expression(2);
1086 static type_t *make_global_typedef(const char *name, type_t *type)
1088 symbol_t *const symbol = symbol_table_insert(name);
1090 declaration_t *const declaration = allocate_declaration_zero();
1091 declaration->namespc = NAMESPACE_NORMAL;
1092 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1093 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1094 declaration->type = type;
1095 declaration->symbol = symbol;
1096 declaration->source_position = builtin_source_position;
1097 declaration->implicit = true;
1099 record_declaration(declaration, false);
1101 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1102 typedef_type->typedeft.declaration = declaration;
1104 return typedef_type;
1107 static string_t parse_string_literals(void)
1109 assert(token.type == T_STRING_LITERAL);
1110 string_t result = token.v.string;
1114 while (token.type == T_STRING_LITERAL) {
1115 result = concat_strings(&result, &token.v.string);
1122 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1123 [GNU_AK_CONST] = "const",
1124 [GNU_AK_VOLATILE] = "volatile",
1125 [GNU_AK_CDECL] = "cdecl",
1126 [GNU_AK_STDCALL] = "stdcall",
1127 [GNU_AK_FASTCALL] = "fastcall",
1128 [GNU_AK_DEPRECATED] = "deprecated",
1129 [GNU_AK_NOINLINE] = "noinline",
1130 [GNU_AK_NORETURN] = "noreturn",
1131 [GNU_AK_NAKED] = "naked",
1132 [GNU_AK_PURE] = "pure",
1133 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1134 [GNU_AK_MALLOC] = "malloc",
1135 [GNU_AK_WEAK] = "weak",
1136 [GNU_AK_CONSTRUCTOR] = "constructor",
1137 [GNU_AK_DESTRUCTOR] = "destructor",
1138 [GNU_AK_NOTHROW] = "nothrow",
1139 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1140 [GNU_AK_COMMON] = "common",
1141 [GNU_AK_NOCOMMON] = "nocommon",
1142 [GNU_AK_PACKED] = "packed",
1143 [GNU_AK_SHARED] = "shared",
1144 [GNU_AK_NOTSHARED] = "notshared",
1145 [GNU_AK_USED] = "used",
1146 [GNU_AK_UNUSED] = "unused",
1147 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1148 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1149 [GNU_AK_LONGCALL] = "longcall",
1150 [GNU_AK_SHORTCALL] = "shortcall",
1151 [GNU_AK_LONG_CALL] = "long_call",
1152 [GNU_AK_SHORT_CALL] = "short_call",
1153 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1154 [GNU_AK_INTERRUPT] = "interrupt",
1155 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1156 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1157 [GNU_AK_NESTING] = "nesting",
1158 [GNU_AK_NEAR] = "near",
1159 [GNU_AK_FAR] = "far",
1160 [GNU_AK_SIGNAL] = "signal",
1161 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1162 [GNU_AK_TINY_DATA] = "tiny_data",
1163 [GNU_AK_SAVEALL] = "saveall",
1164 [GNU_AK_FLATTEN] = "flatten",
1165 [GNU_AK_SSEREGPARM] = "sseregparm",
1166 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1167 [GNU_AK_RETURN_TWICE] = "return_twice",
1168 [GNU_AK_MAY_ALIAS] = "may_alias",
1169 [GNU_AK_MS_STRUCT] = "ms_struct",
1170 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1171 [GNU_AK_DLLIMPORT] = "dllimport",
1172 [GNU_AK_DLLEXPORT] = "dllexport",
1173 [GNU_AK_ALIGNED] = "aligned",
1174 [GNU_AK_ALIAS] = "alias",
1175 [GNU_AK_SECTION] = "section",
1176 [GNU_AK_FORMAT] = "format",
1177 [GNU_AK_FORMAT_ARG] = "format_arg",
1178 [GNU_AK_WEAKREF] = "weakref",
1179 [GNU_AK_NONNULL] = "nonnull",
1180 [GNU_AK_TLS_MODEL] = "tls_model",
1181 [GNU_AK_VISIBILITY] = "visibility",
1182 [GNU_AK_REGPARM] = "regparm",
1183 [GNU_AK_MODE] = "mode",
1184 [GNU_AK_MODEL] = "model",
1185 [GNU_AK_TRAP_EXIT] = "trap_exit",
1186 [GNU_AK_SP_SWITCH] = "sp_switch",
1187 [GNU_AK_SENTINEL] = "sentinel"
1191 * compare two string, ignoring double underscores on the second.
1193 static int strcmp_underscore(const char *s1, const char *s2)
1195 if (s2[0] == '_' && s2[1] == '_') {
1196 size_t len2 = strlen(s2);
1197 size_t len1 = strlen(s1);
1198 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1199 return strncmp(s1, s2+2, len2-4);
1203 return strcmp(s1, s2);
1207 * Allocate a new gnu temporal attribute.
1209 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1211 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1212 attribute->kind = kind;
1213 attribute->next = NULL;
1214 attribute->invalid = false;
1215 attribute->have_arguments = false;
1221 * parse one constant expression argument.
1223 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1225 expression_t *expression;
1226 add_anchor_token(')');
1227 expression = parse_constant_expression();
1228 rem_anchor_token(')');
1230 attribute->u.argument = fold_constant(expression);
1233 attribute->invalid = true;
1237 * parse a list of constant expressions arguments.
1239 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1241 argument_list_t **list = &attribute->u.arguments;
1242 argument_list_t *entry;
1243 expression_t *expression;
1244 add_anchor_token(')');
1245 add_anchor_token(',');
1247 expression = parse_constant_expression();
1248 entry = obstack_alloc(&temp_obst, sizeof(entry));
1249 entry->argument = fold_constant(expression);
1252 list = &entry->next;
1253 if (token.type != ',')
1257 rem_anchor_token(',');
1258 rem_anchor_token(')');
1262 attribute->invalid = true;
1266 * parse one string literal argument.
1268 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1271 add_anchor_token('(');
1272 if (token.type != T_STRING_LITERAL) {
1273 parse_error_expected("while parsing attribute directive",
1274 T_STRING_LITERAL, NULL);
1277 *string = parse_string_literals();
1278 rem_anchor_token('(');
1282 attribute->invalid = true;
1286 * parse one tls model.
1288 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1290 static const char *const tls_models[] = {
1296 string_t string = { NULL, 0 };
1297 parse_gnu_attribute_string_arg(attribute, &string);
1298 if (string.begin != NULL) {
1299 for(size_t i = 0; i < 4; ++i) {
1300 if (strcmp(tls_models[i], string.begin) == 0) {
1301 attribute->u.value = i;
1305 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1307 attribute->invalid = true;
1311 * parse one tls model.
1313 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1315 static const char *const visibilities[] = {
1321 string_t string = { NULL, 0 };
1322 parse_gnu_attribute_string_arg(attribute, &string);
1323 if (string.begin != NULL) {
1324 for(size_t i = 0; i < 4; ++i) {
1325 if (strcmp(visibilities[i], string.begin) == 0) {
1326 attribute->u.value = i;
1330 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1332 attribute->invalid = true;
1336 * parse one (code) model.
1338 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1340 static const char *const visibilities[] = {
1345 string_t string = { NULL, 0 };
1346 parse_gnu_attribute_string_arg(attribute, &string);
1347 if (string.begin != NULL) {
1348 for(int i = 0; i < 3; ++i) {
1349 if (strcmp(visibilities[i], string.begin) == 0) {
1350 attribute->u.value = i;
1354 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1356 attribute->invalid = true;
1359 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1361 /* TODO: find out what is allowed here... */
1363 /* at least: byte, word, pointer, list of machine modes
1364 * __XXX___ is interpreted as XXX */
1365 add_anchor_token(')');
1367 if (token.type != T_IDENTIFIER) {
1368 expect(T_IDENTIFIER);
1371 /* This isn't really correct, the backend should provide a list of machine
1372 * specific modes (according to gcc philosophy that is...) */
1373 const char *symbol_str = token.v.symbol->string;
1374 if (strcmp_underscore("QI", symbol_str) == 0 ||
1375 strcmp_underscore("byte", symbol_str) == 0) {
1376 attribute->u.akind = ATOMIC_TYPE_CHAR;
1377 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1378 attribute->u.akind = ATOMIC_TYPE_SHORT;
1379 } else if (strcmp_underscore("SI", symbol_str) == 0
1380 || strcmp_underscore("word", symbol_str) == 0
1381 || strcmp_underscore("pointer", symbol_str) == 0) {
1382 attribute->u.akind = ATOMIC_TYPE_INT;
1383 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1384 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1386 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1387 attribute->invalid = true;
1391 rem_anchor_token(')');
1395 attribute->invalid = true;
1399 * parse one interrupt argument.
1401 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1403 static const char *const interrupts[] = {
1410 string_t string = { NULL, 0 };
1411 parse_gnu_attribute_string_arg(attribute, &string);
1412 if (string.begin != NULL) {
1413 for(size_t i = 0; i < 5; ++i) {
1414 if (strcmp(interrupts[i], string.begin) == 0) {
1415 attribute->u.value = i;
1419 errorf(HERE, "'%s' is not an interrupt", string.begin);
1421 attribute->invalid = true;
1425 * parse ( identifier, const expression, const expression )
1427 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1429 static const char *const format_names[] = {
1437 if (token.type != T_IDENTIFIER) {
1438 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1441 const char *name = token.v.symbol->string;
1442 for(i = 0; i < 4; ++i) {
1443 if (strcmp_underscore(format_names[i], name) == 0)
1447 if (warning.attribute)
1448 warningf(HERE, "'%s' is an unrecognized format function type", name);
1453 add_anchor_token(')');
1454 add_anchor_token(',');
1455 parse_constant_expression();
1456 rem_anchor_token(',');
1457 rem_anchor_token('(');
1460 add_anchor_token(')');
1461 parse_constant_expression();
1462 rem_anchor_token('(');
1466 attribute->u.value = true;
1469 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1471 if (!attribute->have_arguments)
1474 /* should have no arguments */
1475 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1476 eat_until_matching_token('(');
1477 /* we have already consumed '(', so we stop before ')', eat it */
1479 attribute->invalid = true;
1483 * Parse one GNU attribute.
1485 * Note that attribute names can be specified WITH or WITHOUT
1486 * double underscores, ie const or __const__.
1488 * The following attributes are parsed without arguments
1513 * no_instrument_function
1514 * warn_unused_result
1531 * externally_visible
1539 * The following attributes are parsed with arguments
1540 * aligned( const expression )
1541 * alias( string literal )
1542 * section( string literal )
1543 * format( identifier, const expression, const expression )
1544 * format_arg( const expression )
1545 * tls_model( string literal )
1546 * visibility( string literal )
1547 * regparm( const expression )
1548 * model( string leteral )
1549 * trap_exit( const expression )
1550 * sp_switch( string literal )
1552 * The following attributes might have arguments
1553 * weak_ref( string literal )
1554 * non_null( const expression // ',' )
1555 * interrupt( string literal )
1556 * sentinel( constant expression )
1558 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1560 gnu_attribute_t *head = *attributes;
1561 gnu_attribute_t *last = *attributes;
1562 decl_modifiers_t modifiers = 0;
1563 gnu_attribute_t *attribute;
1565 eat(T___attribute__);
1569 if (token.type != ')') {
1570 /* find the end of the list */
1572 while (last->next != NULL)
1576 /* non-empty attribute list */
1579 if (token.type == T_const) {
1581 } else if (token.type == T_volatile) {
1583 } else if (token.type == T_cdecl) {
1584 /* __attribute__((cdecl)), WITH ms mode */
1586 } else if (token.type == T_IDENTIFIER) {
1587 const symbol_t *sym = token.v.symbol;
1590 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1597 for(i = 0; i < GNU_AK_LAST; ++i) {
1598 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1601 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1604 if (kind == GNU_AK_LAST) {
1605 if (warning.attribute)
1606 warningf(HERE, "'%s' attribute directive ignored", name);
1608 /* skip possible arguments */
1609 if (token.type == '(') {
1610 eat_until_matching_token(')');
1613 /* check for arguments */
1614 attribute = allocate_gnu_attribute(kind);
1615 if (token.type == '(') {
1617 if (token.type == ')') {
1618 /* empty args are allowed */
1621 attribute->have_arguments = true;
1626 case GNU_AK_VOLATILE:
1631 case GNU_AK_NOCOMMON:
1633 case GNU_AK_NOTSHARED:
1634 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1635 case GNU_AK_WARN_UNUSED_RESULT:
1636 case GNU_AK_LONGCALL:
1637 case GNU_AK_SHORTCALL:
1638 case GNU_AK_LONG_CALL:
1639 case GNU_AK_SHORT_CALL:
1640 case GNU_AK_FUNCTION_VECTOR:
1641 case GNU_AK_INTERRUPT_HANDLER:
1642 case GNU_AK_NMI_HANDLER:
1643 case GNU_AK_NESTING:
1647 case GNU_AK_EIGTHBIT_DATA:
1648 case GNU_AK_TINY_DATA:
1649 case GNU_AK_SAVEALL:
1650 case GNU_AK_FLATTEN:
1651 case GNU_AK_SSEREGPARM:
1652 case GNU_AK_EXTERNALLY_VISIBLE:
1653 case GNU_AK_RETURN_TWICE:
1654 case GNU_AK_MAY_ALIAS:
1655 case GNU_AK_MS_STRUCT:
1656 case GNU_AK_GCC_STRUCT:
1659 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1660 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1661 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1662 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1663 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1664 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1665 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1666 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1667 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1668 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1669 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1670 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1671 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1672 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1673 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1674 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1675 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1677 case GNU_AK_ALIGNED:
1678 /* __align__ may be used without an argument */
1679 if (attribute->have_arguments) {
1680 parse_gnu_attribute_const_arg(attribute);
1684 case GNU_AK_FORMAT_ARG:
1685 case GNU_AK_REGPARM:
1686 case GNU_AK_TRAP_EXIT:
1687 if (!attribute->have_arguments) {
1688 /* should have arguments */
1689 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1690 attribute->invalid = true;
1692 parse_gnu_attribute_const_arg(attribute);
1695 case GNU_AK_SECTION:
1696 case GNU_AK_SP_SWITCH:
1697 if (!attribute->have_arguments) {
1698 /* should have arguments */
1699 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1700 attribute->invalid = true;
1702 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1705 if (!attribute->have_arguments) {
1706 /* should have arguments */
1707 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1708 attribute->invalid = true;
1710 parse_gnu_attribute_format_args(attribute);
1712 case GNU_AK_WEAKREF:
1713 /* may have one string argument */
1714 if (attribute->have_arguments)
1715 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1717 case GNU_AK_NONNULL:
1718 if (attribute->have_arguments)
1719 parse_gnu_attribute_const_arg_list(attribute);
1721 case GNU_AK_TLS_MODEL:
1722 if (!attribute->have_arguments) {
1723 /* should have arguments */
1724 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1726 parse_gnu_attribute_tls_model_arg(attribute);
1728 case GNU_AK_VISIBILITY:
1729 if (!attribute->have_arguments) {
1730 /* should have arguments */
1731 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1733 parse_gnu_attribute_visibility_arg(attribute);
1736 if (!attribute->have_arguments) {
1737 /* should have arguments */
1738 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1740 parse_gnu_attribute_model_arg(attribute);
1744 if (!attribute->have_arguments) {
1745 /* should have arguments */
1746 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1748 parse_gnu_attribute_mode_arg(attribute);
1751 case GNU_AK_INTERRUPT:
1752 /* may have one string argument */
1753 if (attribute->have_arguments)
1754 parse_gnu_attribute_interrupt_arg(attribute);
1756 case GNU_AK_SENTINEL:
1757 /* may have one string argument */
1758 if (attribute->have_arguments)
1759 parse_gnu_attribute_const_arg(attribute);
1762 /* already handled */
1766 check_no_argument(attribute, name);
1769 if (attribute != NULL) {
1771 last->next = attribute;
1774 head = last = attribute;
1778 if (token.type != ',')
1792 * Parse GNU attributes.
1794 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1796 decl_modifiers_t modifiers = 0;
1799 switch(token.type) {
1800 case T___attribute__:
1801 modifiers |= parse_gnu_attribute(attributes);
1807 if (token.type != T_STRING_LITERAL) {
1808 parse_error_expected("while parsing assembler attribute",
1809 T_STRING_LITERAL, NULL);
1810 eat_until_matching_token('(');
1813 parse_string_literals();
1818 case T_cdecl: modifiers |= DM_CDECL; break;
1819 case T__fastcall: modifiers |= DM_FASTCALL; break;
1820 case T__stdcall: modifiers |= DM_STDCALL; break;
1823 /* TODO record modifier */
1824 warningf(HERE, "Ignoring declaration modifier %K", &token);
1828 default: return modifiers;
1835 static designator_t *parse_designation(void)
1837 designator_t *result = NULL;
1838 designator_t *last = NULL;
1841 designator_t *designator;
1842 switch(token.type) {
1844 designator = allocate_ast_zero(sizeof(designator[0]));
1845 designator->source_position = token.source_position;
1847 add_anchor_token(']');
1848 designator->array_index = parse_constant_expression();
1849 rem_anchor_token(']');
1853 designator = allocate_ast_zero(sizeof(designator[0]));
1854 designator->source_position = token.source_position;
1856 if (token.type != T_IDENTIFIER) {
1857 parse_error_expected("while parsing designator",
1858 T_IDENTIFIER, NULL);
1861 designator->symbol = token.v.symbol;
1869 assert(designator != NULL);
1871 last->next = designator;
1873 result = designator;
1881 static initializer_t *initializer_from_string(array_type_t *type,
1882 const string_t *const string)
1884 /* TODO: check len vs. size of array type */
1887 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1888 initializer->string.string = *string;
1893 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1894 wide_string_t *const string)
1896 /* TODO: check len vs. size of array type */
1899 initializer_t *const initializer =
1900 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1901 initializer->wide_string.string = *string;
1907 * Build an initializer from a given expression.
1909 static initializer_t *initializer_from_expression(type_t *orig_type,
1910 expression_t *expression)
1912 /* TODO check that expression is a constant expression */
1914 /* § 6.7.8.14/15 char array may be initialized by string literals */
1915 type_t *type = skip_typeref(orig_type);
1916 type_t *expr_type_orig = expression->base.type;
1917 type_t *expr_type = skip_typeref(expr_type_orig);
1918 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1919 array_type_t *const array_type = &type->array;
1920 type_t *const element_type = skip_typeref(array_type->element_type);
1922 if (element_type->kind == TYPE_ATOMIC) {
1923 atomic_type_kind_t akind = element_type->atomic.akind;
1924 switch (expression->kind) {
1925 case EXPR_STRING_LITERAL:
1926 if (akind == ATOMIC_TYPE_CHAR
1927 || akind == ATOMIC_TYPE_SCHAR
1928 || akind == ATOMIC_TYPE_UCHAR) {
1929 return initializer_from_string(array_type,
1930 &expression->string.value);
1933 case EXPR_WIDE_STRING_LITERAL: {
1934 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1935 if (get_unqualified_type(element_type) == bare_wchar_type) {
1936 return initializer_from_wide_string(array_type,
1937 &expression->wide_string.value);
1947 assign_error_t error = semantic_assign(type, expression);
1948 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1950 report_assign_error(error, type, expression, "initializer",
1951 &expression->base.source_position);
1953 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1954 result->value.value = create_implicit_cast(expression, type);
1960 * Checks if a given expression can be used as an constant initializer.
1962 static bool is_initializer_constant(const expression_t *expression)
1964 return is_constant_expression(expression)
1965 || is_address_constant(expression);
1969 * Parses an scalar initializer.
1971 * § 6.7.8.11; eat {} without warning
1973 static initializer_t *parse_scalar_initializer(type_t *type,
1974 bool must_be_constant)
1976 /* there might be extra {} hierarchies */
1978 if (token.type == '{') {
1979 warningf(HERE, "extra curly braces around scalar initializer");
1983 } while (token.type == '{');
1986 expression_t *expression = parse_assignment_expression();
1987 if (must_be_constant && !is_initializer_constant(expression)) {
1988 errorf(&expression->base.source_position,
1989 "Initialisation expression '%E' is not constant\n",
1993 initializer_t *initializer = initializer_from_expression(type, expression);
1995 if (initializer == NULL) {
1996 errorf(&expression->base.source_position,
1997 "expression '%E' (type '%T') doesn't match expected type '%T'",
1998 expression, expression->base.type, type);
2003 bool additional_warning_displayed = false;
2004 while (braces > 0) {
2005 if (token.type == ',') {
2008 if (token.type != '}') {
2009 if (!additional_warning_displayed) {
2010 warningf(HERE, "additional elements in scalar initializer");
2011 additional_warning_displayed = true;
2022 * An entry in the type path.
2024 typedef struct type_path_entry_t type_path_entry_t;
2025 struct type_path_entry_t {
2026 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2028 size_t index; /**< For array types: the current index. */
2029 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2034 * A type path expression a position inside compound or array types.
2036 typedef struct type_path_t type_path_t;
2037 struct type_path_t {
2038 type_path_entry_t *path; /**< An flexible array containing the current path. */
2039 type_t *top_type; /**< type of the element the path points */
2040 size_t max_index; /**< largest index in outermost array */
2044 * Prints a type path for debugging.
2046 static __attribute__((unused)) void debug_print_type_path(
2047 const type_path_t *path)
2049 size_t len = ARR_LEN(path->path);
2051 for(size_t i = 0; i < len; ++i) {
2052 const type_path_entry_t *entry = & path->path[i];
2054 type_t *type = skip_typeref(entry->type);
2055 if (is_type_compound(type)) {
2056 /* in gcc mode structs can have no members */
2057 if (entry->v.compound_entry == NULL) {
2061 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
2062 } else if (is_type_array(type)) {
2063 fprintf(stderr, "[%zu]", entry->v.index);
2065 fprintf(stderr, "-INVALID-");
2068 if (path->top_type != NULL) {
2069 fprintf(stderr, " (");
2070 print_type(path->top_type);
2071 fprintf(stderr, ")");
2076 * Return the top type path entry, ie. in a path
2077 * (type).a.b returns the b.
2079 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2081 size_t len = ARR_LEN(path->path);
2083 return &path->path[len-1];
2087 * Enlarge the type path by an (empty) element.
2089 static type_path_entry_t *append_to_type_path(type_path_t *path)
2091 size_t len = ARR_LEN(path->path);
2092 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2094 type_path_entry_t *result = & path->path[len];
2095 memset(result, 0, sizeof(result[0]));
2100 * Descending into a sub-type. Enter the scope of the current
2103 static void descend_into_subtype(type_path_t *path)
2105 type_t *orig_top_type = path->top_type;
2106 type_t *top_type = skip_typeref(orig_top_type);
2108 assert(is_type_compound(top_type) || is_type_array(top_type));
2110 type_path_entry_t *top = append_to_type_path(path);
2111 top->type = top_type;
2113 if (is_type_compound(top_type)) {
2114 declaration_t *declaration = top_type->compound.declaration;
2115 declaration_t *entry = declaration->scope.declarations;
2116 top->v.compound_entry = entry;
2118 if (entry != NULL) {
2119 path->top_type = entry->type;
2121 path->top_type = NULL;
2124 assert(is_type_array(top_type));
2127 path->top_type = top_type->array.element_type;
2132 * Pop an entry from the given type path, ie. returning from
2133 * (type).a.b to (type).a
2135 static void ascend_from_subtype(type_path_t *path)
2137 type_path_entry_t *top = get_type_path_top(path);
2139 path->top_type = top->type;
2141 size_t len = ARR_LEN(path->path);
2142 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2146 * Pop entries from the given type path until the given
2147 * path level is reached.
2149 static void ascend_to(type_path_t *path, size_t top_path_level)
2151 size_t len = ARR_LEN(path->path);
2153 while (len > top_path_level) {
2154 ascend_from_subtype(path);
2155 len = ARR_LEN(path->path);
2159 static bool walk_designator(type_path_t *path, const designator_t *designator,
2160 bool used_in_offsetof)
2162 for( ; designator != NULL; designator = designator->next) {
2163 type_path_entry_t *top = get_type_path_top(path);
2164 type_t *orig_type = top->type;
2166 type_t *type = skip_typeref(orig_type);
2168 if (designator->symbol != NULL) {
2169 symbol_t *symbol = designator->symbol;
2170 if (!is_type_compound(type)) {
2171 if (is_type_valid(type)) {
2172 errorf(&designator->source_position,
2173 "'.%Y' designator used for non-compound type '%T'",
2179 declaration_t *declaration = type->compound.declaration;
2180 declaration_t *iter = declaration->scope.declarations;
2181 for( ; iter != NULL; iter = iter->next) {
2182 if (iter->symbol == symbol) {
2187 errorf(&designator->source_position,
2188 "'%T' has no member named '%Y'", orig_type, symbol);
2191 if (used_in_offsetof) {
2192 type_t *real_type = skip_typeref(iter->type);
2193 if (real_type->kind == TYPE_BITFIELD) {
2194 errorf(&designator->source_position,
2195 "offsetof designator '%Y' may not specify bitfield",
2201 top->type = orig_type;
2202 top->v.compound_entry = iter;
2203 orig_type = iter->type;
2205 expression_t *array_index = designator->array_index;
2206 assert(designator->array_index != NULL);
2208 if (!is_type_array(type)) {
2209 if (is_type_valid(type)) {
2210 errorf(&designator->source_position,
2211 "[%E] designator used for non-array type '%T'",
2212 array_index, orig_type);
2216 if (!is_type_valid(array_index->base.type)) {
2220 long index = fold_constant(array_index);
2221 if (!used_in_offsetof) {
2223 errorf(&designator->source_position,
2224 "array index [%E] must be positive", array_index);
2227 if (type->array.size_constant == true) {
2228 long array_size = type->array.size;
2229 if (index >= array_size) {
2230 errorf(&designator->source_position,
2231 "designator [%E] (%d) exceeds array size %d",
2232 array_index, index, array_size);
2238 top->type = orig_type;
2239 top->v.index = (size_t) index;
2240 orig_type = type->array.element_type;
2242 path->top_type = orig_type;
2244 if (designator->next != NULL) {
2245 descend_into_subtype(path);
2254 static void advance_current_object(type_path_t *path, size_t top_path_level)
2256 type_path_entry_t *top = get_type_path_top(path);
2258 type_t *type = skip_typeref(top->type);
2259 if (is_type_union(type)) {
2260 /* in unions only the first element is initialized */
2261 top->v.compound_entry = NULL;
2262 } else if (is_type_struct(type)) {
2263 declaration_t *entry = top->v.compound_entry;
2265 entry = entry->next;
2266 top->v.compound_entry = entry;
2267 if (entry != NULL) {
2268 path->top_type = entry->type;
2272 assert(is_type_array(type));
2276 if (!type->array.size_constant || top->v.index < type->array.size) {
2281 /* we're past the last member of the current sub-aggregate, try if we
2282 * can ascend in the type hierarchy and continue with another subobject */
2283 size_t len = ARR_LEN(path->path);
2285 if (len > top_path_level) {
2286 ascend_from_subtype(path);
2287 advance_current_object(path, top_path_level);
2289 path->top_type = NULL;
2294 * skip until token is found.
2296 static void skip_until(int type)
2298 while (token.type != type) {
2299 if (token.type == T_EOF)
2306 * skip any {...} blocks until a closing bracket is reached.
2308 static void skip_initializers(void)
2310 if (token.type == '{')
2313 while (token.type != '}') {
2314 if (token.type == T_EOF)
2316 if (token.type == '{') {
2324 static initializer_t *create_empty_initializer(void)
2326 static initializer_t empty_initializer
2327 = { .list = { { INITIALIZER_LIST }, 0 } };
2328 return &empty_initializer;
2332 * Parse a part of an initialiser for a struct or union,
2334 static initializer_t *parse_sub_initializer(type_path_t *path,
2335 type_t *outer_type, size_t top_path_level,
2336 parse_initializer_env_t *env)
2338 if (token.type == '}') {
2339 /* empty initializer */
2340 return create_empty_initializer();
2343 type_t *orig_type = path->top_type;
2344 type_t *type = NULL;
2346 if (orig_type == NULL) {
2347 /* We are initializing an empty compound. */
2349 type = skip_typeref(orig_type);
2351 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2352 * initializers in this case. */
2353 if (!is_type_valid(type)) {
2354 skip_initializers();
2355 return create_empty_initializer();
2359 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2362 designator_t *designator = NULL;
2363 if (token.type == '.' || token.type == '[') {
2364 designator = parse_designation();
2365 goto finish_designator;
2366 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2367 /* GNU-style designator ("identifier: value") */
2368 designator = allocate_ast_zero(sizeof(designator[0]));
2369 designator->source_position = token.source_position;
2370 designator->symbol = token.v.symbol;
2375 /* reset path to toplevel, evaluate designator from there */
2376 ascend_to(path, top_path_level);
2377 if (!walk_designator(path, designator, false)) {
2378 /* can't continue after designation error */
2382 initializer_t *designator_initializer
2383 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2384 designator_initializer->designator.designator = designator;
2385 ARR_APP1(initializer_t*, initializers, designator_initializer);
2387 orig_type = path->top_type;
2388 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2393 if (token.type == '{') {
2394 if (type != NULL && is_type_scalar(type)) {
2395 sub = parse_scalar_initializer(type, env->must_be_constant);
2399 if (env->declaration != NULL) {
2400 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2401 env->declaration->symbol);
2403 errorf(HERE, "extra brace group at end of initializer");
2406 descend_into_subtype(path);
2408 add_anchor_token('}');
2409 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2411 rem_anchor_token('}');
2414 ascend_from_subtype(path);
2418 goto error_parse_next;
2422 /* must be an expression */
2423 expression_t *expression = parse_assignment_expression();
2425 if (env->must_be_constant && !is_initializer_constant(expression)) {
2426 errorf(&expression->base.source_position,
2427 "Initialisation expression '%E' is not constant\n",
2432 /* we are already outside, ... */
2436 /* handle { "string" } special case */
2437 if ((expression->kind == EXPR_STRING_LITERAL
2438 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2439 && outer_type != NULL) {
2440 sub = initializer_from_expression(outer_type, expression);
2442 if (token.type == ',') {
2445 if (token.type != '}') {
2446 warningf(HERE, "excessive elements in initializer for type '%T'",
2449 /* TODO: eat , ... */
2454 /* descend into subtypes until expression matches type */
2456 orig_type = path->top_type;
2457 type = skip_typeref(orig_type);
2459 sub = initializer_from_expression(orig_type, expression);
2463 if (!is_type_valid(type)) {
2466 if (is_type_scalar(type)) {
2467 errorf(&expression->base.source_position,
2468 "expression '%E' doesn't match expected type '%T'",
2469 expression, orig_type);
2473 descend_into_subtype(path);
2477 /* update largest index of top array */
2478 const type_path_entry_t *first = &path->path[0];
2479 type_t *first_type = first->type;
2480 first_type = skip_typeref(first_type);
2481 if (is_type_array(first_type)) {
2482 size_t index = first->v.index;
2483 if (index > path->max_index)
2484 path->max_index = index;
2488 /* append to initializers list */
2489 ARR_APP1(initializer_t*, initializers, sub);
2492 if (env->declaration != NULL)
2493 warningf(HERE, "excess elements in struct initializer for '%Y'",
2494 env->declaration->symbol);
2496 warningf(HERE, "excess elements in struct initializer");
2500 if (token.type == '}') {
2504 if (token.type == '}') {
2509 /* advance to the next declaration if we are not at the end */
2510 advance_current_object(path, top_path_level);
2511 orig_type = path->top_type;
2512 if (orig_type != NULL)
2513 type = skip_typeref(orig_type);
2519 size_t len = ARR_LEN(initializers);
2520 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2521 initializer_t *result = allocate_ast_zero(size);
2522 result->kind = INITIALIZER_LIST;
2523 result->list.len = len;
2524 memcpy(&result->list.initializers, initializers,
2525 len * sizeof(initializers[0]));
2527 DEL_ARR_F(initializers);
2528 ascend_to(path, top_path_level+1);
2533 skip_initializers();
2534 DEL_ARR_F(initializers);
2535 ascend_to(path, top_path_level+1);
2540 * Parses an initializer. Parsers either a compound literal
2541 * (env->declaration == NULL) or an initializer of a declaration.
2543 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2545 type_t *type = skip_typeref(env->type);
2546 initializer_t *result = NULL;
2549 if (is_type_scalar(type)) {
2550 result = parse_scalar_initializer(type, env->must_be_constant);
2551 } else if (token.type == '{') {
2555 memset(&path, 0, sizeof(path));
2556 path.top_type = env->type;
2557 path.path = NEW_ARR_F(type_path_entry_t, 0);
2559 descend_into_subtype(&path);
2561 add_anchor_token('}');
2562 result = parse_sub_initializer(&path, env->type, 1, env);
2563 rem_anchor_token('}');
2565 max_index = path.max_index;
2566 DEL_ARR_F(path.path);
2570 /* parse_scalar_initializer() also works in this case: we simply
2571 * have an expression without {} around it */
2572 result = parse_scalar_initializer(type, env->must_be_constant);
2575 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2576 * the array type size */
2577 if (is_type_array(type) && type->array.size_expression == NULL
2578 && result != NULL) {
2580 switch (result->kind) {
2581 case INITIALIZER_LIST:
2582 size = max_index + 1;
2585 case INITIALIZER_STRING:
2586 size = result->string.string.size;
2589 case INITIALIZER_WIDE_STRING:
2590 size = result->wide_string.string.size;
2593 case INITIALIZER_DESIGNATOR:
2594 case INITIALIZER_VALUE:
2595 /* can happen for parse errors */
2600 internal_errorf(HERE, "invalid initializer type");
2603 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2604 cnst->base.type = type_size_t;
2605 cnst->conste.v.int_value = size;
2607 type_t *new_type = duplicate_type(type);
2609 new_type->array.size_expression = cnst;
2610 new_type->array.size_constant = true;
2611 new_type->array.size = size;
2612 env->type = new_type;
2620 static declaration_t *append_declaration(declaration_t *declaration);
2622 static declaration_t *parse_compound_type_specifier(bool is_struct)
2624 gnu_attribute_t *attributes = NULL;
2625 decl_modifiers_t modifiers = 0;
2632 symbol_t *symbol = NULL;
2633 declaration_t *declaration = NULL;
2635 if (token.type == T___attribute__) {
2636 modifiers |= parse_attributes(&attributes);
2639 if (token.type == T_IDENTIFIER) {
2640 symbol = token.v.symbol;
2643 namespace_t const namespc =
2644 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2645 declaration = get_declaration(symbol, namespc);
2646 if (declaration != NULL) {
2647 if (declaration->parent_scope != scope &&
2648 (token.type == '{' || token.type == ';')) {
2650 } else if (declaration->init.complete &&
2651 token.type == '{') {
2652 assert(symbol != NULL);
2653 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2654 is_struct ? "struct" : "union", symbol,
2655 &declaration->source_position);
2656 declaration->scope.declarations = NULL;
2659 } else if (token.type != '{') {
2661 parse_error_expected("while parsing struct type specifier",
2662 T_IDENTIFIER, '{', NULL);
2664 parse_error_expected("while parsing union type specifier",
2665 T_IDENTIFIER, '{', NULL);
2671 if (declaration == NULL) {
2672 declaration = allocate_declaration_zero();
2673 declaration->namespc =
2674 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2675 declaration->source_position = token.source_position;
2676 declaration->symbol = symbol;
2677 declaration->parent_scope = scope;
2678 if (symbol != NULL) {
2679 environment_push(declaration);
2681 append_declaration(declaration);
2684 if (token.type == '{') {
2685 declaration->init.complete = true;
2687 parse_compound_type_entries(declaration);
2688 modifiers |= parse_attributes(&attributes);
2691 declaration->modifiers |= modifiers;
2695 static void parse_enum_entries(type_t *const enum_type)
2699 if (token.type == '}') {
2701 errorf(HERE, "empty enum not allowed");
2705 add_anchor_token('}');
2707 if (token.type != T_IDENTIFIER) {
2708 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2710 rem_anchor_token('}');
2714 declaration_t *const entry = allocate_declaration_zero();
2715 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2716 entry->type = enum_type;
2717 entry->symbol = token.v.symbol;
2718 entry->source_position = token.source_position;
2721 if (token.type == '=') {
2723 expression_t *value = parse_constant_expression();
2725 value = create_implicit_cast(value, enum_type);
2726 entry->init.enum_value = value;
2731 record_declaration(entry, false);
2733 if (token.type != ',')
2736 } while (token.type != '}');
2737 rem_anchor_token('}');
2745 static type_t *parse_enum_specifier(void)
2747 gnu_attribute_t *attributes = NULL;
2748 declaration_t *declaration;
2752 if (token.type == T_IDENTIFIER) {
2753 symbol = token.v.symbol;
2756 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2757 } else if (token.type != '{') {
2758 parse_error_expected("while parsing enum type specifier",
2759 T_IDENTIFIER, '{', NULL);
2766 if (declaration == NULL) {
2767 declaration = allocate_declaration_zero();
2768 declaration->namespc = NAMESPACE_ENUM;
2769 declaration->source_position = token.source_position;
2770 declaration->symbol = symbol;
2771 declaration->parent_scope = scope;
2774 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2775 type->enumt.declaration = declaration;
2777 if (token.type == '{') {
2778 if (declaration->init.complete) {
2779 errorf(HERE, "multiple definitions of enum %Y", symbol);
2781 if (symbol != NULL) {
2782 environment_push(declaration);
2784 append_declaration(declaration);
2785 declaration->init.complete = true;
2787 parse_enum_entries(type);
2788 parse_attributes(&attributes);
2795 * if a symbol is a typedef to another type, return true
2797 static bool is_typedef_symbol(symbol_t *symbol)
2799 const declaration_t *const declaration =
2800 get_declaration(symbol, NAMESPACE_NORMAL);
2802 declaration != NULL &&
2803 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2806 static type_t *parse_typeof(void)
2813 add_anchor_token(')');
2815 expression_t *expression = NULL;
2818 switch(token.type) {
2819 case T___extension__:
2820 /* This can be a prefix to a typename or an expression. We simply eat
2824 } while (token.type == T___extension__);
2828 if (is_typedef_symbol(token.v.symbol)) {
2829 type = parse_typename();
2831 expression = parse_expression();
2832 type = expression->base.type;
2837 type = parse_typename();
2841 expression = parse_expression();
2842 type = expression->base.type;
2846 rem_anchor_token(')');
2849 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2850 typeof_type->typeoft.expression = expression;
2851 typeof_type->typeoft.typeof_type = type;
2858 typedef enum specifiers_t {
2859 SPECIFIER_SIGNED = 1 << 0,
2860 SPECIFIER_UNSIGNED = 1 << 1,
2861 SPECIFIER_LONG = 1 << 2,
2862 SPECIFIER_INT = 1 << 3,
2863 SPECIFIER_DOUBLE = 1 << 4,
2864 SPECIFIER_CHAR = 1 << 5,
2865 SPECIFIER_SHORT = 1 << 6,
2866 SPECIFIER_LONG_LONG = 1 << 7,
2867 SPECIFIER_FLOAT = 1 << 8,
2868 SPECIFIER_BOOL = 1 << 9,
2869 SPECIFIER_VOID = 1 << 10,
2870 SPECIFIER_INT8 = 1 << 11,
2871 SPECIFIER_INT16 = 1 << 12,
2872 SPECIFIER_INT32 = 1 << 13,
2873 SPECIFIER_INT64 = 1 << 14,
2874 SPECIFIER_INT128 = 1 << 15,
2875 SPECIFIER_COMPLEX = 1 << 16,
2876 SPECIFIER_IMAGINARY = 1 << 17,
2879 static type_t *create_builtin_type(symbol_t *const symbol,
2880 type_t *const real_type)
2882 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2883 type->builtin.symbol = symbol;
2884 type->builtin.real_type = real_type;
2886 type_t *result = typehash_insert(type);
2887 if (type != result) {
2894 static type_t *get_typedef_type(symbol_t *symbol)
2896 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2897 if (declaration == NULL ||
2898 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2901 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2902 type->typedeft.declaration = declaration;
2908 * check for the allowed MS alignment values.
2910 static bool check_alignment_value(long long intvalue)
2912 if (intvalue < 1 || intvalue > 8192) {
2913 errorf(HERE, "illegal alignment value");
2916 unsigned v = (unsigned)intvalue;
2917 for(unsigned i = 1; i <= 8192; i += i) {
2921 errorf(HERE, "alignment must be power of two");
2925 #define DET_MOD(name, tag) do { \
2926 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2927 *modifiers |= tag; \
2930 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2932 decl_modifiers_t *modifiers = &specifiers->modifiers;
2935 if (token.type == T_restrict) {
2937 DET_MOD(restrict, DM_RESTRICT);
2939 } else if (token.type != T_IDENTIFIER)
2941 symbol_t *symbol = token.v.symbol;
2942 if (symbol == sym_align) {
2945 if (token.type != T_INTEGER)
2947 if (check_alignment_value(token.v.intvalue)) {
2948 if (specifiers->alignment != 0)
2949 warningf(HERE, "align used more than once");
2950 specifiers->alignment = (unsigned char)token.v.intvalue;
2954 } else if (symbol == sym_allocate) {
2957 if (token.type != T_IDENTIFIER)
2959 (void)token.v.symbol;
2961 } else if (symbol == sym_dllimport) {
2963 DET_MOD(dllimport, DM_DLLIMPORT);
2964 } else if (symbol == sym_dllexport) {
2966 DET_MOD(dllexport, DM_DLLEXPORT);
2967 } else if (symbol == sym_thread) {
2969 DET_MOD(thread, DM_THREAD);
2970 } else if (symbol == sym_naked) {
2972 DET_MOD(naked, DM_NAKED);
2973 } else if (symbol == sym_noinline) {
2975 DET_MOD(noinline, DM_NOINLINE);
2976 } else if (symbol == sym_noreturn) {
2978 DET_MOD(noreturn, DM_NORETURN);
2979 } else if (symbol == sym_nothrow) {
2981 DET_MOD(nothrow, DM_NOTHROW);
2982 } else if (symbol == sym_novtable) {
2984 DET_MOD(novtable, DM_NOVTABLE);
2985 } else if (symbol == sym_property) {
2989 bool is_get = false;
2990 if (token.type != T_IDENTIFIER)
2992 if (token.v.symbol == sym_get) {
2994 } else if (token.v.symbol == sym_put) {
2996 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3001 if (token.type != T_IDENTIFIER)
3004 if (specifiers->get_property_sym != NULL) {
3005 errorf(HERE, "get property name already specified");
3007 specifiers->get_property_sym = token.v.symbol;
3010 if (specifiers->put_property_sym != NULL) {
3011 errorf(HERE, "put property name already specified");
3013 specifiers->put_property_sym = token.v.symbol;
3017 if (token.type == ',') {
3024 } else if (symbol == sym_selectany) {
3026 DET_MOD(selectany, DM_SELECTANY);
3027 } else if (symbol == sym_uuid) {
3030 if (token.type != T_STRING_LITERAL)
3034 } else if (symbol == sym_deprecated) {
3036 if (specifiers->deprecated != 0)
3037 warningf(HERE, "deprecated used more than once");
3038 specifiers->deprecated = 1;
3039 if (token.type == '(') {
3041 if (token.type == T_STRING_LITERAL) {
3042 specifiers->deprecated_string = token.v.string.begin;
3045 errorf(HERE, "string literal expected");
3049 } else if (symbol == sym_noalias) {
3051 DET_MOD(noalias, DM_NOALIAS);
3053 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3055 if (token.type == '(')
3059 if (token.type == ',')
3066 static declaration_t *create_error_declaration(symbol_t *symbol, storage_class_tag_t storage_class)
3068 declaration_t *const decl = allocate_declaration_zero();
3069 decl->source_position = *HERE;
3070 decl->declared_storage_class = storage_class;
3071 decl->storage_class =
3072 storage_class != STORAGE_CLASS_NONE || scope == global_scope ?
3073 storage_class : STORAGE_CLASS_AUTO;
3074 decl->symbol = symbol;
3075 decl->implicit = true;
3076 record_declaration(decl, false);
3081 * Finish the construction of a struct type by calculating
3082 * its size, offsets, alignment.
3084 static void finish_struct_type(compound_type_t *type) {
3085 if (type->declaration == NULL)
3087 declaration_t *struct_decl = type->declaration;
3088 if (! struct_decl->init.complete)
3093 il_alignment_t alignment = 1;
3094 bool need_pad = false;
3096 declaration_t *entry = struct_decl->scope.declarations;
3097 for (; entry != NULL; entry = entry->next) {
3098 if (entry->namespc != NAMESPACE_NORMAL)
3101 type_t *m_type = skip_typeref(entry->type);
3102 il_alignment_t m_alignment = m_type->base.alignment;
3104 new_size = (size + m_alignment - 1) & -m_alignment;
3105 if (m_alignment > alignment)
3106 alignment = m_alignment;
3107 if (new_size > size)
3109 entry->offset = new_size;
3110 size = new_size + m_type->base.size;
3112 if (type->base.alignment != 0) {
3113 alignment = type->base.alignment;
3116 new_size = (size + alignment - 1) & -alignment;
3117 if (new_size > size)
3120 if (warning.padded && need_pad) {
3121 warningf(&struct_decl->source_position,
3122 "'%#T' needs padding", type, struct_decl->symbol);
3124 if (warning.packed && !need_pad) {
3125 warningf(&struct_decl->source_position,
3126 "superfluous packed attribute on '%#T'",
3127 type, struct_decl->symbol);
3130 type->base.size = new_size;
3131 type->base.alignment = alignment;
3135 * Finish the construction of an union type by calculating
3136 * its size and alignment.
3138 static void finish_union_type(compound_type_t *type) {
3139 if (type->declaration == NULL)
3141 declaration_t *union_decl = type->declaration;
3142 if (! union_decl->init.complete)
3146 il_alignment_t alignment = 1;
3148 declaration_t *entry = union_decl->scope.declarations;
3149 for (; entry != NULL; entry = entry->next) {
3150 if (entry->namespc != NAMESPACE_NORMAL)
3153 type_t *m_type = skip_typeref(entry->type);
3156 if (m_type->base.size > size)
3157 size = m_type->base.size;
3158 if (m_type->base.alignment > alignment)
3159 alignment = m_type->base.alignment;
3161 if (type->base.alignment != 0) {
3162 alignment = type->base.alignment;
3164 size = (size + alignment - 1) & -alignment;
3165 type->base.size = size;
3166 type->base.alignment = alignment;
3169 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3171 type_t *type = NULL;
3172 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3173 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3174 unsigned type_specifiers = 0;
3175 bool newtype = false;
3176 bool saw_error = false;
3178 specifiers->source_position = token.source_position;
3181 specifiers->modifiers
3182 |= parse_attributes(&specifiers->gnu_attributes);
3183 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3184 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3186 switch(token.type) {
3189 #define MATCH_STORAGE_CLASS(token, class) \
3191 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3192 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3194 specifiers->declared_storage_class = class; \
3198 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3199 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3200 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3201 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3202 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3207 add_anchor_token(')');
3208 parse_microsoft_extended_decl_modifier(specifiers);
3209 rem_anchor_token(')');
3214 switch (specifiers->declared_storage_class) {
3215 case STORAGE_CLASS_NONE:
3216 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3219 case STORAGE_CLASS_EXTERN:
3220 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3223 case STORAGE_CLASS_STATIC:
3224 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3228 errorf(HERE, "multiple storage classes in declaration specifiers");
3234 /* type qualifiers */
3235 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3237 qualifiers |= qualifier; \
3241 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3242 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3243 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3244 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3245 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3246 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3247 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3248 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3250 case T___extension__:
3255 /* type specifiers */
3256 #define MATCH_SPECIFIER(token, specifier, name) \
3259 if (type_specifiers & specifier) { \
3260 errorf(HERE, "multiple " name " type specifiers given"); \
3262 type_specifiers |= specifier; \
3266 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3267 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3268 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3269 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3270 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3271 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3272 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3273 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3274 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3275 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3276 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3277 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3278 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3279 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3280 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3281 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3283 case T__forceinline:
3284 /* only in microsoft mode */
3285 specifiers->modifiers |= DM_FORCEINLINE;
3290 specifiers->is_inline = true;
3295 if (type_specifiers & SPECIFIER_LONG_LONG) {
3296 errorf(HERE, "multiple type specifiers given");
3297 } else if (type_specifiers & SPECIFIER_LONG) {
3298 type_specifiers |= SPECIFIER_LONG_LONG;
3300 type_specifiers |= SPECIFIER_LONG;
3305 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3307 type->compound.declaration = parse_compound_type_specifier(true);
3308 finish_struct_type(&type->compound);
3312 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3313 type->compound.declaration = parse_compound_type_specifier(false);
3314 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3315 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3317 finish_union_type(&type->compound);
3320 type = parse_enum_specifier();
3323 type = parse_typeof();
3325 case T___builtin_va_list:
3326 type = duplicate_type(type_valist);
3330 case T_IDENTIFIER: {
3331 /* only parse identifier if we haven't found a type yet */
3332 if (type != NULL || type_specifiers != 0) {
3333 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3334 * declaration, so it doesn't generate errors about expecting '(' or
3336 switch (look_ahead(1)->type) {
3343 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3346 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3351 goto finish_specifiers;
3355 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3356 if (typedef_type == NULL) {
3357 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3358 * declaration, so it doesn't generate 'implicit int' followed by more
3359 * errors later on. */
3360 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3365 errorf(HERE, "%K does not name a type", &token);
3367 declaration_t *const decl =
3368 create_error_declaration(token.v.symbol, STORAGE_CLASS_TYPEDEF);
3370 type = allocate_type_zero(TYPE_TYPEDEF, HERE);
3371 type->typedeft.declaration = decl;
3375 if (la1_type == '*')
3376 goto finish_specifiers;
3381 goto finish_specifiers;
3386 type = typedef_type;
3390 /* function specifier */
3392 goto finish_specifiers;
3397 if (type == NULL || (saw_error && type_specifiers != 0)) {
3398 atomic_type_kind_t atomic_type;
3400 /* match valid basic types */
3401 switch(type_specifiers) {
3402 case SPECIFIER_VOID:
3403 atomic_type = ATOMIC_TYPE_VOID;
3405 case SPECIFIER_CHAR:
3406 atomic_type = ATOMIC_TYPE_CHAR;
3408 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3409 atomic_type = ATOMIC_TYPE_SCHAR;
3411 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3412 atomic_type = ATOMIC_TYPE_UCHAR;
3414 case SPECIFIER_SHORT:
3415 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3416 case SPECIFIER_SHORT | SPECIFIER_INT:
3417 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3418 atomic_type = ATOMIC_TYPE_SHORT;
3420 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3421 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3422 atomic_type = ATOMIC_TYPE_USHORT;
3425 case SPECIFIER_SIGNED:
3426 case SPECIFIER_SIGNED | SPECIFIER_INT:
3427 atomic_type = ATOMIC_TYPE_INT;
3429 case SPECIFIER_UNSIGNED:
3430 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3431 atomic_type = ATOMIC_TYPE_UINT;
3433 case SPECIFIER_LONG:
3434 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3435 case SPECIFIER_LONG | SPECIFIER_INT:
3436 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3437 atomic_type = ATOMIC_TYPE_LONG;
3439 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3440 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3441 atomic_type = ATOMIC_TYPE_ULONG;
3444 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3445 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3446 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3447 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3449 atomic_type = ATOMIC_TYPE_LONGLONG;
3450 goto warn_about_long_long;
3452 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3453 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3455 atomic_type = ATOMIC_TYPE_ULONGLONG;
3456 warn_about_long_long:
3457 if (warning.long_long) {
3458 warningf(&specifiers->source_position,
3459 "ISO C90 does not support 'long long'");
3463 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3464 atomic_type = unsigned_int8_type_kind;
3467 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3468 atomic_type = unsigned_int16_type_kind;
3471 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3472 atomic_type = unsigned_int32_type_kind;
3475 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3476 atomic_type = unsigned_int64_type_kind;
3479 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3480 atomic_type = unsigned_int128_type_kind;
3483 case SPECIFIER_INT8:
3484 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3485 atomic_type = int8_type_kind;
3488 case SPECIFIER_INT16:
3489 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3490 atomic_type = int16_type_kind;
3493 case SPECIFIER_INT32:
3494 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3495 atomic_type = int32_type_kind;
3498 case SPECIFIER_INT64:
3499 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3500 atomic_type = int64_type_kind;
3503 case SPECIFIER_INT128:
3504 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3505 atomic_type = int128_type_kind;
3508 case SPECIFIER_FLOAT:
3509 atomic_type = ATOMIC_TYPE_FLOAT;
3511 case SPECIFIER_DOUBLE:
3512 atomic_type = ATOMIC_TYPE_DOUBLE;
3514 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3515 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3517 case SPECIFIER_BOOL:
3518 atomic_type = ATOMIC_TYPE_BOOL;
3520 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3521 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3522 atomic_type = ATOMIC_TYPE_FLOAT;
3524 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3525 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3526 atomic_type = ATOMIC_TYPE_DOUBLE;
3528 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3529 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3530 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3533 /* invalid specifier combination, give an error message */
3534 if (type_specifiers == 0) {
3536 specifiers->type = type_error_type;
3541 if (warning.implicit_int) {
3542 warningf(HERE, "no type specifiers in declaration, using 'int'");
3544 atomic_type = ATOMIC_TYPE_INT;
3547 errorf(HERE, "no type specifiers given in declaration");
3549 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3550 (type_specifiers & SPECIFIER_UNSIGNED)) {
3551 errorf(HERE, "signed and unsigned specifiers given");
3552 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3553 errorf(HERE, "only integer types can be signed or unsigned");
3555 errorf(HERE, "multiple datatypes in declaration");
3557 atomic_type = ATOMIC_TYPE_INVALID;
3560 if (type_specifiers & SPECIFIER_COMPLEX &&
3561 atomic_type != ATOMIC_TYPE_INVALID) {
3562 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3563 type->complex.akind = atomic_type;
3564 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3565 atomic_type != ATOMIC_TYPE_INVALID) {
3566 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3567 type->imaginary.akind = atomic_type;
3569 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3570 type->atomic.akind = atomic_type;
3573 } else if (type_specifiers != 0) {
3574 errorf(HERE, "multiple datatypes in declaration");
3577 /* FIXME: check type qualifiers here */
3579 type->base.qualifiers = qualifiers;
3580 type->base.modifiers = modifiers;
3582 type_t *result = typehash_insert(type);
3583 if (newtype && result != type) {
3587 specifiers->type = result;
3592 static type_qualifiers_t parse_type_qualifiers(void)
3594 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3597 switch(token.type) {
3598 /* type qualifiers */
3599 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3600 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3601 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3602 /* microsoft extended type modifiers */
3603 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3604 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3605 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3606 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3607 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3615 static declaration_t *parse_identifier_list(void)
3617 declaration_t *declarations = NULL;
3618 declaration_t *last_declaration = NULL;
3620 declaration_t *const declaration = allocate_declaration_zero();
3621 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3622 declaration->source_position = token.source_position;
3623 declaration->symbol = token.v.symbol;
3626 if (last_declaration != NULL) {
3627 last_declaration->next = declaration;
3629 declarations = declaration;
3631 last_declaration = declaration;
3633 if (token.type != ',') {
3637 } while (token.type == T_IDENTIFIER);
3639 return declarations;
3642 static type_t *automatic_type_conversion(type_t *orig_type);
3644 static void semantic_parameter(declaration_t *declaration)
3646 /* TODO: improve error messages */
3647 source_position_t const* const pos = &declaration->source_position;
3649 switch (declaration->declared_storage_class) {
3650 case STORAGE_CLASS_TYPEDEF:
3651 errorf(pos, "typedef not allowed in parameter list");
3654 /* Allowed storage classes */
3655 case STORAGE_CLASS_NONE:
3656 case STORAGE_CLASS_REGISTER:
3660 errorf(pos, "parameter may only have none or register storage class");
3664 type_t *const orig_type = declaration->type;
3665 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3666 * sugar. Turn it into a pointer.
3667 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3668 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3670 type_t *const type = automatic_type_conversion(orig_type);
3671 declaration->type = type;
3673 if (is_type_incomplete(skip_typeref(type))) {
3674 errorf(pos, "parameter '%#T' is of incomplete type",
3675 orig_type, declaration->symbol);
3679 static declaration_t *parse_parameter(void)
3681 declaration_specifiers_t specifiers;
3682 memset(&specifiers, 0, sizeof(specifiers));
3684 parse_declaration_specifiers(&specifiers);
3686 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3691 static declaration_t *parse_parameters(function_type_t *type)
3693 declaration_t *declarations = NULL;
3696 add_anchor_token(')');
3697 int saved_comma_state = save_and_reset_anchor_state(',');
3699 if (token.type == T_IDENTIFIER &&
3700 !is_typedef_symbol(token.v.symbol)) {
3701 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3702 if (la1_type == ',' || la1_type == ')') {
3703 type->kr_style_parameters = true;
3704 declarations = parse_identifier_list();
3705 goto parameters_finished;
3709 if (token.type == ')') {
3710 type->unspecified_parameters = 1;
3711 goto parameters_finished;
3714 declaration_t *declaration;
3715 declaration_t *last_declaration = NULL;
3716 function_parameter_t *parameter;
3717 function_parameter_t *last_parameter = NULL;
3720 switch(token.type) {
3724 goto parameters_finished;
3727 case T___extension__:
3729 declaration = parse_parameter();
3731 /* func(void) is not a parameter */
3732 if (last_parameter == NULL
3733 && token.type == ')'
3734 && declaration->symbol == NULL
3735 && skip_typeref(declaration->type) == type_void) {
3736 goto parameters_finished;
3738 semantic_parameter(declaration);
3740 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3741 memset(parameter, 0, sizeof(parameter[0]));
3742 parameter->type = declaration->type;
3744 if (last_parameter != NULL) {
3745 last_declaration->next = declaration;
3746 last_parameter->next = parameter;
3748 type->parameters = parameter;
3749 declarations = declaration;
3751 last_parameter = parameter;
3752 last_declaration = declaration;
3756 goto parameters_finished;
3758 if (token.type != ',') {
3759 goto parameters_finished;
3765 parameters_finished:
3766 rem_anchor_token(')');
3769 restore_anchor_state(',', saved_comma_state);
3770 return declarations;
3773 restore_anchor_state(',', saved_comma_state);
3777 typedef enum construct_type_kind_t {
3782 } construct_type_kind_t;
3784 typedef struct construct_type_t construct_type_t;
3785 struct construct_type_t {
3786 construct_type_kind_t kind;
3787 construct_type_t *next;
3790 typedef struct parsed_pointer_t parsed_pointer_t;
3791 struct parsed_pointer_t {
3792 construct_type_t construct_type;
3793 type_qualifiers_t type_qualifiers;
3796 typedef struct construct_function_type_t construct_function_type_t;
3797 struct construct_function_type_t {
3798 construct_type_t construct_type;
3799 type_t *function_type;
3802 typedef struct parsed_array_t parsed_array_t;
3803 struct parsed_array_t {
3804 construct_type_t construct_type;
3805 type_qualifiers_t type_qualifiers;
3811 typedef struct construct_base_type_t construct_base_type_t;
3812 struct construct_base_type_t {
3813 construct_type_t construct_type;
3817 static construct_type_t *parse_pointer_declarator(void)
3821 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3822 memset(pointer, 0, sizeof(pointer[0]));
3823 pointer->construct_type.kind = CONSTRUCT_POINTER;
3824 pointer->type_qualifiers = parse_type_qualifiers();
3826 return (construct_type_t*) pointer;
3829 static construct_type_t *parse_array_declarator(void)
3832 add_anchor_token(']');
3834 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3835 memset(array, 0, sizeof(array[0]));
3836 array->construct_type.kind = CONSTRUCT_ARRAY;
3838 if (token.type == T_static) {
3839 array->is_static = true;
3843 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3844 if (type_qualifiers != 0) {
3845 if (token.type == T_static) {
3846 array->is_static = true;
3850 array->type_qualifiers = type_qualifiers;
3852 if (token.type == '*' && look_ahead(1)->type == ']') {
3853 array->is_variable = true;
3855 } else if (token.type != ']') {
3856 array->size = parse_assignment_expression();
3859 rem_anchor_token(']');
3862 return (construct_type_t*) array;
3867 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3870 if (declaration != NULL) {
3871 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3873 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3875 if (mask & (mask-1)) {
3876 const char *first = NULL, *second = NULL;
3878 /* more than one calling convention set */
3879 if (declaration->modifiers & DM_CDECL) {
3880 if (first == NULL) first = "cdecl";
3881 else if (second == NULL) second = "cdecl";
3883 if (declaration->modifiers & DM_STDCALL) {
3884 if (first == NULL) first = "stdcall";
3885 else if (second == NULL) second = "stdcall";
3887 if (declaration->modifiers & DM_FASTCALL) {
3888 if (first == NULL) first = "fastcall";
3889 else if (second == NULL) second = "fastcall";
3891 if (declaration->modifiers & DM_THISCALL) {
3892 if (first == NULL) first = "thiscall";
3893 else if (second == NULL) second = "thiscall";
3895 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3898 if (declaration->modifiers & DM_CDECL)
3899 type->function.calling_convention = CC_CDECL;
3900 else if (declaration->modifiers & DM_STDCALL)
3901 type->function.calling_convention = CC_STDCALL;
3902 else if (declaration->modifiers & DM_FASTCALL)
3903 type->function.calling_convention = CC_FASTCALL;
3904 else if (declaration->modifiers & DM_THISCALL)
3905 type->function.calling_convention = CC_THISCALL;
3907 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3910 declaration_t *parameters = parse_parameters(&type->function);
3911 if (declaration != NULL) {
3912 declaration->scope.declarations = parameters;
3915 construct_function_type_t *construct_function_type =
3916 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3917 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3918 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3919 construct_function_type->function_type = type;
3921 return &construct_function_type->construct_type;
3924 static void fix_declaration_type(declaration_t *declaration)
3926 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3927 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3929 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3930 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3932 if (declaration->type->base.modifiers == type_modifiers)
3935 type_t *copy = duplicate_type(declaration->type);
3936 copy->base.modifiers = type_modifiers;
3938 type_t *result = typehash_insert(copy);
3939 if (result != copy) {
3940 obstack_free(type_obst, copy);
3943 declaration->type = result;
3946 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3947 bool may_be_abstract)
3949 /* construct a single linked list of construct_type_t's which describe
3950 * how to construct the final declarator type */
3951 construct_type_t *first = NULL;
3952 construct_type_t *last = NULL;
3953 gnu_attribute_t *attributes = NULL;
3955 decl_modifiers_t modifiers = parse_attributes(&attributes);
3958 while (token.type == '*') {
3959 construct_type_t *type = parse_pointer_declarator();
3969 /* TODO: find out if this is correct */
3970 modifiers |= parse_attributes(&attributes);
3973 if (declaration != NULL)
3974 declaration->modifiers |= modifiers;
3976 construct_type_t *inner_types = NULL;
3978 switch(token.type) {
3980 if (declaration == NULL) {
3981 errorf(HERE, "no identifier expected in typename");
3983 declaration->symbol = token.v.symbol;
3984 declaration->source_position = token.source_position;
3990 add_anchor_token(')');
3991 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3992 /* All later declarators only modify the return type, not declaration */
3994 rem_anchor_token(')');
3998 if (may_be_abstract)
4000 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4001 /* avoid a loop in the outermost scope, because eat_statement doesn't
4003 if (token.type == '}' && current_function == NULL) {
4011 construct_type_t *p = last;
4014 construct_type_t *type;
4015 switch(token.type) {
4017 type = parse_function_declarator(declaration);
4020 type = parse_array_declarator();
4023 goto declarator_finished;
4026 /* insert in the middle of the list (behind p) */
4028 type->next = p->next;
4039 declarator_finished:
4040 /* append inner_types at the end of the list, we don't to set last anymore
4041 * as it's not needed anymore */
4043 assert(first == NULL);
4044 first = inner_types;
4046 last->next = inner_types;
4054 static void parse_declaration_attributes(declaration_t *declaration)
4056 gnu_attribute_t *attributes = NULL;
4057 decl_modifiers_t modifiers = parse_attributes(&attributes);
4059 if (declaration == NULL)
4062 declaration->modifiers |= modifiers;
4063 /* check if we have these stupid mode attributes... */
4064 type_t *old_type = declaration->type;
4065 if (old_type == NULL)
4068 gnu_attribute_t *attribute = attributes;
4069 for ( ; attribute != NULL; attribute = attribute->next) {
4070 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4073 atomic_type_kind_t akind = attribute->u.akind;
4074 if (!is_type_signed(old_type)) {
4076 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4077 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4078 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4079 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4081 panic("invalid akind in mode attribute");
4085 = make_atomic_type(akind, old_type->base.qualifiers);
4089 static type_t *construct_declarator_type(construct_type_t *construct_list,
4092 construct_type_t *iter = construct_list;
4093 for( ; iter != NULL; iter = iter->next) {
4094 switch(iter->kind) {
4095 case CONSTRUCT_INVALID:
4096 internal_errorf(HERE, "invalid type construction found");
4097 case CONSTRUCT_FUNCTION: {
4098 construct_function_type_t *construct_function_type
4099 = (construct_function_type_t*) iter;
4101 type_t *function_type = construct_function_type->function_type;
4103 function_type->function.return_type = type;
4105 type_t *skipped_return_type = skip_typeref(type);
4106 if (is_type_function(skipped_return_type)) {
4107 errorf(HERE, "function returning function is not allowed");
4108 type = type_error_type;
4109 } else if (is_type_array(skipped_return_type)) {
4110 errorf(HERE, "function returning array is not allowed");
4111 type = type_error_type;
4113 type = function_type;
4118 case CONSTRUCT_POINTER: {
4119 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4120 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
4121 pointer_type->pointer.points_to = type;
4122 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
4124 type = pointer_type;
4128 case CONSTRUCT_ARRAY: {
4129 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4130 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
4132 expression_t *size_expression = parsed_array->size;
4133 if (size_expression != NULL) {
4135 = create_implicit_cast(size_expression, type_size_t);
4138 array_type->base.qualifiers = parsed_array->type_qualifiers;
4139 array_type->array.element_type = type;
4140 array_type->array.is_static = parsed_array->is_static;
4141 array_type->array.is_variable = parsed_array->is_variable;
4142 array_type->array.size_expression = size_expression;
4144 if (size_expression != NULL) {
4145 if (is_constant_expression(size_expression)) {
4146 array_type->array.size_constant = true;
4147 array_type->array.size
4148 = fold_constant(size_expression);
4150 array_type->array.is_vla = true;
4154 type_t *skipped_type = skip_typeref(type);
4155 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
4156 errorf(HERE, "array of void is not allowed");
4157 type = type_error_type;
4165 type_t *hashed_type = typehash_insert(type);
4166 if (hashed_type != type) {
4167 /* the function type was constructed earlier freeing it here will
4168 * destroy other types... */
4169 if (iter->kind != CONSTRUCT_FUNCTION) {
4179 static declaration_t *parse_declarator(
4180 const declaration_specifiers_t *specifiers, bool may_be_abstract)
4182 declaration_t *const declaration = allocate_declaration_zero();
4183 declaration->source_position = specifiers->source_position;
4184 declaration->declared_storage_class = specifiers->declared_storage_class;
4185 declaration->modifiers = specifiers->modifiers;
4186 declaration->deprecated_string = specifiers->deprecated_string;
4187 declaration->get_property_sym = specifiers->get_property_sym;
4188 declaration->put_property_sym = specifiers->put_property_sym;
4189 declaration->is_inline = specifiers->is_inline;
4191 declaration->storage_class = specifiers->declared_storage_class;
4192 if (declaration->storage_class == STORAGE_CLASS_NONE
4193 && scope != global_scope) {
4194 declaration->storage_class = STORAGE_CLASS_AUTO;
4197 if (specifiers->alignment != 0) {
4198 /* TODO: add checks here */
4199 declaration->alignment = specifiers->alignment;
4202 construct_type_t *construct_type
4203 = parse_inner_declarator(declaration, may_be_abstract);
4204 type_t *const type = specifiers->type;
4205 declaration->type = construct_declarator_type(construct_type, type);
4207 parse_declaration_attributes(declaration);
4209 fix_declaration_type(declaration);
4211 if (construct_type != NULL) {
4212 obstack_free(&temp_obst, construct_type);
4218 static type_t *parse_abstract_declarator(type_t *base_type)
4220 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4222 type_t *result = construct_declarator_type(construct_type, base_type);
4223 if (construct_type != NULL) {
4224 obstack_free(&temp_obst, construct_type);
4230 static declaration_t *append_declaration(declaration_t* const declaration)
4232 if (last_declaration != NULL) {
4233 last_declaration->next = declaration;
4235 scope->declarations = declaration;
4237 last_declaration = declaration;
4242 * Check if the declaration of main is suspicious. main should be a
4243 * function with external linkage, returning int, taking either zero
4244 * arguments, two, or three arguments of appropriate types, ie.
4246 * int main([ int argc, char **argv [, char **env ] ]).
4248 * @param decl the declaration to check
4249 * @param type the function type of the declaration
4251 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
4253 if (decl->storage_class == STORAGE_CLASS_STATIC) {
4254 warningf(&decl->source_position,
4255 "'main' is normally a non-static function");
4257 if (skip_typeref(func_type->return_type) != type_int) {
4258 warningf(&decl->source_position,
4259 "return type of 'main' should be 'int', but is '%T'",
4260 func_type->return_type);
4262 const function_parameter_t *parm = func_type->parameters;
4264 type_t *const first_type = parm->type;
4265 if (!types_compatible(skip_typeref(first_type), type_int)) {
4266 warningf(&decl->source_position,
4267 "first argument of 'main' should be 'int', but is '%T'", first_type);
4271 type_t *const second_type = parm->type;
4272 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4273 warningf(&decl->source_position,
4274 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4278 type_t *const third_type = parm->type;
4279 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4280 warningf(&decl->source_position,
4281 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4285 goto warn_arg_count;
4289 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4295 * Check if a symbol is the equal to "main".
4297 static bool is_sym_main(const symbol_t *const sym)
4299 return strcmp(sym->string, "main") == 0;
4302 static declaration_t *record_declaration(
4303 declaration_t *const declaration,
4304 const bool is_definition)
4306 const symbol_t *const symbol = declaration->symbol;
4307 const namespace_t namespc = (namespace_t)declaration->namespc;
4309 assert(symbol != NULL);
4310 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4312 type_t *const orig_type = declaration->type;
4313 type_t *const type = skip_typeref(orig_type);
4314 if (is_type_function(type) &&
4315 type->function.unspecified_parameters &&
4316 warning.strict_prototypes &&
4317 previous_declaration == NULL) {
4318 warningf(&declaration->source_position,
4319 "function declaration '%#T' is not a prototype",
4320 orig_type, declaration->symbol);
4323 if (warning.main && is_type_function(type) && is_sym_main(symbol)) {
4324 check_type_of_main(declaration, &type->function);
4327 if (warning.nested_externs &&
4328 declaration->storage_class == STORAGE_CLASS_EXTERN &&
4329 scope != global_scope) {
4330 warningf(&declaration->source_position,
4331 "nested extern declaration of '%#T'", declaration->type, symbol);
4334 assert(declaration != previous_declaration);
4335 if (previous_declaration != NULL
4336 && previous_declaration->parent_scope == scope) {
4337 /* can happen for K&R style declarations */
4338 if (previous_declaration->type == NULL) {
4339 previous_declaration->type = declaration->type;
4342 const type_t *prev_type = skip_typeref(previous_declaration->type);
4343 if (!types_compatible(type, prev_type)) {
4344 errorf(&declaration->source_position,
4345 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4346 orig_type, symbol, previous_declaration->type, symbol,
4347 &previous_declaration->source_position);
4349 unsigned old_storage_class = previous_declaration->storage_class;
4350 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4351 errorf(&declaration->source_position,
4352 "redeclaration of enum entry '%Y' (declared %P)",
4353 symbol, &previous_declaration->source_position);
4354 return previous_declaration;
4357 if (warning.redundant_decls &&
4359 previous_declaration->storage_class == STORAGE_CLASS_STATIC &&
4360 !(previous_declaration->modifiers & DM_USED) &&
4361 !previous_declaration->used) {
4362 warningf(&previous_declaration->source_position,
4363 "unnecessary static forward declaration for '%#T'",
4364 previous_declaration->type, symbol);
4367 unsigned new_storage_class = declaration->storage_class;
4369 if (is_type_incomplete(prev_type)) {
4370 previous_declaration->type = type;
4374 /* pretend no storage class means extern for function
4375 * declarations (except if the previous declaration is neither
4376 * none nor extern) */
4377 if (is_type_function(type)) {
4378 if (prev_type->function.unspecified_parameters) {
4379 previous_declaration->type = type;
4383 switch (old_storage_class) {
4384 case STORAGE_CLASS_NONE:
4385 old_storage_class = STORAGE_CLASS_EXTERN;
4388 case STORAGE_CLASS_EXTERN:
4389 if (is_definition) {
4390 if (warning.missing_prototypes &&
4391 prev_type->function.unspecified_parameters &&
4392 !is_sym_main(symbol)) {
4393 warningf(&declaration->source_position,
4394 "no previous prototype for '%#T'",
4397 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4398 new_storage_class = STORAGE_CLASS_EXTERN;
4407 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4408 new_storage_class == STORAGE_CLASS_EXTERN) {
4409 warn_redundant_declaration:
4410 if (!is_definition &&
4411 warning.redundant_decls &&
4412 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4413 warningf(&declaration->source_position,
4414 "redundant declaration for '%Y' (declared %P)",
4415 symbol, &previous_declaration->source_position);
4417 } else if (current_function == NULL) {
4418 if (old_storage_class != STORAGE_CLASS_STATIC &&
4419 new_storage_class == STORAGE_CLASS_STATIC) {
4420 errorf(&declaration->source_position,
4421 "static declaration of '%Y' follows non-static declaration (declared %P)",
4422 symbol, &previous_declaration->source_position);
4423 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4424 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4425 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4427 goto warn_redundant_declaration;
4429 } else if (old_storage_class == new_storage_class) {
4430 errorf(&declaration->source_position,
4431 "redeclaration of '%Y' (declared %P)",
4432 symbol, &previous_declaration->source_position);
4434 errorf(&declaration->source_position,
4435 "redeclaration of '%Y' with different linkage (declared %P)",
4436 symbol, &previous_declaration->source_position);
4440 previous_declaration->modifiers |= declaration->modifiers;
4441 previous_declaration->is_inline |= declaration->is_inline;
4442 return previous_declaration;
4443 } else if (is_type_function(type)) {
4444 if (is_definition &&
4445 declaration->storage_class != STORAGE_CLASS_STATIC) {
4446 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4447 warningf(&declaration->source_position,
4448 "no previous prototype for '%#T'", orig_type, symbol);
4449 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4450 warningf(&declaration->source_position,
4451 "no previous declaration for '%#T'", orig_type,
4456 if (warning.missing_declarations &&
4457 scope == global_scope && (
4458 declaration->storage_class == STORAGE_CLASS_NONE ||
4459 declaration->storage_class == STORAGE_CLASS_THREAD
4461 warningf(&declaration->source_position,
4462 "no previous declaration for '%#T'", orig_type, symbol);
4466 assert(declaration->parent_scope == NULL);
4467 assert(scope != NULL);
4469 declaration->parent_scope = scope;
4471 environment_push(declaration);
4472 return append_declaration(declaration);
4475 static void parser_error_multiple_definition(declaration_t *declaration,
4476 const source_position_t *source_position)
4478 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4479 declaration->symbol, &declaration->source_position);
4482 static bool is_declaration_specifier(const token_t *token,
4483 bool only_specifiers_qualifiers)
4485 switch(token->type) {
4490 return is_typedef_symbol(token->v.symbol);
4492 case T___extension__:
4494 return !only_specifiers_qualifiers;
4501 static void parse_init_declarator_rest(declaration_t *declaration)
4505 type_t *orig_type = declaration->type;
4506 type_t *type = skip_typeref(orig_type);
4508 if (declaration->init.initializer != NULL) {
4509 parser_error_multiple_definition(declaration, HERE);
4512 bool must_be_constant = false;
4513 if (declaration->storage_class == STORAGE_CLASS_STATIC
4514 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4515 || declaration->parent_scope == global_scope) {
4516 must_be_constant = true;
4519 if (is_type_function(type)) {
4520 errorf(&declaration->source_position,
4521 "function '%#T' is initialized like a variable",
4522 orig_type, declaration->symbol);
4523 orig_type = type_error_type;
4526 parse_initializer_env_t env;
4527 env.type = orig_type;
4528 env.must_be_constant = must_be_constant;
4529 env.declaration = current_init_decl = declaration;
4531 initializer_t *initializer = parse_initializer(&env);
4532 current_init_decl = NULL;
4534 if (!is_type_function(type)) {
4535 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
4536 * the array type size */
4537 declaration->type = env.type;
4538 declaration->init.initializer = initializer;
4542 /* parse rest of a declaration without any declarator */
4543 static void parse_anonymous_declaration_rest(
4544 const declaration_specifiers_t *specifiers)
4548 declaration_t *const declaration = allocate_declaration_zero();
4549 declaration->type = specifiers->type;
4550 declaration->declared_storage_class = specifiers->declared_storage_class;
4551 declaration->source_position = specifiers->source_position;
4552 declaration->modifiers = specifiers->modifiers;
4554 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4555 warningf(&declaration->source_position,
4556 "useless storage class in empty declaration");
4558 declaration->storage_class = STORAGE_CLASS_NONE;
4560 type_t *type = declaration->type;
4561 switch (type->kind) {
4562 case TYPE_COMPOUND_STRUCT:
4563 case TYPE_COMPOUND_UNION: {
4564 if (type->compound.declaration->symbol == NULL) {
4565 warningf(&declaration->source_position,
4566 "unnamed struct/union that defines no instances");
4575 warningf(&declaration->source_position, "empty declaration");
4579 append_declaration(declaration);
4582 static void parse_declaration_rest(declaration_t *ndeclaration,
4583 const declaration_specifiers_t *specifiers,
4584 parsed_declaration_func finished_declaration)
4586 add_anchor_token(';');
4587 add_anchor_token('=');
4588 add_anchor_token(',');
4590 declaration_t *declaration =
4591 finished_declaration(ndeclaration, token.type == '=');
4593 type_t *orig_type = declaration->type;
4594 type_t *type = skip_typeref(orig_type);
4596 if (type->kind != TYPE_FUNCTION &&
4597 declaration->is_inline &&
4598 is_type_valid(type)) {
4599 warningf(&declaration->source_position,
4600 "variable '%Y' declared 'inline'\n", declaration->symbol);
4603 if (token.type == '=') {
4604 parse_init_declarator_rest(declaration);
4607 if (token.type != ',')
4611 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4616 rem_anchor_token(';');
4617 rem_anchor_token('=');
4618 rem_anchor_token(',');
4621 static declaration_t *finished_kr_declaration(declaration_t *declaration, bool is_definition)
4623 symbol_t *symbol = declaration->symbol;
4624 if (symbol == NULL) {
4625 errorf(HERE, "anonymous declaration not valid as function parameter");
4628 namespace_t namespc = (namespace_t) declaration->namespc;
4629 if (namespc != NAMESPACE_NORMAL) {
4630 return record_declaration(declaration, false);
4633 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4634 if (previous_declaration == NULL ||
4635 previous_declaration->parent_scope != scope) {
4636 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4641 if (is_definition) {
4642 errorf(HERE, "parameter %Y is initialised", declaration->symbol);
4645 if (previous_declaration->type == NULL) {
4646 previous_declaration->type = declaration->type;
4647 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4648 previous_declaration->storage_class = declaration->storage_class;
4649 previous_declaration->parent_scope = scope;
4650 return previous_declaration;
4652 return record_declaration(declaration, false);
4656 static void parse_declaration(parsed_declaration_func finished_declaration)
4658 declaration_specifiers_t specifiers;
4659 memset(&specifiers, 0, sizeof(specifiers));
4660 parse_declaration_specifiers(&specifiers);
4662 if (token.type == ';') {
4663 parse_anonymous_declaration_rest(&specifiers);
4665 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4666 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4670 static type_t *get_default_promoted_type(type_t *orig_type)
4672 type_t *result = orig_type;
4674 type_t *type = skip_typeref(orig_type);
4675 if (is_type_integer(type)) {
4676 result = promote_integer(type);
4677 } else if (type == type_float) {
4678 result = type_double;
4684 static void parse_kr_declaration_list(declaration_t *declaration)
4686 type_t *type = skip_typeref(declaration->type);
4687 if (!is_type_function(type))
4690 if (!type->function.kr_style_parameters)
4693 /* push function parameters */
4694 int top = environment_top();
4695 scope_t *last_scope = scope;
4696 set_scope(&declaration->scope);
4698 declaration_t *parameter = declaration->scope.declarations;
4699 for ( ; parameter != NULL; parameter = parameter->next) {
4700 assert(parameter->parent_scope == NULL);
4701 parameter->parent_scope = scope;
4702 environment_push(parameter);
4705 /* parse declaration list */
4706 while (is_declaration_specifier(&token, false)) {
4707 parse_declaration(finished_kr_declaration);
4710 /* pop function parameters */
4711 assert(scope == &declaration->scope);
4712 set_scope(last_scope);
4713 environment_pop_to(top);
4715 /* update function type */
4716 type_t *new_type = duplicate_type(type);
4718 function_parameter_t *parameters = NULL;
4719 function_parameter_t *last_parameter = NULL;
4721 declaration_t *parameter_declaration = declaration->scope.declarations;
4722 for( ; parameter_declaration != NULL;
4723 parameter_declaration = parameter_declaration->next) {
4724 type_t *parameter_type = parameter_declaration->type;
4725 if (parameter_type == NULL) {
4727 errorf(HERE, "no type specified for function parameter '%Y'",
4728 parameter_declaration->symbol);
4730 if (warning.implicit_int) {
4731 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4732 parameter_declaration->symbol);
4734 parameter_type = type_int;
4735 parameter_declaration->type = parameter_type;
4739 semantic_parameter(parameter_declaration);
4740 parameter_type = parameter_declaration->type;
4743 * we need the default promoted types for the function type
4745 parameter_type = get_default_promoted_type(parameter_type);
4747 function_parameter_t *function_parameter
4748 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4749 memset(function_parameter, 0, sizeof(function_parameter[0]));
4751 function_parameter->type = parameter_type;
4752 if (last_parameter != NULL) {
4753 last_parameter->next = function_parameter;
4755 parameters = function_parameter;
4757 last_parameter = function_parameter;
4760 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4762 new_type->function.parameters = parameters;
4763 new_type->function.unspecified_parameters = true;
4765 type = typehash_insert(new_type);
4766 if (type != new_type) {
4767 obstack_free(type_obst, new_type);
4770 declaration->type = type;
4773 static bool first_err = true;
4776 * When called with first_err set, prints the name of the current function,
4779 static void print_in_function(void)
4783 diagnosticf("%s: In function '%Y':\n",
4784 current_function->source_position.input_name,
4785 current_function->symbol);
4790 * Check if all labels are defined in the current function.
4791 * Check if all labels are used in the current function.
4793 static void check_labels(void)
4795 for (const goto_statement_t *goto_statement = goto_first;
4796 goto_statement != NULL;
4797 goto_statement = goto_statement->next) {
4798 /* skip computed gotos */
4799 if (goto_statement->expression != NULL)
4802 declaration_t *label = goto_statement->label;
4805 if (label->source_position.input_name == NULL) {
4806 print_in_function();
4807 errorf(&goto_statement->base.source_position,
4808 "label '%Y' used but not defined", label->symbol);
4811 goto_first = goto_last = NULL;
4813 if (warning.unused_label) {
4814 for (const label_statement_t *label_statement = label_first;
4815 label_statement != NULL;
4816 label_statement = label_statement->next) {
4817 const declaration_t *label = label_statement->label;
4819 if (! label->used) {
4820 print_in_function();
4821 warningf(&label_statement->base.source_position,
4822 "label '%Y' defined but not used", label->symbol);
4826 label_first = label_last = NULL;
4830 * Check declarations of current_function for unused entities.
4832 static void check_declarations(void)
4834 if (warning.unused_parameter) {
4835 const scope_t *scope = ¤t_function->scope;
4837 if (is_sym_main(current_function->symbol)) {
4838 /* do not issue unused warnings for main */
4841 const declaration_t *parameter = scope->declarations;
4842 for (; parameter != NULL; parameter = parameter->next) {
4843 if (! parameter->used) {
4844 print_in_function();
4845 warningf(¶meter->source_position,
4846 "unused parameter '%Y'", parameter->symbol);
4850 if (warning.unused_variable) {
4854 static int determine_truth(expression_t const* const cond)
4857 !is_constant_expression(cond) ? 0 :
4858 fold_constant(cond) != 0 ? 1 :
4862 static bool noreturn_candidate;
4864 static void check_reachable(statement_t *const stmt)
4866 if (stmt->base.reachable)
4868 if (stmt->kind != STATEMENT_DO_WHILE)
4869 stmt->base.reachable = true;
4871 statement_t *last = stmt;
4873 switch (stmt->kind) {
4874 case STATEMENT_INVALID:
4875 case STATEMENT_EMPTY:
4876 case STATEMENT_DECLARATION:
4878 next = stmt->base.next;
4881 case STATEMENT_COMPOUND:
4882 next = stmt->compound.statements;
4885 case STATEMENT_RETURN:
4886 noreturn_candidate = false;
4889 case STATEMENT_IF: {
4890 if_statement_t const* const ifs = &stmt->ifs;
4891 int const val = determine_truth(ifs->condition);
4894 check_reachable(ifs->true_statement);
4899 if (ifs->false_statement != NULL) {
4900 check_reachable(ifs->false_statement);
4904 next = stmt->base.next;
4908 case STATEMENT_SWITCH: {
4909 switch_statement_t const *const switchs = &stmt->switchs;
4910 expression_t const *const expr = switchs->expression;
4912 if (is_constant_expression(expr)) {
4913 long const val = fold_constant(expr);
4914 case_label_statement_t * defaults = NULL;
4915 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4916 if (i->expression == NULL) {
4921 if (i->first_case <= val && val <= i->last_case) {
4922 check_reachable((statement_t*)i);
4927 if (defaults != NULL) {
4928 check_reachable((statement_t*)defaults);
4932 bool has_default = false;
4933 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4934 if (i->expression == NULL)
4937 check_reachable((statement_t*)i);
4944 next = stmt->base.next;
4948 case STATEMENT_EXPRESSION: {
4949 /* Check for noreturn function call */
4950 expression_t const *const expr = stmt->expression.expression;
4951 if (expr->kind == EXPR_CALL) {
4952 expression_t const *const func = expr->call.function;
4953 if (func->kind == EXPR_REFERENCE) {
4954 declaration_t const *const decl = func->reference.declaration;
4955 if (decl != NULL && decl->modifiers & DM_NORETURN) {
4961 next = stmt->base.next;
4965 case STATEMENT_CONTINUE: {
4966 statement_t *parent = stmt;
4968 parent = parent->base.parent;
4969 if (parent == NULL) /* continue not within loop */
4973 switch (parent->kind) {
4974 case STATEMENT_WHILE: goto continue_while;
4975 case STATEMENT_DO_WHILE: goto continue_do_while;
4976 case STATEMENT_FOR: goto continue_for;
4983 case STATEMENT_BREAK: {
4984 statement_t *parent = stmt;
4986 parent = parent->base.parent;
4987 if (parent == NULL) /* break not within loop/switch */
4990 switch (parent->kind) {
4991 case STATEMENT_SWITCH:
4992 case STATEMENT_WHILE:
4993 case STATEMENT_DO_WHILE:
4996 next = parent->base.next;
4997 goto found_break_parent;
5006 case STATEMENT_GOTO:
5007 if (stmt->gotos.expression) {
5008 statement_t *parent = stmt->base.parent;
5009 if (parent == NULL) /* top level goto */
5013 next = stmt->gotos.label->init.statement;
5014 if (next == NULL) /* missing label */
5019 case STATEMENT_LABEL:
5020 next = stmt->label.statement;
5023 case STATEMENT_CASE_LABEL:
5024 next = stmt->case_label.statement;
5027 case STATEMENT_WHILE: {
5028 while_statement_t const *const whiles = &stmt->whiles;
5029 int const val = determine_truth(whiles->condition);
5032 check_reachable(whiles->body);
5037 next = stmt->base.next;
5041 case STATEMENT_DO_WHILE:
5042 next = stmt->do_while.body;
5045 case STATEMENT_FOR: {
5046 for_statement_t *const fors = &stmt->fors;
5048 if (fors->condition_reachable)
5050 fors->condition_reachable = true;
5052 expression_t const *const cond = fors->condition;
5054 cond == NULL ? 1 : determine_truth(cond);
5057 check_reachable(fors->body);
5062 next = stmt->base.next;
5066 case STATEMENT_MS_TRY: {
5067 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5068 check_reachable(ms_try->try_statement);
5069 next = ms_try->final_statement;
5073 case STATEMENT_LEAVE: {
5074 statement_t *parent = stmt;
5076 parent = parent->base.parent;
5077 if (parent == NULL) /* __leave not within __try */
5080 if (parent->kind == STATEMENT_MS_TRY) {
5082 next = parent->ms_try.final_statement;
5090 while (next == NULL) {
5091 next = last->base.parent;
5093 noreturn_candidate = false;
5095 type_t *const type = current_function->type;
5096 assert(is_type_function(type));
5097 type_t *const ret = skip_typeref(type->function.return_type);
5098 if (warning.return_type &&
5099 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5100 is_type_valid(ret) &&
5101 !is_sym_main(current_function->symbol)) {
5102 warningf(&stmt->base.source_position,
5103 "control reaches end of non-void function");
5108 switch (next->kind) {
5109 case STATEMENT_INVALID:
5110 case STATEMENT_EMPTY:
5111 case STATEMENT_DECLARATION:
5112 case STATEMENT_EXPRESSION:
5114 case STATEMENT_RETURN:
5115 case STATEMENT_CONTINUE:
5116 case STATEMENT_BREAK:
5117 case STATEMENT_GOTO:
5118 case STATEMENT_LEAVE:
5119 panic("invalid control flow in function");
5121 case STATEMENT_COMPOUND:
5123 case STATEMENT_SWITCH:
5124 case STATEMENT_LABEL:
5125 case STATEMENT_CASE_LABEL:
5127 next = next->base.next;
5130 case STATEMENT_WHILE: {
5132 if (next->base.reachable)
5134 next->base.reachable = true;
5136 while_statement_t const *const whiles = &next->whiles;
5137 int const val = determine_truth(whiles->condition);
5140 check_reachable(whiles->body);
5146 next = next->base.next;
5150 case STATEMENT_DO_WHILE: {
5152 if (next->base.reachable)
5154 next->base.reachable = true;
5156 do_while_statement_t const *const dw = &next->do_while;
5157 int const val = determine_truth(dw->condition);
5160 check_reachable(dw->body);
5166 next = next->base.next;
5170 case STATEMENT_FOR: {
5172 for_statement_t *const fors = &next->fors;
5174 fors->step_reachable = true;
5176 if (fors->condition_reachable)
5178 fors->condition_reachable = true;
5180 expression_t const *const cond = fors->condition;
5182 cond == NULL ? 1 : determine_truth(cond);
5185 check_reachable(fors->body);
5191 next = next->base.next;
5195 case STATEMENT_MS_TRY:
5197 next = next->ms_try.final_statement;
5203 next = stmt->base.parent;
5205 warningf(&stmt->base.source_position,
5206 "control reaches end of non-void function");
5210 check_reachable(next);
5213 static void check_unreachable(statement_t const* const stmt)
5215 if (!stmt->base.reachable &&
5216 stmt->kind != STATEMENT_DO_WHILE &&
5217 stmt->kind != STATEMENT_FOR &&
5218 (stmt->kind != STATEMENT_COMPOUND || stmt->compound.statements == NULL)) {
5219 warningf(&stmt->base.source_position, "statement is unreachable");
5222 switch (stmt->kind) {
5223 case STATEMENT_INVALID:
5224 case STATEMENT_EMPTY:
5225 case STATEMENT_RETURN:
5226 case STATEMENT_DECLARATION:
5227 case STATEMENT_EXPRESSION:
5228 case STATEMENT_CONTINUE:
5229 case STATEMENT_BREAK:
5230 case STATEMENT_GOTO:
5232 case STATEMENT_LEAVE:
5235 case STATEMENT_COMPOUND:
5236 if (stmt->compound.statements)
5237 check_unreachable(stmt->compound.statements);
5241 check_unreachable(stmt->ifs.true_statement);
5242 if (stmt->ifs.false_statement != NULL)
5243 check_unreachable(stmt->ifs.false_statement);
5246 case STATEMENT_SWITCH:
5247 check_unreachable(stmt->switchs.body);
5250 case STATEMENT_LABEL:
5251 check_unreachable(stmt->label.statement);
5254 case STATEMENT_CASE_LABEL:
5255 check_unreachable(stmt->case_label.statement);
5258 case STATEMENT_WHILE:
5259 check_unreachable(stmt->whiles.body);
5262 case STATEMENT_DO_WHILE:
5263 check_unreachable(stmt->do_while.body);
5264 if (!stmt->base.reachable) {
5265 expression_t const *const cond = stmt->do_while.condition;
5266 if (determine_truth(cond) >= 0) {
5267 warningf(&cond->base.source_position,
5268 "condition of do-while-loop is unreachable");
5273 case STATEMENT_FOR: {
5274 for_statement_t const* const fors = &stmt->fors;
5276 // if init and step are unreachable, cond is unreachable, too
5277 if (!stmt->base.reachable && !fors->step_reachable) {
5278 warningf(&stmt->base.source_position, "statement is unreachable");
5280 if (!stmt->base.reachable && fors->initialisation != NULL) {
5281 warningf(&fors->initialisation->base.source_position,
5282 "initialisation of for-statement is unreachable");
5285 if (!fors->condition_reachable && fors->condition != NULL) {
5286 warningf(&fors->condition->base.source_position,
5287 "condition of for-statement is unreachable");
5290 if (!fors->step_reachable && fors->step != NULL) {
5291 warningf(&fors->step->base.source_position,
5292 "step of for-statement is unreachable");
5296 check_unreachable(fors->body);
5300 case STATEMENT_MS_TRY: {
5301 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5302 check_unreachable(ms_try->try_statement);
5303 check_unreachable(ms_try->final_statement);
5307 if (stmt->base.next)
5308 check_unreachable(stmt->base.next);
5311 static void parse_external_declaration(void)
5313 /* function-definitions and declarations both start with declaration
5315 declaration_specifiers_t specifiers;
5316 memset(&specifiers, 0, sizeof(specifiers));
5318 add_anchor_token(';');
5319 parse_declaration_specifiers(&specifiers);
5320 rem_anchor_token(';');
5322 /* must be a declaration */
5323 if (token.type == ';') {
5324 parse_anonymous_declaration_rest(&specifiers);
5328 add_anchor_token(',');
5329 add_anchor_token('=');
5330 rem_anchor_token(';');
5332 /* declarator is common to both function-definitions and declarations */
5333 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
5335 rem_anchor_token(',');
5336 rem_anchor_token('=');
5337 rem_anchor_token(';');
5339 /* must be a declaration */
5340 switch (token.type) {
5344 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
5348 /* must be a function definition */
5349 parse_kr_declaration_list(ndeclaration);
5351 if (token.type != '{') {
5352 parse_error_expected("while parsing function definition", '{', NULL);
5353 eat_until_matching_token(';');
5357 type_t *type = ndeclaration->type;
5359 /* note that we don't skip typerefs: the standard doesn't allow them here
5360 * (so we can't use is_type_function here) */
5361 if (type->kind != TYPE_FUNCTION) {
5362 if (is_type_valid(type)) {
5363 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5364 type, ndeclaration->symbol);
5370 if (warning.aggregate_return &&
5371 is_type_compound(skip_typeref(type->function.return_type))) {
5372 warningf(HERE, "function '%Y' returns an aggregate",
5373 ndeclaration->symbol);
5375 if (warning.traditional && !type->function.unspecified_parameters) {
5376 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5377 ndeclaration->symbol);
5379 if (warning.old_style_definition && type->function.unspecified_parameters) {
5380 warningf(HERE, "old-style function definition '%Y'",
5381 ndeclaration->symbol);
5384 /* § 6.7.5.3 (14) a function definition with () means no
5385 * parameters (and not unspecified parameters) */
5386 if (type->function.unspecified_parameters
5387 && type->function.parameters == NULL
5388 && !type->function.kr_style_parameters) {
5389 type_t *duplicate = duplicate_type(type);
5390 duplicate->function.unspecified_parameters = false;
5392 type = typehash_insert(duplicate);
5393 if (type != duplicate) {
5394 obstack_free(type_obst, duplicate);
5396 ndeclaration->type = type;
5399 declaration_t *const declaration = record_declaration(ndeclaration, true);
5400 if (ndeclaration != declaration) {
5401 declaration->scope = ndeclaration->scope;
5403 type = skip_typeref(declaration->type);
5405 /* push function parameters and switch scope */
5406 int top = environment_top();
5407 scope_t *last_scope = scope;
5408 set_scope(&declaration->scope);
5410 declaration_t *parameter = declaration->scope.declarations;
5411 for( ; parameter != NULL; parameter = parameter->next) {
5412 if (parameter->parent_scope == &ndeclaration->scope) {
5413 parameter->parent_scope = scope;
5415 assert(parameter->parent_scope == NULL
5416 || parameter->parent_scope == scope);
5417 parameter->parent_scope = scope;
5418 if (parameter->symbol == NULL) {
5419 errorf(¶meter->source_position, "parameter name omitted");
5422 environment_push(parameter);
5425 if (declaration->init.statement != NULL) {
5426 parser_error_multiple_definition(declaration, HERE);
5429 /* parse function body */
5430 int label_stack_top = label_top();
5431 declaration_t *old_current_function = current_function;
5432 current_function = declaration;
5433 current_parent = NULL;
5435 statement_t *const body = parse_compound_statement(false);
5436 declaration->init.statement = body;
5439 check_declarations();
5440 if (warning.return_type ||
5441 warning.unreachable_code ||
5442 (warning.missing_noreturn && !(declaration->modifiers & DM_NORETURN))) {
5443 noreturn_candidate = true;
5444 check_reachable(body);
5445 if (warning.unreachable_code)
5446 check_unreachable(body);
5447 if (warning.missing_noreturn &&
5448 noreturn_candidate &&
5449 !(declaration->modifiers & DM_NORETURN)) {
5450 warningf(&body->base.source_position,
5451 "function '%#T' is candidate for attribute 'noreturn'",
5452 type, declaration->symbol);
5456 assert(current_parent == NULL);
5457 assert(current_function == declaration);
5458 current_function = old_current_function;
5459 label_pop_to(label_stack_top);
5462 assert(scope == &declaration->scope);
5463 set_scope(last_scope);
5464 environment_pop_to(top);
5467 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5468 source_position_t *source_position)
5470 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
5472 type->bitfield.base_type = base_type;
5473 type->bitfield.size = size;
5478 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
5481 declaration_t *iter = compound_declaration->scope.declarations;
5482 for( ; iter != NULL; iter = iter->next) {
5483 if (iter->namespc != NAMESPACE_NORMAL)
5486 if (iter->symbol == NULL) {
5487 type_t *type = skip_typeref(iter->type);
5488 if (is_type_compound(type)) {
5489 declaration_t *result
5490 = find_compound_entry(type->compound.declaration, symbol);
5497 if (iter->symbol == symbol) {
5505 static void parse_compound_declarators(declaration_t *struct_declaration,
5506 const declaration_specifiers_t *specifiers)
5508 declaration_t *last_declaration = struct_declaration->scope.declarations;
5509 if (last_declaration != NULL) {
5510 while (last_declaration->next != NULL) {
5511 last_declaration = last_declaration->next;
5516 declaration_t *declaration;
5518 if (token.type == ':') {
5519 source_position_t source_position = *HERE;
5522 type_t *base_type = specifiers->type;
5523 expression_t *size = parse_constant_expression();
5525 if (!is_type_integer(skip_typeref(base_type))) {
5526 errorf(HERE, "bitfield base type '%T' is not an integer type",
5530 type_t *type = make_bitfield_type(base_type, size, &source_position);
5532 declaration = allocate_declaration_zero();
5533 declaration->namespc = NAMESPACE_NORMAL;
5534 declaration->declared_storage_class = STORAGE_CLASS_NONE;
5535 declaration->storage_class = STORAGE_CLASS_NONE;
5536 declaration->source_position = source_position;
5537 declaration->modifiers = specifiers->modifiers;
5538 declaration->type = type;
5540 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
5542 type_t *orig_type = declaration->type;
5543 type_t *type = skip_typeref(orig_type);
5545 if (token.type == ':') {
5546 source_position_t source_position = *HERE;
5548 expression_t *size = parse_constant_expression();
5550 if (!is_type_integer(type)) {
5551 errorf(HERE, "bitfield base type '%T' is not an integer type",
5555 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
5556 declaration->type = bitfield_type;
5558 /* TODO we ignore arrays for now... what is missing is a check
5559 * that they're at the end of the struct */
5560 if (is_type_incomplete(type) && !is_type_array(type)) {
5562 "compound member '%Y' has incomplete type '%T'",
5563 declaration->symbol, orig_type);
5564 } else if (is_type_function(type)) {
5565 errorf(HERE, "compound member '%Y' must not have function type '%T'",
5566 declaration->symbol, orig_type);
5571 /* make sure we don't define a symbol multiple times */
5572 symbol_t *symbol = declaration->symbol;
5573 if (symbol != NULL) {
5574 declaration_t *prev_decl
5575 = find_compound_entry(struct_declaration, symbol);
5577 if (prev_decl != NULL) {
5578 assert(prev_decl->symbol == symbol);
5579 errorf(&declaration->source_position,
5580 "multiple declarations of symbol '%Y' (declared %P)",
5581 symbol, &prev_decl->source_position);
5585 /* append declaration */
5586 if (last_declaration != NULL) {
5587 last_declaration->next = declaration;
5589 struct_declaration->scope.declarations = declaration;
5591 last_declaration = declaration;
5593 if (token.type != ',')
5603 static void parse_compound_type_entries(declaration_t *compound_declaration)
5606 add_anchor_token('}');
5608 while (token.type != '}' && token.type != T_EOF) {
5609 declaration_specifiers_t specifiers;
5610 memset(&specifiers, 0, sizeof(specifiers));
5611 parse_declaration_specifiers(&specifiers);
5613 parse_compound_declarators(compound_declaration, &specifiers);
5615 rem_anchor_token('}');
5617 if (token.type == T_EOF) {
5618 errorf(HERE, "EOF while parsing struct");
5623 static type_t *parse_typename(void)
5625 declaration_specifiers_t specifiers;
5626 memset(&specifiers, 0, sizeof(specifiers));
5627 parse_declaration_specifiers(&specifiers);
5628 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
5629 /* TODO: improve error message, user does probably not know what a
5630 * storage class is...
5632 errorf(HERE, "typename may not have a storage class");
5635 type_t *result = parse_abstract_declarator(specifiers.type);
5643 typedef expression_t* (*parse_expression_function) (unsigned precedence);
5644 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
5645 expression_t *left);
5647 typedef struct expression_parser_function_t expression_parser_function_t;
5648 struct expression_parser_function_t {
5649 unsigned precedence;
5650 parse_expression_function parser;
5651 unsigned infix_precedence;
5652 parse_expression_infix_function infix_parser;
5655 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5658 * Prints an error message if an expression was expected but not read
5660 static expression_t *expected_expression_error(void)
5662 /* skip the error message if the error token was read */
5663 if (token.type != T_ERROR) {
5664 errorf(HERE, "expected expression, got token '%K'", &token);
5668 return create_invalid_expression();
5672 * Parse a string constant.
5674 static expression_t *parse_string_const(void)
5677 if (token.type == T_STRING_LITERAL) {
5678 string_t res = token.v.string;
5680 while (token.type == T_STRING_LITERAL) {
5681 res = concat_strings(&res, &token.v.string);
5684 if (token.type != T_WIDE_STRING_LITERAL) {
5685 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
5686 /* note: that we use type_char_ptr here, which is already the
5687 * automatic converted type. revert_automatic_type_conversion
5688 * will construct the array type */
5689 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
5690 cnst->string.value = res;
5694 wres = concat_string_wide_string(&res, &token.v.wide_string);
5696 wres = token.v.wide_string;
5701 switch (token.type) {
5702 case T_WIDE_STRING_LITERAL:
5703 wres = concat_wide_strings(&wres, &token.v.wide_string);
5706 case T_STRING_LITERAL:
5707 wres = concat_wide_string_string(&wres, &token.v.string);
5711 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5712 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5713 cnst->wide_string.value = wres;
5722 * Parse an integer constant.
5724 static expression_t *parse_int_const(void)
5726 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5727 cnst->base.source_position = *HERE;
5728 cnst->base.type = token.datatype;
5729 cnst->conste.v.int_value = token.v.intvalue;
5737 * Parse a character constant.
5739 static expression_t *parse_character_constant(void)
5741 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
5743 cnst->base.source_position = *HERE;
5744 cnst->base.type = token.datatype;
5745 cnst->conste.v.character = token.v.string;
5747 if (cnst->conste.v.character.size != 1) {
5748 if (warning.multichar && (c_mode & _GNUC)) {
5750 warningf(HERE, "multi-character character constant");
5752 errorf(HERE, "more than 1 characters in character constant");
5761 * Parse a wide character constant.
5763 static expression_t *parse_wide_character_constant(void)
5765 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
5767 cnst->base.source_position = *HERE;
5768 cnst->base.type = token.datatype;
5769 cnst->conste.v.wide_character = token.v.wide_string;
5771 if (cnst->conste.v.wide_character.size != 1) {
5772 if (warning.multichar && (c_mode & _GNUC)) {
5774 warningf(HERE, "multi-character character constant");
5776 errorf(HERE, "more than 1 characters in character constant");
5785 * Parse a float constant.
5787 static expression_t *parse_float_const(void)
5789 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5790 cnst->base.type = token.datatype;
5791 cnst->conste.v.float_value = token.v.floatvalue;
5798 static declaration_t *create_implicit_function(symbol_t *symbol,
5799 const source_position_t *source_position)
5801 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5802 ntype->function.return_type = type_int;
5803 ntype->function.unspecified_parameters = true;
5805 type_t *type = typehash_insert(ntype);
5806 if (type != ntype) {
5810 declaration_t *const declaration = allocate_declaration_zero();
5811 declaration->storage_class = STORAGE_CLASS_EXTERN;
5812 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5813 declaration->type = type;
5814 declaration->symbol = symbol;
5815 declaration->source_position = *source_position;
5816 declaration->implicit = true;
5818 bool strict_prototypes_old = warning.strict_prototypes;
5819 warning.strict_prototypes = false;
5820 record_declaration(declaration, false);
5821 warning.strict_prototypes = strict_prototypes_old;
5827 * Creates a return_type (func)(argument_type) function type if not
5830 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5831 type_t *argument_type2)
5833 function_parameter_t *parameter2
5834 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5835 memset(parameter2, 0, sizeof(parameter2[0]));
5836 parameter2->type = argument_type2;
5838 function_parameter_t *parameter1
5839 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5840 memset(parameter1, 0, sizeof(parameter1[0]));
5841 parameter1->type = argument_type1;
5842 parameter1->next = parameter2;
5844 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5845 type->function.return_type = return_type;
5846 type->function.parameters = parameter1;
5848 type_t *result = typehash_insert(type);
5849 if (result != type) {
5857 * Creates a return_type (func)(argument_type) function type if not
5860 * @param return_type the return type
5861 * @param argument_type the argument type
5863 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5865 function_parameter_t *parameter
5866 = obstack_alloc(type_obst, sizeof(parameter[0]));
5867 memset(parameter, 0, sizeof(parameter[0]));
5868 parameter->type = argument_type;
5870 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5871 type->function.return_type = return_type;
5872 type->function.parameters = parameter;
5874 type_t *result = typehash_insert(type);
5875 if (result != type) {
5882 static type_t *make_function_0_type(type_t *return_type)
5884 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5885 type->function.return_type = return_type;
5886 type->function.parameters = NULL;
5888 type_t *result = typehash_insert(type);
5889 if (result != type) {
5897 * Creates a function type for some function like builtins.
5899 * @param symbol the symbol describing the builtin
5901 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5903 switch(symbol->ID) {
5904 case T___builtin_alloca:
5905 return make_function_1_type(type_void_ptr, type_size_t);
5906 case T___builtin_huge_val:
5907 return make_function_0_type(type_double);
5908 case T___builtin_nan:
5909 return make_function_1_type(type_double, type_char_ptr);
5910 case T___builtin_nanf:
5911 return make_function_1_type(type_float, type_char_ptr);
5912 case T___builtin_nand:
5913 return make_function_1_type(type_long_double, type_char_ptr);
5914 case T___builtin_va_end:
5915 return make_function_1_type(type_void, type_valist);
5916 case T___builtin_expect:
5917 return make_function_2_type(type_long, type_long, type_long);
5919 internal_errorf(HERE, "not implemented builtin symbol found");
5924 * Performs automatic type cast as described in § 6.3.2.1.
5926 * @param orig_type the original type
5928 static type_t *automatic_type_conversion(type_t *orig_type)
5930 type_t *type = skip_typeref(orig_type);
5931 if (is_type_array(type)) {
5932 array_type_t *array_type = &type->array;
5933 type_t *element_type = array_type->element_type;
5934 unsigned qualifiers = array_type->base.qualifiers;
5936 return make_pointer_type(element_type, qualifiers);
5939 if (is_type_function(type)) {
5940 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5947 * reverts the automatic casts of array to pointer types and function
5948 * to function-pointer types as defined § 6.3.2.1
5950 type_t *revert_automatic_type_conversion(const expression_t *expression)
5952 switch (expression->kind) {
5953 case EXPR_REFERENCE: return expression->reference.declaration->type;
5956 return get_qualified_type(expression->select.compound_entry->type,
5957 expression->base.type->base.qualifiers);
5959 case EXPR_UNARY_DEREFERENCE: {
5960 const expression_t *const value = expression->unary.value;
5961 type_t *const type = skip_typeref(value->base.type);
5962 assert(is_type_pointer(type));
5963 return type->pointer.points_to;
5966 case EXPR_BUILTIN_SYMBOL:
5967 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5969 case EXPR_ARRAY_ACCESS: {
5970 const expression_t *array_ref = expression->array_access.array_ref;
5971 type_t *type_left = skip_typeref(array_ref->base.type);
5972 if (!is_type_valid(type_left))
5974 assert(is_type_pointer(type_left));
5975 return type_left->pointer.points_to;
5978 case EXPR_STRING_LITERAL: {
5979 size_t size = expression->string.value.size;
5980 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5983 case EXPR_WIDE_STRING_LITERAL: {
5984 size_t size = expression->wide_string.value.size;
5985 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5988 case EXPR_COMPOUND_LITERAL:
5989 return expression->compound_literal.type;
5994 return expression->base.type;
5997 static expression_t *parse_reference(void)
5999 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
6001 reference_expression_t *ref = &expression->reference;
6002 symbol_t *const symbol = token.v.symbol;
6004 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
6006 source_position_t source_position = token.source_position;
6009 if (declaration == NULL) {
6010 if (token.type == '(') {
6011 /* an implicitly declared function */
6013 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6014 } else if (warning.implicit_function_declaration) {
6015 warningf(HERE, "implicit declaration of function '%Y'",
6019 declaration = create_implicit_function(symbol,
6022 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6023 declaration = create_error_declaration(symbol, STORAGE_CLASS_NONE);
6027 type_t *type = declaration->type;
6029 /* we always do the auto-type conversions; the & and sizeof parser contains
6030 * code to revert this! */
6031 type = automatic_type_conversion(type);
6033 ref->declaration = declaration;
6034 ref->base.type = type;
6036 /* this declaration is used */
6037 declaration->used = true;
6039 /* check for deprecated functions */
6040 if (warning.deprecated_declarations &&
6041 declaration->modifiers & DM_DEPRECATED) {
6042 char const *const prefix = is_type_function(declaration->type) ?
6043 "function" : "variable";
6045 if (declaration->deprecated_string != NULL) {
6046 warningf(&source_position,
6047 "%s '%Y' is deprecated (declared %P): \"%s\"", prefix,
6048 declaration->symbol, &declaration->source_position,
6049 declaration->deprecated_string);
6051 warningf(&source_position,
6052 "%s '%Y' is deprecated (declared %P)", prefix,
6053 declaration->symbol, &declaration->source_position);
6056 if (warning.init_self && declaration == current_init_decl) {
6057 current_init_decl = NULL;
6058 warningf(&source_position,
6059 "variable '%#T' is initialized by itself",
6060 declaration->type, declaration->symbol);
6066 static bool semantic_cast(expression_t *cast)
6068 expression_t *expression = cast->unary.value;
6069 type_t *orig_dest_type = cast->base.type;
6070 type_t *orig_type_right = expression->base.type;
6071 type_t const *dst_type = skip_typeref(orig_dest_type);
6072 type_t const *src_type = skip_typeref(orig_type_right);
6073 source_position_t const *pos = &cast->base.source_position;
6075 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6076 if (dst_type == type_void)
6079 /* only integer and pointer can be casted to pointer */
6080 if (is_type_pointer(dst_type) &&
6081 !is_type_pointer(src_type) &&
6082 !is_type_integer(src_type) &&
6083 is_type_valid(src_type)) {
6084 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6088 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6089 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6093 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6094 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6098 if (warning.cast_qual &&
6099 is_type_pointer(src_type) &&
6100 is_type_pointer(dst_type)) {
6101 type_t *src = skip_typeref(src_type->pointer.points_to);
6102 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6103 unsigned missing_qualifiers =
6104 src->base.qualifiers & ~dst->base.qualifiers;
6105 if (missing_qualifiers != 0) {
6107 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6108 missing_qualifiers, orig_type_right);
6114 static expression_t *parse_compound_literal(type_t *type)
6116 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6118 parse_initializer_env_t env;
6120 env.declaration = NULL;
6121 env.must_be_constant = false;
6122 initializer_t *initializer = parse_initializer(&env);
6125 expression->compound_literal.initializer = initializer;
6126 expression->compound_literal.type = type;
6127 expression->base.type = automatic_type_conversion(type);
6133 * Parse a cast expression.
6135 static expression_t *parse_cast(void)
6137 source_position_t source_position = token.source_position;
6139 type_t *type = parse_typename();
6141 /* matching add_anchor_token() is at call site */
6142 rem_anchor_token(')');
6145 if (token.type == '{') {
6146 return parse_compound_literal(type);
6149 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6150 cast->base.source_position = source_position;
6152 expression_t *value = parse_sub_expression(20);
6153 cast->base.type = type;
6154 cast->unary.value = value;
6156 if (! semantic_cast(cast)) {
6157 /* TODO: record the error in the AST. else it is impossible to detect it */
6162 return create_invalid_expression();
6166 * Parse a statement expression.
6168 static expression_t *parse_statement_expression(void)
6170 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6172 statement_t *statement = parse_compound_statement(true);
6173 expression->statement.statement = statement;
6174 expression->base.source_position = statement->base.source_position;
6176 /* find last statement and use its type */
6177 type_t *type = type_void;
6178 const statement_t *stmt = statement->compound.statements;
6180 while (stmt->base.next != NULL)
6181 stmt = stmt->base.next;
6183 if (stmt->kind == STATEMENT_EXPRESSION) {
6184 type = stmt->expression.expression->base.type;
6187 warningf(&expression->base.source_position, "empty statement expression ({})");
6189 expression->base.type = type;
6195 return create_invalid_expression();
6199 * Parse a parenthesized expression.
6201 static expression_t *parse_parenthesized_expression(void)
6204 add_anchor_token(')');
6206 switch(token.type) {
6208 /* gcc extension: a statement expression */
6209 return parse_statement_expression();
6213 return parse_cast();
6215 if (is_typedef_symbol(token.v.symbol)) {
6216 return parse_cast();
6220 expression_t *result = parse_expression();
6221 rem_anchor_token(')');
6226 return create_invalid_expression();
6229 static expression_t *parse_function_keyword(void)
6234 if (current_function == NULL) {
6235 errorf(HERE, "'__func__' used outside of a function");
6238 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6239 expression->base.type = type_char_ptr;
6240 expression->funcname.kind = FUNCNAME_FUNCTION;
6245 static expression_t *parse_pretty_function_keyword(void)
6247 eat(T___PRETTY_FUNCTION__);
6249 if (current_function == NULL) {
6250 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6253 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6254 expression->base.type = type_char_ptr;
6255 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6260 static expression_t *parse_funcsig_keyword(void)
6264 if (current_function == NULL) {
6265 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6268 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6269 expression->base.type = type_char_ptr;
6270 expression->funcname.kind = FUNCNAME_FUNCSIG;
6275 static expression_t *parse_funcdname_keyword(void)
6277 eat(T___FUNCDNAME__);
6279 if (current_function == NULL) {
6280 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6283 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6284 expression->base.type = type_char_ptr;
6285 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6290 static designator_t *parse_designator(void)
6292 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6293 result->source_position = *HERE;
6295 if (token.type != T_IDENTIFIER) {
6296 parse_error_expected("while parsing member designator",
6297 T_IDENTIFIER, NULL);
6300 result->symbol = token.v.symbol;
6303 designator_t *last_designator = result;
6305 if (token.type == '.') {
6307 if (token.type != T_IDENTIFIER) {
6308 parse_error_expected("while parsing member designator",
6309 T_IDENTIFIER, NULL);
6312 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6313 designator->source_position = *HERE;
6314 designator->symbol = token.v.symbol;
6317 last_designator->next = designator;
6318 last_designator = designator;
6321 if (token.type == '[') {
6323 add_anchor_token(']');
6324 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6325 designator->source_position = *HERE;
6326 designator->array_index = parse_expression();
6327 rem_anchor_token(']');
6329 if (designator->array_index == NULL) {
6333 last_designator->next = designator;
6334 last_designator = designator;
6346 * Parse the __builtin_offsetof() expression.
6348 static expression_t *parse_offsetof(void)
6350 eat(T___builtin_offsetof);
6352 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6353 expression->base.type = type_size_t;
6356 add_anchor_token(',');
6357 type_t *type = parse_typename();
6358 rem_anchor_token(',');
6360 add_anchor_token(')');
6361 designator_t *designator = parse_designator();
6362 rem_anchor_token(')');
6365 expression->offsetofe.type = type;
6366 expression->offsetofe.designator = designator;
6369 memset(&path, 0, sizeof(path));
6370 path.top_type = type;
6371 path.path = NEW_ARR_F(type_path_entry_t, 0);
6373 descend_into_subtype(&path);
6375 if (!walk_designator(&path, designator, true)) {
6376 return create_invalid_expression();
6379 DEL_ARR_F(path.path);
6383 return create_invalid_expression();
6387 * Parses a _builtin_va_start() expression.
6389 static expression_t *parse_va_start(void)
6391 eat(T___builtin_va_start);
6393 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6396 add_anchor_token(',');
6397 expression->va_starte.ap = parse_assignment_expression();
6398 rem_anchor_token(',');
6400 expression_t *const expr = parse_assignment_expression();
6401 if (expr->kind == EXPR_REFERENCE) {
6402 declaration_t *const decl = expr->reference.declaration;
6404 return create_invalid_expression();
6405 if (decl->parent_scope == ¤t_function->scope &&
6406 decl->next == NULL) {
6407 expression->va_starte.parameter = decl;
6412 errorf(&expr->base.source_position,
6413 "second argument of 'va_start' must be last parameter of the current function");
6415 return create_invalid_expression();
6419 * Parses a _builtin_va_arg() expression.
6421 static expression_t *parse_va_arg(void)
6423 eat(T___builtin_va_arg);
6425 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6428 expression->va_arge.ap = parse_assignment_expression();
6430 expression->base.type = parse_typename();
6435 return create_invalid_expression();
6438 static expression_t *parse_builtin_symbol(void)
6440 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
6442 symbol_t *symbol = token.v.symbol;
6444 expression->builtin_symbol.symbol = symbol;
6447 type_t *type = get_builtin_symbol_type(symbol);
6448 type = automatic_type_conversion(type);
6450 expression->base.type = type;
6455 * Parses a __builtin_constant() expression.
6457 static expression_t *parse_builtin_constant(void)
6459 eat(T___builtin_constant_p);
6461 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6464 add_anchor_token(')');
6465 expression->builtin_constant.value = parse_assignment_expression();
6466 rem_anchor_token(')');
6468 expression->base.type = type_int;
6472 return create_invalid_expression();
6476 * Parses a __builtin_prefetch() expression.
6478 static expression_t *parse_builtin_prefetch(void)
6480 eat(T___builtin_prefetch);
6482 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
6485 add_anchor_token(')');
6486 expression->builtin_prefetch.adr = parse_assignment_expression();
6487 if (token.type == ',') {
6489 expression->builtin_prefetch.rw = parse_assignment_expression();
6491 if (token.type == ',') {
6493 expression->builtin_prefetch.locality = parse_assignment_expression();
6495 rem_anchor_token(')');
6497 expression->base.type = type_void;
6501 return create_invalid_expression();
6505 * Parses a __builtin_is_*() compare expression.
6507 static expression_t *parse_compare_builtin(void)
6509 expression_t *expression;
6511 switch(token.type) {
6512 case T___builtin_isgreater:
6513 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6515 case T___builtin_isgreaterequal:
6516 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6518 case T___builtin_isless:
6519 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6521 case T___builtin_islessequal:
6522 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6524 case T___builtin_islessgreater:
6525 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6527 case T___builtin_isunordered:
6528 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6531 internal_errorf(HERE, "invalid compare builtin found");
6534 expression->base.source_position = *HERE;
6538 expression->binary.left = parse_assignment_expression();
6540 expression->binary.right = parse_assignment_expression();
6543 type_t *const orig_type_left = expression->binary.left->base.type;
6544 type_t *const orig_type_right = expression->binary.right->base.type;
6546 type_t *const type_left = skip_typeref(orig_type_left);
6547 type_t *const type_right = skip_typeref(orig_type_right);
6548 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6549 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6550 type_error_incompatible("invalid operands in comparison",
6551 &expression->base.source_position, orig_type_left, orig_type_right);
6554 semantic_comparison(&expression->binary);
6559 return create_invalid_expression();
6564 * Parses a __builtin_expect() expression.
6566 static expression_t *parse_builtin_expect(void)
6568 eat(T___builtin_expect);
6570 expression_t *expression
6571 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
6574 expression->binary.left = parse_assignment_expression();
6576 expression->binary.right = parse_constant_expression();
6579 expression->base.type = expression->binary.left->base.type;
6583 return create_invalid_expression();
6588 * Parses a MS assume() expression.
6590 static expression_t *parse_assume(void)
6594 expression_t *expression
6595 = allocate_expression_zero(EXPR_UNARY_ASSUME);
6598 add_anchor_token(')');
6599 expression->unary.value = parse_assignment_expression();
6600 rem_anchor_token(')');
6603 expression->base.type = type_void;
6606 return create_invalid_expression();
6610 * Return the declaration for a given label symbol or create a new one.
6612 * @param symbol the symbol of the label
6614 static declaration_t *get_label(symbol_t *symbol)
6616 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6617 assert(current_function != NULL);
6618 /* if we found a label in the same function, then we already created the
6620 if (candidate != NULL
6621 && candidate->parent_scope == ¤t_function->scope) {
6625 /* otherwise we need to create a new one */
6626 declaration_t *const declaration = allocate_declaration_zero();
6627 declaration->namespc = NAMESPACE_LABEL;
6628 declaration->symbol = symbol;
6630 label_push(declaration);
6636 * Parses a GNU && label address expression.
6638 static expression_t *parse_label_address(void)
6640 source_position_t source_position = token.source_position;
6642 if (token.type != T_IDENTIFIER) {
6643 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6646 symbol_t *symbol = token.v.symbol;
6649 declaration_t *label = get_label(symbol);
6652 label->address_taken = true;
6654 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6655 expression->base.source_position = source_position;
6657 /* label address is threaten as a void pointer */
6658 expression->base.type = type_void_ptr;
6659 expression->label_address.declaration = label;
6662 return create_invalid_expression();
6666 * Parse a microsoft __noop expression.
6668 static expression_t *parse_noop_expression(void)
6670 source_position_t source_position = *HERE;
6673 if (token.type == '(') {
6674 /* parse arguments */
6676 add_anchor_token(')');
6677 add_anchor_token(',');
6679 if (token.type != ')') {
6681 (void)parse_assignment_expression();
6682 if (token.type != ',')
6688 rem_anchor_token(',');
6689 rem_anchor_token(')');
6692 /* the result is a (int)0 */
6693 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6694 cnst->base.source_position = source_position;
6695 cnst->base.type = type_int;
6696 cnst->conste.v.int_value = 0;
6697 cnst->conste.is_ms_noop = true;
6702 return create_invalid_expression();
6706 * Parses a primary expression.
6708 static expression_t *parse_primary_expression(void)
6710 switch (token.type) {
6711 case T_INTEGER: return parse_int_const();
6712 case T_CHARACTER_CONSTANT: return parse_character_constant();
6713 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6714 case T_FLOATINGPOINT: return parse_float_const();
6715 case T_STRING_LITERAL:
6716 case T_WIDE_STRING_LITERAL: return parse_string_const();
6717 case T_IDENTIFIER: return parse_reference();
6718 case T___FUNCTION__:
6719 case T___func__: return parse_function_keyword();
6720 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6721 case T___FUNCSIG__: return parse_funcsig_keyword();
6722 case T___FUNCDNAME__: return parse_funcdname_keyword();
6723 case T___builtin_offsetof: return parse_offsetof();
6724 case T___builtin_va_start: return parse_va_start();
6725 case T___builtin_va_arg: return parse_va_arg();
6726 case T___builtin_expect:
6727 case T___builtin_alloca:
6728 case T___builtin_nan:
6729 case T___builtin_nand:
6730 case T___builtin_nanf:
6731 case T___builtin_huge_val:
6732 case T___builtin_va_end: return parse_builtin_symbol();
6733 case T___builtin_isgreater:
6734 case T___builtin_isgreaterequal:
6735 case T___builtin_isless:
6736 case T___builtin_islessequal:
6737 case T___builtin_islessgreater:
6738 case T___builtin_isunordered: return parse_compare_builtin();
6739 case T___builtin_constant_p: return parse_builtin_constant();
6740 case T___builtin_prefetch: return parse_builtin_prefetch();
6741 case T__assume: return parse_assume();
6744 return parse_label_address();
6747 case '(': return parse_parenthesized_expression();
6748 case T___noop: return parse_noop_expression();
6751 errorf(HERE, "unexpected token %K, expected an expression", &token);
6752 return create_invalid_expression();
6756 * Check if the expression has the character type and issue a warning then.
6758 static void check_for_char_index_type(const expression_t *expression)
6760 type_t *const type = expression->base.type;
6761 const type_t *const base_type = skip_typeref(type);
6763 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
6764 warning.char_subscripts) {
6765 warningf(&expression->base.source_position,
6766 "array subscript has type '%T'", type);
6770 static expression_t *parse_array_expression(unsigned precedence,
6776 add_anchor_token(']');
6778 expression_t *inside = parse_expression();
6780 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6782 array_access_expression_t *array_access = &expression->array_access;
6784 type_t *const orig_type_left = left->base.type;
6785 type_t *const orig_type_inside = inside->base.type;
6787 type_t *const type_left = skip_typeref(orig_type_left);
6788 type_t *const type_inside = skip_typeref(orig_type_inside);
6790 type_t *return_type;
6791 if (is_type_pointer(type_left)) {
6792 return_type = type_left->pointer.points_to;
6793 array_access->array_ref = left;
6794 array_access->index = inside;
6795 check_for_char_index_type(inside);
6796 } else if (is_type_pointer(type_inside)) {
6797 return_type = type_inside->pointer.points_to;
6798 array_access->array_ref = inside;
6799 array_access->index = left;
6800 array_access->flipped = true;
6801 check_for_char_index_type(left);
6803 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6805 "array access on object with non-pointer types '%T', '%T'",
6806 orig_type_left, orig_type_inside);
6808 return_type = type_error_type;
6809 array_access->array_ref = create_invalid_expression();
6812 rem_anchor_token(']');
6813 if (token.type != ']') {
6814 parse_error_expected("Problem while parsing array access", ']', NULL);
6819 return_type = automatic_type_conversion(return_type);
6820 expression->base.type = return_type;
6825 static expression_t *parse_typeprop(expression_kind_t const kind,
6826 source_position_t const pos,
6827 unsigned const precedence)
6829 expression_t *tp_expression = allocate_expression_zero(kind);
6830 tp_expression->base.type = type_size_t;
6831 tp_expression->base.source_position = pos;
6833 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6835 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
6837 add_anchor_token(')');
6838 type_t* const orig_type = parse_typename();
6839 tp_expression->typeprop.type = orig_type;
6841 type_t const* const type = skip_typeref(orig_type);
6842 char const* const wrong_type =
6843 is_type_incomplete(type) ? "incomplete" :
6844 type->kind == TYPE_FUNCTION ? "function designator" :
6845 type->kind == TYPE_BITFIELD ? "bitfield" :
6847 if (wrong_type != NULL) {
6848 errorf(&pos, "operand of %s expression must not be %s type '%T'",
6849 what, wrong_type, type);
6852 rem_anchor_token(')');
6855 expression_t *expression = parse_sub_expression(precedence);
6857 type_t* const orig_type = revert_automatic_type_conversion(expression);
6858 expression->base.type = orig_type;
6860 type_t const* const type = skip_typeref(orig_type);
6861 char const* const wrong_type =
6862 is_type_incomplete(type) ? "incomplete" :
6863 type->kind == TYPE_FUNCTION ? "function designator" :
6864 type->kind == TYPE_BITFIELD ? "bitfield" :
6866 if (wrong_type != NULL) {
6867 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
6870 tp_expression->typeprop.type = expression->base.type;
6871 tp_expression->typeprop.tp_expression = expression;
6874 return tp_expression;
6876 return create_invalid_expression();
6879 static expression_t *parse_sizeof(unsigned precedence)
6881 source_position_t pos = *HERE;
6883 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
6886 static expression_t *parse_alignof(unsigned precedence)
6888 source_position_t pos = *HERE;
6890 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
6893 static expression_t *parse_select_expression(unsigned precedence,
6894 expression_t *compound)
6897 assert(token.type == '.' || token.type == T_MINUSGREATER);
6899 bool is_pointer = (token.type == T_MINUSGREATER);
6902 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6903 select->select.compound = compound;
6905 if (token.type != T_IDENTIFIER) {
6906 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6909 symbol_t *symbol = token.v.symbol;
6912 type_t *const orig_type = compound->base.type;
6913 type_t *const type = skip_typeref(orig_type);
6916 bool saw_error = false;
6917 if (is_type_pointer(type)) {
6920 "request for member '%Y' in something not a struct or union, but '%T'",
6924 type_left = skip_typeref(type->pointer.points_to);
6926 if (is_pointer && is_type_valid(type)) {
6927 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6933 declaration_t *entry;
6934 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
6935 type_left->kind == TYPE_COMPOUND_UNION) {
6936 declaration_t *const declaration = type_left->compound.declaration;
6938 if (!declaration->init.complete) {
6939 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6941 return create_invalid_expression();
6944 entry = find_compound_entry(declaration, symbol);
6945 if (entry == NULL) {
6946 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6947 goto create_error_entry;
6950 if (is_type_valid(type_left) && !saw_error) {
6952 "request for member '%Y' in something not a struct or union, but '%T'",
6956 entry = allocate_declaration_zero();
6957 entry->symbol = symbol;
6960 select->select.compound_entry = entry;
6962 type_t *const res_type =
6963 get_qualified_type(entry->type, type_left->base.qualifiers);
6965 /* we always do the auto-type conversions; the & and sizeof parser contains
6966 * code to revert this! */
6967 select->base.type = automatic_type_conversion(res_type);
6969 type_t *skipped = skip_typeref(res_type);
6970 if (skipped->kind == TYPE_BITFIELD) {
6971 select->base.type = skipped->bitfield.base_type;
6977 static void check_call_argument(const function_parameter_t *parameter,
6978 call_argument_t *argument, unsigned pos)
6980 type_t *expected_type = parameter->type;
6981 type_t *expected_type_skip = skip_typeref(expected_type);
6982 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6983 expression_t *arg_expr = argument->expression;
6984 type_t *arg_type = skip_typeref(arg_expr->base.type);
6986 /* handle transparent union gnu extension */
6987 if (is_type_union(expected_type_skip)
6988 && (expected_type_skip->base.modifiers
6989 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6990 declaration_t *union_decl = expected_type_skip->compound.declaration;
6992 declaration_t *declaration = union_decl->scope.declarations;
6993 type_t *best_type = NULL;
6994 for ( ; declaration != NULL; declaration = declaration->next) {
6995 type_t *decl_type = declaration->type;
6996 error = semantic_assign(decl_type, arg_expr);
6997 if (error == ASSIGN_ERROR_INCOMPATIBLE
6998 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7001 if (error == ASSIGN_SUCCESS) {
7002 best_type = decl_type;
7003 } else if (best_type == NULL) {
7004 best_type = decl_type;
7008 if (best_type != NULL) {
7009 expected_type = best_type;
7013 error = semantic_assign(expected_type, arg_expr);
7014 argument->expression = create_implicit_cast(argument->expression,
7017 if (error != ASSIGN_SUCCESS) {
7018 /* report exact scope in error messages (like "in argument 3") */
7020 snprintf(buf, sizeof(buf), "call argument %u", pos);
7021 report_assign_error(error, expected_type, arg_expr, buf,
7022 &arg_expr->base.source_position);
7023 } else if (warning.traditional | warning.conversion) {
7025 /* passing as integer instead of float or complex */
7026 (is_type_integer(expected_type) &&
7027 (is_type_float(arg_type) || is_type_complex(arg_type))) ||
7028 /* passing as complex instead of integer or float */
7029 (is_type_complex(expected_type) &&
7030 (is_type_integer(arg_type) || is_type_float(arg_type))) ||
7031 /* passing as float instead of integer or complex */
7032 (is_type_float(expected_type) &&
7033 (is_type_integer(arg_type) || is_type_complex(arg_type))) ||
7034 /* passing as float instead of double */
7035 (is_type_float(expected_type) && expected_type != type_double &&
7036 is_type_float(arg_type))) {
7037 warningf(&arg_expr->base.source_position,
7038 "passing call argument %u as '%T' rather than '%T' due to prototype",
7039 pos, expected_type, arg_type);
7041 if (is_type_integer(expected_type) && is_type_integer(arg_type)) {
7042 /* TODO check for size HERE */
7048 * Parse a call expression, ie. expression '( ... )'.
7050 * @param expression the function address
7052 static expression_t *parse_call_expression(unsigned precedence,
7053 expression_t *expression)
7056 expression_t *result = allocate_expression_zero(EXPR_CALL);
7057 result->base.source_position = expression->base.source_position;
7059 call_expression_t *call = &result->call;
7060 call->function = expression;
7062 type_t *const orig_type = expression->base.type;
7063 type_t *const type = skip_typeref(orig_type);
7065 function_type_t *function_type = NULL;
7066 if (is_type_pointer(type)) {
7067 type_t *const to_type = skip_typeref(type->pointer.points_to);
7069 if (is_type_function(to_type)) {
7070 function_type = &to_type->function;
7071 call->base.type = function_type->return_type;
7075 if (function_type == NULL && is_type_valid(type)) {
7076 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7079 /* parse arguments */
7081 add_anchor_token(')');
7082 add_anchor_token(',');
7084 if (token.type != ')') {
7085 call_argument_t *last_argument = NULL;
7088 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7090 argument->expression = parse_assignment_expression();
7091 if (last_argument == NULL) {
7092 call->arguments = argument;
7094 last_argument->next = argument;
7096 last_argument = argument;
7098 if (token.type != ',')
7103 rem_anchor_token(',');
7104 rem_anchor_token(')');
7107 if (function_type == NULL)
7110 function_parameter_t *parameter = function_type->parameters;
7111 call_argument_t *argument = call->arguments;
7112 if (!function_type->unspecified_parameters) {
7113 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7114 parameter = parameter->next, argument = argument->next) {
7115 check_call_argument(parameter, argument, ++pos);
7118 if (parameter != NULL) {
7119 errorf(HERE, "too few arguments to function '%E'", expression);
7120 } else if (argument != NULL && !function_type->variadic) {
7121 errorf(HERE, "too many arguments to function '%E'", expression);
7125 /* do default promotion */
7126 for( ; argument != NULL; argument = argument->next) {
7127 type_t *type = argument->expression->base.type;
7129 type = get_default_promoted_type(type);
7131 argument->expression
7132 = create_implicit_cast(argument->expression, type);
7135 check_format(&result->call);
7137 if (warning.aggregate_return &&
7138 is_type_compound(skip_typeref(function_type->return_type))) {
7139 warningf(&result->base.source_position,
7140 "function call has aggregate value");
7145 return create_invalid_expression();
7148 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7150 static bool same_compound_type(const type_t *type1, const type_t *type2)
7153 is_type_compound(type1) &&
7154 type1->kind == type2->kind &&
7155 type1->compound.declaration == type2->compound.declaration;
7159 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7161 * @param expression the conditional expression
7163 static expression_t *parse_conditional_expression(unsigned precedence,
7164 expression_t *expression)
7166 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7168 conditional_expression_t *conditional = &result->conditional;
7169 conditional->base.source_position = *HERE;
7170 conditional->condition = expression;
7173 add_anchor_token(':');
7176 type_t *const condition_type_orig = expression->base.type;
7177 type_t *const condition_type = skip_typeref(condition_type_orig);
7178 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7179 type_error("expected a scalar type in conditional condition",
7180 &expression->base.source_position, condition_type_orig);
7183 expression_t *true_expression = expression;
7184 bool gnu_cond = false;
7185 if ((c_mode & _GNUC) && token.type == ':') {
7188 true_expression = parse_expression();
7189 rem_anchor_token(':');
7191 expression_t *false_expression = parse_sub_expression(precedence);
7193 type_t *const orig_true_type = true_expression->base.type;
7194 type_t *const orig_false_type = false_expression->base.type;
7195 type_t *const true_type = skip_typeref(orig_true_type);
7196 type_t *const false_type = skip_typeref(orig_false_type);
7199 type_t *result_type;
7200 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7201 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7202 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
7203 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7204 warningf(&conditional->base.source_position,
7205 "ISO C forbids conditional expression with only one void side");
7207 result_type = type_void;
7208 } else if (is_type_arithmetic(true_type)
7209 && is_type_arithmetic(false_type)) {
7210 result_type = semantic_arithmetic(true_type, false_type);
7212 true_expression = create_implicit_cast(true_expression, result_type);
7213 false_expression = create_implicit_cast(false_expression, result_type);
7215 conditional->true_expression = true_expression;
7216 conditional->false_expression = false_expression;
7217 conditional->base.type = result_type;
7218 } else if (same_compound_type(true_type, false_type)) {
7219 /* just take 1 of the 2 types */
7220 result_type = true_type;
7221 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7222 type_t *pointer_type;
7224 expression_t *other_expression;
7225 if (is_type_pointer(true_type) &&
7226 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7227 pointer_type = true_type;
7228 other_type = false_type;
7229 other_expression = false_expression;
7231 pointer_type = false_type;
7232 other_type = true_type;
7233 other_expression = true_expression;
7236 if (is_null_pointer_constant(other_expression)) {
7237 result_type = pointer_type;
7238 } else if (is_type_pointer(other_type)) {
7239 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7240 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7243 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7244 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7246 } else if (types_compatible(get_unqualified_type(to1),
7247 get_unqualified_type(to2))) {
7250 warningf(&conditional->base.source_position,
7251 "pointer types '%T' and '%T' in conditional expression are incompatible",
7252 true_type, false_type);
7256 type_t *const type =
7257 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7258 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7259 } else if (is_type_integer(other_type)) {
7260 warningf(&conditional->base.source_position,
7261 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7262 result_type = pointer_type;
7264 type_error_incompatible("while parsing conditional",
7265 &expression->base.source_position, true_type, false_type);
7266 result_type = type_error_type;
7269 /* TODO: one pointer to void*, other some pointer */
7271 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7272 type_error_incompatible("while parsing conditional",
7273 &conditional->base.source_position, true_type,
7276 result_type = type_error_type;
7279 conditional->true_expression
7280 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7281 conditional->false_expression
7282 = create_implicit_cast(false_expression, result_type);
7283 conditional->base.type = result_type;
7286 return create_invalid_expression();
7290 * Parse an extension expression.
7292 static expression_t *parse_extension(unsigned precedence)
7294 eat(T___extension__);
7296 /* TODO enable extensions */
7297 expression_t *expression = parse_sub_expression(precedence);
7298 /* TODO disable extensions */
7303 * Parse a __builtin_classify_type() expression.
7305 static expression_t *parse_builtin_classify_type(const unsigned precedence)
7307 eat(T___builtin_classify_type);
7309 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7310 result->base.type = type_int;
7313 add_anchor_token(')');
7314 expression_t *expression = parse_sub_expression(precedence);
7315 rem_anchor_token(')');
7317 result->classify_type.type_expression = expression;
7321 return create_invalid_expression();
7324 static bool check_pointer_arithmetic(const source_position_t *source_position,
7325 type_t *pointer_type,
7326 type_t *orig_pointer_type)
7328 type_t *points_to = pointer_type->pointer.points_to;
7329 points_to = skip_typeref(points_to);
7331 if (is_type_incomplete(points_to)) {
7332 if (!(c_mode & _GNUC) || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7333 errorf(source_position,
7334 "arithmetic with pointer to incomplete type '%T' not allowed",
7337 } else if (warning.pointer_arith) {
7338 warningf(source_position,
7339 "pointer of type '%T' used in arithmetic",
7342 } else if (is_type_function(points_to)) {
7343 if (!(c_mode && _GNUC)) {
7344 errorf(source_position,
7345 "arithmetic with pointer to function type '%T' not allowed",
7348 } else if (warning.pointer_arith) {
7349 warningf(source_position,
7350 "pointer to a function '%T' used in arithmetic",
7357 static bool is_lvalue(const expression_t *expression)
7359 switch (expression->kind) {
7360 case EXPR_REFERENCE:
7361 case EXPR_ARRAY_ACCESS:
7363 case EXPR_UNARY_DEREFERENCE:
7371 static void semantic_incdec(unary_expression_t *expression)
7373 type_t *const orig_type = expression->value->base.type;
7374 type_t *const type = skip_typeref(orig_type);
7375 if (is_type_pointer(type)) {
7376 if (!check_pointer_arithmetic(&expression->base.source_position,
7380 } else if (!is_type_real(type) && is_type_valid(type)) {
7381 /* TODO: improve error message */
7382 errorf(&expression->base.source_position,
7383 "operation needs an arithmetic or pointer type");
7386 if (!is_lvalue(expression->value)) {
7387 /* TODO: improve error message */
7388 errorf(&expression->base.source_position, "lvalue required as operand");
7390 expression->base.type = orig_type;
7393 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7395 type_t *const orig_type = expression->value->base.type;
7396 type_t *const type = skip_typeref(orig_type);
7397 if (!is_type_arithmetic(type)) {
7398 if (is_type_valid(type)) {
7399 /* TODO: improve error message */
7400 errorf(&expression->base.source_position,
7401 "operation needs an arithmetic type");
7406 expression->base.type = orig_type;
7409 static void semantic_unexpr_plus(unary_expression_t *expression)
7411 semantic_unexpr_arithmetic(expression);
7412 if (warning.traditional)
7413 warningf(&expression->base.source_position,
7414 "traditional C rejects the unary plus operator");
7417 static void semantic_not(unary_expression_t *expression)
7419 type_t *const orig_type = expression->value->base.type;
7420 type_t *const type = skip_typeref(orig_type);
7421 if (!is_type_scalar(type) && is_type_valid(type)) {
7422 errorf(&expression->base.source_position,
7423 "operand of ! must be of scalar type");
7426 expression->base.type = type_int;
7429 static void semantic_unexpr_integer(unary_expression_t *expression)
7431 type_t *const orig_type = expression->value->base.type;
7432 type_t *const type = skip_typeref(orig_type);
7433 if (!is_type_integer(type)) {
7434 if (is_type_valid(type)) {
7435 errorf(&expression->base.source_position,
7436 "operand of ~ must be of integer type");
7441 expression->base.type = orig_type;
7444 static void semantic_dereference(unary_expression_t *expression)
7446 type_t *const orig_type = expression->value->base.type;
7447 type_t *const type = skip_typeref(orig_type);
7448 if (!is_type_pointer(type)) {
7449 if (is_type_valid(type)) {
7450 errorf(&expression->base.source_position,
7451 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7456 type_t *result_type = type->pointer.points_to;
7457 result_type = automatic_type_conversion(result_type);
7458 expression->base.type = result_type;
7462 * Record that an address is taken (expression represents an lvalue).
7464 * @param expression the expression
7465 * @param may_be_register if true, the expression might be an register
7467 static void set_address_taken(expression_t *expression, bool may_be_register)
7469 if (expression->kind != EXPR_REFERENCE)
7472 declaration_t *const declaration = expression->reference.declaration;
7473 /* happens for parse errors */
7474 if (declaration == NULL)
7477 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
7478 errorf(&expression->base.source_position,
7479 "address of register variable '%Y' requested",
7480 declaration->symbol);
7482 declaration->address_taken = 1;
7487 * Check the semantic of the address taken expression.
7489 static void semantic_take_addr(unary_expression_t *expression)
7491 expression_t *value = expression->value;
7492 value->base.type = revert_automatic_type_conversion(value);
7494 type_t *orig_type = value->base.type;
7495 if (!is_type_valid(orig_type))
7498 set_address_taken(value, false);
7500 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7503 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7504 static expression_t *parse_##unexpression_type(unsigned precedence) \
7506 expression_t *unary_expression \
7507 = allocate_expression_zero(unexpression_type); \
7508 unary_expression->base.source_position = *HERE; \
7510 unary_expression->unary.value = parse_sub_expression(precedence); \
7512 sfunc(&unary_expression->unary); \
7514 return unary_expression; \
7517 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7518 semantic_unexpr_arithmetic)
7519 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7520 semantic_unexpr_plus)
7521 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7523 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7524 semantic_dereference)
7525 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7527 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7528 semantic_unexpr_integer)
7529 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7531 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7534 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7536 static expression_t *parse_##unexpression_type(unsigned precedence, \
7537 expression_t *left) \
7539 (void) precedence; \
7541 expression_t *unary_expression \
7542 = allocate_expression_zero(unexpression_type); \
7543 unary_expression->base.source_position = *HERE; \
7545 unary_expression->unary.value = left; \
7547 sfunc(&unary_expression->unary); \
7549 return unary_expression; \
7552 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7553 EXPR_UNARY_POSTFIX_INCREMENT,
7555 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7556 EXPR_UNARY_POSTFIX_DECREMENT,
7559 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7561 /* TODO: handle complex + imaginary types */
7563 /* § 6.3.1.8 Usual arithmetic conversions */
7564 if (type_left == type_long_double || type_right == type_long_double) {
7565 return type_long_double;
7566 } else if (type_left == type_double || type_right == type_double) {
7568 } else if (type_left == type_float || type_right == type_float) {
7572 type_left = promote_integer(type_left);
7573 type_right = promote_integer(type_right);
7575 if (type_left == type_right)
7578 bool const signed_left = is_type_signed(type_left);
7579 bool const signed_right = is_type_signed(type_right);
7580 int const rank_left = get_rank(type_left);
7581 int const rank_right = get_rank(type_right);
7583 if (signed_left == signed_right)
7584 return rank_left >= rank_right ? type_left : type_right;
7593 u_rank = rank_right;
7594 u_type = type_right;
7596 s_rank = rank_right;
7597 s_type = type_right;
7602 if (u_rank >= s_rank)
7605 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7607 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7608 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7612 case ATOMIC_TYPE_INT: return type_unsigned_int;
7613 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7614 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7616 default: panic("invalid atomic type");
7621 * Check the semantic restrictions for a binary expression.
7623 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7625 expression_t *const left = expression->left;
7626 expression_t *const right = expression->right;
7627 type_t *const orig_type_left = left->base.type;
7628 type_t *const orig_type_right = right->base.type;
7629 type_t *const type_left = skip_typeref(orig_type_left);
7630 type_t *const type_right = skip_typeref(orig_type_right);
7632 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7633 /* TODO: improve error message */
7634 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7635 errorf(&expression->base.source_position,
7636 "operation needs arithmetic types");
7641 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7642 expression->left = create_implicit_cast(left, arithmetic_type);
7643 expression->right = create_implicit_cast(right, arithmetic_type);
7644 expression->base.type = arithmetic_type;
7647 static void warn_div_by_zero(binary_expression_t const *const expression)
7649 if (warning.div_by_zero &&
7650 is_type_integer(expression->base.type) &&
7651 is_constant_expression(expression->right) &&
7652 fold_constant(expression->right) == 0) {
7653 warningf(&expression->base.source_position, "division by zero");
7658 * Check the semantic restrictions for a div/mod expression.
7660 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
7661 semantic_binexpr_arithmetic(expression);
7662 warn_div_by_zero(expression);
7665 static void semantic_shift_op(binary_expression_t *expression)
7667 expression_t *const left = expression->left;
7668 expression_t *const right = expression->right;
7669 type_t *const orig_type_left = left->base.type;
7670 type_t *const orig_type_right = right->base.type;
7671 type_t * type_left = skip_typeref(orig_type_left);
7672 type_t * type_right = skip_typeref(orig_type_right);
7674 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7675 /* TODO: improve error message */
7676 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7677 errorf(&expression->base.source_position,
7678 "operands of shift operation must have integer types");
7683 type_left = promote_integer(type_left);
7684 type_right = promote_integer(type_right);
7686 expression->left = create_implicit_cast(left, type_left);
7687 expression->right = create_implicit_cast(right, type_right);
7688 expression->base.type = type_left;
7691 static void semantic_add(binary_expression_t *expression)
7693 expression_t *const left = expression->left;
7694 expression_t *const right = expression->right;
7695 type_t *const orig_type_left = left->base.type;
7696 type_t *const orig_type_right = right->base.type;
7697 type_t *const type_left = skip_typeref(orig_type_left);
7698 type_t *const type_right = skip_typeref(orig_type_right);
7701 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7702 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7703 expression->left = create_implicit_cast(left, arithmetic_type);
7704 expression->right = create_implicit_cast(right, arithmetic_type);
7705 expression->base.type = arithmetic_type;
7707 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7708 check_pointer_arithmetic(&expression->base.source_position,
7709 type_left, orig_type_left);
7710 expression->base.type = type_left;
7711 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7712 check_pointer_arithmetic(&expression->base.source_position,
7713 type_right, orig_type_right);
7714 expression->base.type = type_right;
7715 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7716 errorf(&expression->base.source_position,
7717 "invalid operands to binary + ('%T', '%T')",
7718 orig_type_left, orig_type_right);
7722 static void semantic_sub(binary_expression_t *expression)
7724 expression_t *const left = expression->left;
7725 expression_t *const right = expression->right;
7726 type_t *const orig_type_left = left->base.type;
7727 type_t *const orig_type_right = right->base.type;
7728 type_t *const type_left = skip_typeref(orig_type_left);
7729 type_t *const type_right = skip_typeref(orig_type_right);
7730 source_position_t const *const pos = &expression->base.source_position;
7733 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7734 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7735 expression->left = create_implicit_cast(left, arithmetic_type);
7736 expression->right = create_implicit_cast(right, arithmetic_type);
7737 expression->base.type = arithmetic_type;
7739 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7740 check_pointer_arithmetic(&expression->base.source_position,
7741 type_left, orig_type_left);
7742 expression->base.type = type_left;
7743 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7744 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7745 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7746 if (!types_compatible(unqual_left, unqual_right)) {
7748 "subtracting pointers to incompatible types '%T' and '%T'",
7749 orig_type_left, orig_type_right);
7750 } else if (!is_type_object(unqual_left)) {
7751 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
7752 warningf(pos, "subtracting pointers to void");
7754 errorf(pos, "subtracting pointers to non-object types '%T'",
7758 expression->base.type = type_ptrdiff_t;
7759 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7760 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7761 orig_type_left, orig_type_right);
7766 * Check the semantics of comparison expressions.
7768 * @param expression The expression to check.
7770 static void semantic_comparison(binary_expression_t *expression)
7772 expression_t *left = expression->left;
7773 expression_t *right = expression->right;
7774 type_t *orig_type_left = left->base.type;
7775 type_t *orig_type_right = right->base.type;
7777 type_t *type_left = skip_typeref(orig_type_left);
7778 type_t *type_right = skip_typeref(orig_type_right);
7780 /* TODO non-arithmetic types */
7781 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7782 /* test for signed vs unsigned compares */
7783 if (warning.sign_compare &&
7784 (expression->base.kind != EXPR_BINARY_EQUAL &&
7785 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
7786 (is_type_signed(type_left) != is_type_signed(type_right))) {
7788 /* check if 1 of the operands is a constant, in this case we just
7789 * check wether we can safely represent the resulting constant in
7790 * the type of the other operand. */
7791 expression_t *const_expr = NULL;
7792 expression_t *other_expr = NULL;
7794 if (is_constant_expression(left)) {
7797 } else if (is_constant_expression(right)) {
7802 if (const_expr != NULL) {
7803 type_t *other_type = skip_typeref(other_expr->base.type);
7804 long val = fold_constant(const_expr);
7805 /* TODO: check if val can be represented by other_type */
7809 warningf(&expression->base.source_position,
7810 "comparison between signed and unsigned");
7812 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7813 expression->left = create_implicit_cast(left, arithmetic_type);
7814 expression->right = create_implicit_cast(right, arithmetic_type);
7815 expression->base.type = arithmetic_type;
7816 if (warning.float_equal &&
7817 (expression->base.kind == EXPR_BINARY_EQUAL ||
7818 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
7819 is_type_float(arithmetic_type)) {
7820 warningf(&expression->base.source_position,
7821 "comparing floating point with == or != is unsafe");
7823 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7824 /* TODO check compatibility */
7825 } else if (is_type_pointer(type_left)) {
7826 expression->right = create_implicit_cast(right, type_left);
7827 } else if (is_type_pointer(type_right)) {
7828 expression->left = create_implicit_cast(left, type_right);
7829 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7830 type_error_incompatible("invalid operands in comparison",
7831 &expression->base.source_position,
7832 type_left, type_right);
7834 expression->base.type = type_int;
7838 * Checks if a compound type has constant fields.
7840 static bool has_const_fields(const compound_type_t *type)
7842 const scope_t *scope = &type->declaration->scope;
7843 const declaration_t *declaration = scope->declarations;
7845 for (; declaration != NULL; declaration = declaration->next) {
7846 if (declaration->namespc != NAMESPACE_NORMAL)
7849 const type_t *decl_type = skip_typeref(declaration->type);
7850 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
7857 static bool is_valid_assignment_lhs(expression_t const* const left)
7859 type_t *const orig_type_left = revert_automatic_type_conversion(left);
7860 type_t *const type_left = skip_typeref(orig_type_left);
7862 if (!is_lvalue(left)) {
7863 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
7868 if (is_type_array(type_left)) {
7869 errorf(HERE, "cannot assign to arrays ('%E')", left);
7872 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
7873 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
7877 if (is_type_incomplete(type_left)) {
7878 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
7879 left, orig_type_left);
7882 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
7883 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
7884 left, orig_type_left);
7891 static void semantic_arithmetic_assign(binary_expression_t *expression)
7893 expression_t *left = expression->left;
7894 expression_t *right = expression->right;
7895 type_t *orig_type_left = left->base.type;
7896 type_t *orig_type_right = right->base.type;
7898 if (!is_valid_assignment_lhs(left))
7901 type_t *type_left = skip_typeref(orig_type_left);
7902 type_t *type_right = skip_typeref(orig_type_right);
7904 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7905 /* TODO: improve error message */
7906 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7907 errorf(&expression->base.source_position,
7908 "operation needs arithmetic types");
7913 /* combined instructions are tricky. We can't create an implicit cast on
7914 * the left side, because we need the uncasted form for the store.
7915 * The ast2firm pass has to know that left_type must be right_type
7916 * for the arithmetic operation and create a cast by itself */
7917 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7918 expression->right = create_implicit_cast(right, arithmetic_type);
7919 expression->base.type = type_left;
7922 static void semantic_divmod_assign(binary_expression_t *expression)
7924 semantic_arithmetic_assign(expression);
7925 warn_div_by_zero(expression);
7928 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
7930 expression_t *const left = expression->left;
7931 expression_t *const right = expression->right;
7932 type_t *const orig_type_left = left->base.type;
7933 type_t *const orig_type_right = right->base.type;
7934 type_t *const type_left = skip_typeref(orig_type_left);
7935 type_t *const type_right = skip_typeref(orig_type_right);
7937 if (!is_valid_assignment_lhs(left))
7940 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7941 /* combined instructions are tricky. We can't create an implicit cast on
7942 * the left side, because we need the uncasted form for the store.
7943 * The ast2firm pass has to know that left_type must be right_type
7944 * for the arithmetic operation and create a cast by itself */
7945 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
7946 expression->right = create_implicit_cast(right, arithmetic_type);
7947 expression->base.type = type_left;
7948 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7949 check_pointer_arithmetic(&expression->base.source_position,
7950 type_left, orig_type_left);
7951 expression->base.type = type_left;
7952 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7953 errorf(&expression->base.source_position,
7954 "incompatible types '%T' and '%T' in assignment",
7955 orig_type_left, orig_type_right);
7960 * Check the semantic restrictions of a logical expression.
7962 static void semantic_logical_op(binary_expression_t *expression)
7964 expression_t *const left = expression->left;
7965 expression_t *const right = expression->right;
7966 type_t *const orig_type_left = left->base.type;
7967 type_t *const orig_type_right = right->base.type;
7968 type_t *const type_left = skip_typeref(orig_type_left);
7969 type_t *const type_right = skip_typeref(orig_type_right);
7971 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
7972 /* TODO: improve error message */
7973 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7974 errorf(&expression->base.source_position,
7975 "operation needs scalar types");
7980 expression->base.type = type_int;
7984 * Check the semantic restrictions of a binary assign expression.
7986 static void semantic_binexpr_assign(binary_expression_t *expression)
7988 expression_t *left = expression->left;
7989 type_t *orig_type_left = left->base.type;
7991 if (!is_valid_assignment_lhs(left))
7994 assign_error_t error = semantic_assign(orig_type_left, expression->right);
7995 report_assign_error(error, orig_type_left, expression->right,
7996 "assignment", &left->base.source_position);
7997 expression->right = create_implicit_cast(expression->right, orig_type_left);
7998 expression->base.type = orig_type_left;
8002 * Determine if the outermost operation (or parts thereof) of the given
8003 * expression has no effect in order to generate a warning about this fact.
8004 * Therefore in some cases this only examines some of the operands of the
8005 * expression (see comments in the function and examples below).
8007 * f() + 23; // warning, because + has no effect
8008 * x || f(); // no warning, because x controls execution of f()
8009 * x ? y : f(); // warning, because y has no effect
8010 * (void)x; // no warning to be able to suppress the warning
8011 * This function can NOT be used for an "expression has definitely no effect"-
8013 static bool expression_has_effect(const expression_t *const expr)
8015 switch (expr->kind) {
8016 case EXPR_UNKNOWN: break;
8017 case EXPR_INVALID: return true; /* do NOT warn */
8018 case EXPR_REFERENCE: return false;
8019 /* suppress the warning for microsoft __noop operations */
8020 case EXPR_CONST: return expr->conste.is_ms_noop;
8021 case EXPR_CHARACTER_CONSTANT: return false;
8022 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8023 case EXPR_STRING_LITERAL: return false;
8024 case EXPR_WIDE_STRING_LITERAL: return false;
8027 const call_expression_t *const call = &expr->call;
8028 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8031 switch (call->function->builtin_symbol.symbol->ID) {
8032 case T___builtin_va_end: return true;
8033 default: return false;
8037 /* Generate the warning if either the left or right hand side of a
8038 * conditional expression has no effect */
8039 case EXPR_CONDITIONAL: {
8040 const conditional_expression_t *const cond = &expr->conditional;
8042 expression_has_effect(cond->true_expression) &&
8043 expression_has_effect(cond->false_expression);
8046 case EXPR_SELECT: return false;
8047 case EXPR_ARRAY_ACCESS: return false;
8048 case EXPR_SIZEOF: return false;
8049 case EXPR_CLASSIFY_TYPE: return false;
8050 case EXPR_ALIGNOF: return false;
8052 case EXPR_FUNCNAME: return false;
8053 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8054 case EXPR_BUILTIN_CONSTANT_P: return false;
8055 case EXPR_BUILTIN_PREFETCH: return true;
8056 case EXPR_OFFSETOF: return false;
8057 case EXPR_VA_START: return true;
8058 case EXPR_VA_ARG: return true;
8059 case EXPR_STATEMENT: return true; // TODO
8060 case EXPR_COMPOUND_LITERAL: return false;
8062 case EXPR_UNARY_NEGATE: return false;
8063 case EXPR_UNARY_PLUS: return false;
8064 case EXPR_UNARY_BITWISE_NEGATE: return false;
8065 case EXPR_UNARY_NOT: return false;
8066 case EXPR_UNARY_DEREFERENCE: return false;
8067 case EXPR_UNARY_TAKE_ADDRESS: return false;
8068 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8069 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8070 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8071 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8073 /* Treat void casts as if they have an effect in order to being able to
8074 * suppress the warning */
8075 case EXPR_UNARY_CAST: {
8076 type_t *const type = skip_typeref(expr->base.type);
8077 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8080 case EXPR_UNARY_CAST_IMPLICIT: return true;
8081 case EXPR_UNARY_ASSUME: return true;
8083 case EXPR_BINARY_ADD: return false;
8084 case EXPR_BINARY_SUB: return false;
8085 case EXPR_BINARY_MUL: return false;
8086 case EXPR_BINARY_DIV: return false;
8087 case EXPR_BINARY_MOD: return false;
8088 case EXPR_BINARY_EQUAL: return false;
8089 case EXPR_BINARY_NOTEQUAL: return false;
8090 case EXPR_BINARY_LESS: return false;
8091 case EXPR_BINARY_LESSEQUAL: return false;
8092 case EXPR_BINARY_GREATER: return false;
8093 case EXPR_BINARY_GREATEREQUAL: return false;
8094 case EXPR_BINARY_BITWISE_AND: return false;
8095 case EXPR_BINARY_BITWISE_OR: return false;
8096 case EXPR_BINARY_BITWISE_XOR: return false;
8097 case EXPR_BINARY_SHIFTLEFT: return false;
8098 case EXPR_BINARY_SHIFTRIGHT: return false;
8099 case EXPR_BINARY_ASSIGN: return true;
8100 case EXPR_BINARY_MUL_ASSIGN: return true;
8101 case EXPR_BINARY_DIV_ASSIGN: return true;
8102 case EXPR_BINARY_MOD_ASSIGN: return true;
8103 case EXPR_BINARY_ADD_ASSIGN: return true;
8104 case EXPR_BINARY_SUB_ASSIGN: return true;
8105 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8106 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8107 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8108 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8109 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8111 /* Only examine the right hand side of && and ||, because the left hand
8112 * side already has the effect of controlling the execution of the right
8114 case EXPR_BINARY_LOGICAL_AND:
8115 case EXPR_BINARY_LOGICAL_OR:
8116 /* Only examine the right hand side of a comma expression, because the left
8117 * hand side has a separate warning */
8118 case EXPR_BINARY_COMMA:
8119 return expression_has_effect(expr->binary.right);
8121 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8122 case EXPR_BINARY_ISGREATER: return false;
8123 case EXPR_BINARY_ISGREATEREQUAL: return false;
8124 case EXPR_BINARY_ISLESS: return false;
8125 case EXPR_BINARY_ISLESSEQUAL: return false;
8126 case EXPR_BINARY_ISLESSGREATER: return false;
8127 case EXPR_BINARY_ISUNORDERED: return false;
8130 internal_errorf(HERE, "unexpected expression");
8133 static void semantic_comma(binary_expression_t *expression)
8135 if (warning.unused_value) {
8136 const expression_t *const left = expression->left;
8137 if (!expression_has_effect(left)) {
8138 warningf(&left->base.source_position,
8139 "left-hand operand of comma expression has no effect");
8142 expression->base.type = expression->right->base.type;
8145 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
8146 static expression_t *parse_##binexpression_type(unsigned precedence, \
8147 expression_t *left) \
8149 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8150 binexpr->base.source_position = *HERE; \
8151 binexpr->binary.left = left; \
8154 expression_t *right = parse_sub_expression(precedence + lr); \
8156 binexpr->binary.right = right; \
8157 sfunc(&binexpr->binary); \
8162 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
8163 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
8164 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_divmod_arithmetic, 1)
8165 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_divmod_arithmetic, 1)
8166 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
8167 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
8168 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
8169 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
8170 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
8172 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
8173 semantic_comparison, 1)
8174 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
8175 semantic_comparison, 1)
8176 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
8177 semantic_comparison, 1)
8178 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
8179 semantic_comparison, 1)
8181 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
8182 semantic_binexpr_arithmetic, 1)
8183 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
8184 semantic_binexpr_arithmetic, 1)
8185 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
8186 semantic_binexpr_arithmetic, 1)
8187 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
8188 semantic_logical_op, 1)
8189 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
8190 semantic_logical_op, 1)
8191 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
8192 semantic_shift_op, 1)
8193 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
8194 semantic_shift_op, 1)
8195 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
8196 semantic_arithmetic_addsubb_assign, 0)
8197 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
8198 semantic_arithmetic_addsubb_assign, 0)
8199 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
8200 semantic_arithmetic_assign, 0)
8201 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
8202 semantic_divmod_assign, 0)
8203 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
8204 semantic_divmod_assign, 0)
8205 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
8206 semantic_arithmetic_assign, 0)
8207 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8208 semantic_arithmetic_assign, 0)
8209 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
8210 semantic_arithmetic_assign, 0)
8211 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
8212 semantic_arithmetic_assign, 0)
8213 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
8214 semantic_arithmetic_assign, 0)
8216 static expression_t *parse_sub_expression(unsigned precedence)
8218 if (token.type < 0) {
8219 return expected_expression_error();
8222 expression_parser_function_t *parser
8223 = &expression_parsers[token.type];
8224 source_position_t source_position = token.source_position;
8227 if (parser->parser != NULL) {
8228 left = parser->parser(parser->precedence);
8230 left = parse_primary_expression();
8232 assert(left != NULL);
8233 left->base.source_position = source_position;
8236 if (token.type < 0) {
8237 return expected_expression_error();
8240 parser = &expression_parsers[token.type];
8241 if (parser->infix_parser == NULL)
8243 if (parser->infix_precedence < precedence)
8246 left = parser->infix_parser(parser->infix_precedence, left);
8248 assert(left != NULL);
8249 assert(left->kind != EXPR_UNKNOWN);
8250 left->base.source_position = source_position;
8257 * Parse an expression.
8259 static expression_t *parse_expression(void)
8261 return parse_sub_expression(1);
8265 * Register a parser for a prefix-like operator with given precedence.
8267 * @param parser the parser function
8268 * @param token_type the token type of the prefix token
8269 * @param precedence the precedence of the operator
8271 static void register_expression_parser(parse_expression_function parser,
8272 int token_type, unsigned precedence)
8274 expression_parser_function_t *entry = &expression_parsers[token_type];
8276 if (entry->parser != NULL) {
8277 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8278 panic("trying to register multiple expression parsers for a token");
8280 entry->parser = parser;
8281 entry->precedence = precedence;
8285 * Register a parser for an infix operator with given precedence.
8287 * @param parser the parser function
8288 * @param token_type the token type of the infix operator
8289 * @param precedence the precedence of the operator
8291 static void register_infix_parser(parse_expression_infix_function parser,
8292 int token_type, unsigned precedence)
8294 expression_parser_function_t *entry = &expression_parsers[token_type];
8296 if (entry->infix_parser != NULL) {
8297 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8298 panic("trying to register multiple infix expression parsers for a "
8301 entry->infix_parser = parser;
8302 entry->infix_precedence = precedence;
8306 * Initialize the expression parsers.
8308 static void init_expression_parsers(void)
8310 memset(&expression_parsers, 0, sizeof(expression_parsers));
8312 register_infix_parser(parse_array_expression, '[', 30);
8313 register_infix_parser(parse_call_expression, '(', 30);
8314 register_infix_parser(parse_select_expression, '.', 30);
8315 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
8316 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
8318 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
8321 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
8322 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
8323 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
8324 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
8325 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
8326 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
8327 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
8328 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
8329 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
8330 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
8331 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
8332 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
8333 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
8334 T_EXCLAMATIONMARKEQUAL, 13);
8335 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
8336 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
8337 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
8338 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
8339 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
8340 register_infix_parser(parse_conditional_expression, '?', 7);
8341 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
8342 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
8343 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
8344 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
8345 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
8346 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
8347 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
8348 T_LESSLESSEQUAL, 2);
8349 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
8350 T_GREATERGREATEREQUAL, 2);
8351 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
8353 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
8355 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
8358 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
8360 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
8361 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
8362 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
8363 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
8364 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
8365 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
8366 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
8368 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
8370 register_expression_parser(parse_sizeof, T_sizeof, 25);
8371 register_expression_parser(parse_alignof, T___alignof__, 25);
8372 register_expression_parser(parse_extension, T___extension__, 25);
8373 register_expression_parser(parse_builtin_classify_type,
8374 T___builtin_classify_type, 25);
8378 * Parse a asm statement arguments specification.
8380 static asm_argument_t *parse_asm_arguments(bool is_out)
8382 asm_argument_t *result = NULL;
8383 asm_argument_t *last = NULL;
8385 while (token.type == T_STRING_LITERAL || token.type == '[') {
8386 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8387 memset(argument, 0, sizeof(argument[0]));
8389 if (token.type == '[') {
8391 if (token.type != T_IDENTIFIER) {
8392 parse_error_expected("while parsing asm argument",
8393 T_IDENTIFIER, NULL);
8396 argument->symbol = token.v.symbol;
8401 argument->constraints = parse_string_literals();
8403 add_anchor_token(')');
8404 expression_t *expression = parse_expression();
8405 rem_anchor_token(')');
8407 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8408 * change size or type representation (e.g. int -> long is ok, but
8409 * int -> float is not) */
8410 if (expression->kind == EXPR_UNARY_CAST) {
8411 type_t *const type = expression->base.type;
8412 type_kind_t const kind = type->kind;
8413 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8416 if (kind == TYPE_ATOMIC) {
8417 atomic_type_kind_t const akind = type->atomic.akind;
8418 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8419 size = get_atomic_type_size(akind);
8421 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8422 size = get_atomic_type_size(get_intptr_kind());
8426 expression_t *const value = expression->unary.value;
8427 type_t *const value_type = value->base.type;
8428 type_kind_t const value_kind = value_type->kind;
8430 unsigned value_flags;
8431 unsigned value_size;
8432 if (value_kind == TYPE_ATOMIC) {
8433 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8434 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8435 value_size = get_atomic_type_size(value_akind);
8436 } else if (value_kind == TYPE_POINTER) {
8437 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8438 value_size = get_atomic_type_size(get_intptr_kind());
8443 if (value_flags != flags || value_size != size)
8447 } while (expression->kind == EXPR_UNARY_CAST);
8451 if (!is_lvalue(expression)) {
8452 errorf(&expression->base.source_position,
8453 "asm output argument is not an lvalue");
8456 argument->expression = expression;
8459 set_address_taken(expression, true);
8462 last->next = argument;
8468 if (token.type != ',')
8479 * Parse a asm statement clobber specification.
8481 static asm_clobber_t *parse_asm_clobbers(void)
8483 asm_clobber_t *result = NULL;
8484 asm_clobber_t *last = NULL;
8486 while(token.type == T_STRING_LITERAL) {
8487 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8488 clobber->clobber = parse_string_literals();
8491 last->next = clobber;
8497 if (token.type != ',')
8506 * Parse an asm statement.
8508 static statement_t *parse_asm_statement(void)
8512 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8513 statement->base.source_position = token.source_position;
8515 asm_statement_t *asm_statement = &statement->asms;
8517 if (token.type == T_volatile) {
8519 asm_statement->is_volatile = true;
8523 add_anchor_token(')');
8524 add_anchor_token(':');
8525 asm_statement->asm_text = parse_string_literals();
8527 if (token.type != ':') {
8528 rem_anchor_token(':');
8533 asm_statement->outputs = parse_asm_arguments(true);
8534 if (token.type != ':') {
8535 rem_anchor_token(':');
8540 asm_statement->inputs = parse_asm_arguments(false);
8541 if (token.type != ':') {
8542 rem_anchor_token(':');
8545 rem_anchor_token(':');
8548 asm_statement->clobbers = parse_asm_clobbers();
8551 rem_anchor_token(')');
8555 if (asm_statement->outputs == NULL) {
8556 /* GCC: An 'asm' instruction without any output operands will be treated
8557 * identically to a volatile 'asm' instruction. */
8558 asm_statement->is_volatile = true;
8563 return create_invalid_statement();
8567 * Parse a case statement.
8569 static statement_t *parse_case_statement(void)
8573 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8574 source_position_t *const pos = &statement->base.source_position;
8576 *pos = token.source_position;
8577 statement->case_label.expression = parse_expression();
8578 if (! is_constant_expression(statement->case_label.expression)) {
8579 errorf(pos, "case label does not reduce to an integer constant");
8580 statement->case_label.is_bad = true;
8582 long const val = fold_constant(statement->case_label.expression);
8583 statement->case_label.first_case = val;
8584 statement->case_label.last_case = val;
8587 if (c_mode & _GNUC) {
8588 if (token.type == T_DOTDOTDOT) {
8590 statement->case_label.end_range = parse_expression();
8591 if (! is_constant_expression(statement->case_label.end_range)) {
8592 errorf(pos, "case range does not reduce to an integer constant");
8593 statement->case_label.is_bad = true;
8595 long const val = fold_constant(statement->case_label.end_range);
8596 statement->case_label.last_case = val;
8598 if (val < statement->case_label.first_case) {
8599 statement->case_label.is_empty = true;
8600 warningf(pos, "empty range specified");
8606 PUSH_PARENT(statement);
8610 if (current_switch != NULL) {
8611 if (! statement->case_label.is_bad) {
8612 /* Check for duplicate case values */
8613 case_label_statement_t *c = &statement->case_label;
8614 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8615 if (l->is_bad || l->is_empty || l->expression == NULL)
8618 if (c->last_case < l->first_case || c->first_case > l->last_case)
8621 errorf(pos, "duplicate case value (previously used %P)",
8622 &l->base.source_position);
8626 /* link all cases into the switch statement */
8627 if (current_switch->last_case == NULL) {
8628 current_switch->first_case = &statement->case_label;
8630 current_switch->last_case->next = &statement->case_label;
8632 current_switch->last_case = &statement->case_label;
8634 errorf(pos, "case label not within a switch statement");
8637 statement_t *const inner_stmt = parse_statement();
8638 statement->case_label.statement = inner_stmt;
8639 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8640 errorf(&inner_stmt->base.source_position, "declaration after case label");
8647 return create_invalid_statement();
8651 * Parse a default statement.
8653 static statement_t *parse_default_statement(void)
8657 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8658 statement->base.source_position = token.source_position;
8660 PUSH_PARENT(statement);
8663 if (current_switch != NULL) {
8664 const case_label_statement_t *def_label = current_switch->default_label;
8665 if (def_label != NULL) {
8666 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
8667 &def_label->base.source_position);
8669 current_switch->default_label = &statement->case_label;
8671 /* link all cases into the switch statement */
8672 if (current_switch->last_case == NULL) {
8673 current_switch->first_case = &statement->case_label;
8675 current_switch->last_case->next = &statement->case_label;
8677 current_switch->last_case = &statement->case_label;
8680 errorf(&statement->base.source_position,
8681 "'default' label not within a switch statement");
8684 statement_t *const inner_stmt = parse_statement();
8685 statement->case_label.statement = inner_stmt;
8686 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8687 errorf(&inner_stmt->base.source_position, "declaration after default label");
8694 return create_invalid_statement();
8698 * Parse a label statement.
8700 static statement_t *parse_label_statement(void)
8702 assert(token.type == T_IDENTIFIER);
8703 symbol_t *symbol = token.v.symbol;
8706 declaration_t *label = get_label(symbol);
8708 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8709 statement->base.source_position = token.source_position;
8710 statement->label.label = label;
8712 PUSH_PARENT(statement);
8714 /* if source position is already set then the label is defined twice,
8715 * otherwise it was just mentioned in a goto so far */
8716 if (label->source_position.input_name != NULL) {
8717 errorf(HERE, "duplicate label '%Y' (declared %P)",
8718 symbol, &label->source_position);
8720 label->source_position = token.source_position;
8721 label->init.statement = statement;
8726 if (token.type == '}') {
8727 /* TODO only warn? */
8729 warningf(HERE, "label at end of compound statement");
8730 statement->label.statement = create_empty_statement();
8732 errorf(HERE, "label at end of compound statement");
8733 statement->label.statement = create_invalid_statement();
8735 } else if (token.type == ';') {
8736 /* Eat an empty statement here, to avoid the warning about an empty
8737 * statement after a label. label:; is commonly used to have a label
8738 * before a closing brace. */
8739 statement->label.statement = create_empty_statement();
8742 statement_t *const inner_stmt = parse_statement();
8743 statement->label.statement = inner_stmt;
8744 if (inner_stmt->kind == STATEMENT_DECLARATION) {
8745 errorf(&inner_stmt->base.source_position, "declaration after label");
8749 /* remember the labels in a list for later checking */
8750 if (label_last == NULL) {
8751 label_first = &statement->label;
8753 label_last->next = &statement->label;
8755 label_last = &statement->label;
8762 * Parse an if statement.
8764 static statement_t *parse_if(void)
8768 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8769 statement->base.source_position = token.source_position;
8771 PUSH_PARENT(statement);
8774 add_anchor_token(')');
8775 statement->ifs.condition = parse_expression();
8776 rem_anchor_token(')');
8779 add_anchor_token(T_else);
8780 statement->ifs.true_statement = parse_statement();
8781 rem_anchor_token(T_else);
8783 if (token.type == T_else) {
8785 statement->ifs.false_statement = parse_statement();
8792 return create_invalid_statement();
8796 * Check that all enums are handled in a switch.
8798 * @param statement the switch statement to check
8800 static void check_enum_cases(const switch_statement_t *statement) {
8801 const type_t *type = skip_typeref(statement->expression->base.type);
8802 if (! is_type_enum(type))
8804 const enum_type_t *enumt = &type->enumt;
8806 /* if we have a default, no warnings */
8807 if (statement->default_label != NULL)
8810 /* FIXME: calculation of value should be done while parsing */
8811 const declaration_t *declaration;
8812 long last_value = -1;
8813 for (declaration = enumt->declaration->next;
8814 declaration != NULL && declaration->storage_class == STORAGE_CLASS_ENUM_ENTRY;
8815 declaration = declaration->next) {
8816 const expression_t *expression = declaration->init.enum_value;
8817 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
8819 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
8820 if (l->expression == NULL)
8822 if (l->first_case <= value && value <= l->last_case) {
8828 warningf(&statement->base.source_position,
8829 "enumeration value '%Y' not handled in switch", declaration->symbol);
8836 * Parse a switch statement.
8838 static statement_t *parse_switch(void)
8842 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
8843 statement->base.source_position = token.source_position;
8845 PUSH_PARENT(statement);
8848 add_anchor_token(')');
8849 expression_t *const expr = parse_expression();
8850 type_t * type = skip_typeref(expr->base.type);
8851 if (is_type_integer(type)) {
8852 type = promote_integer(type);
8853 if (warning.traditional) {
8854 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
8855 warningf(&expr->base.source_position,
8856 "'%T' switch expression not converted to '%T' in ISO C",
8860 } else if (is_type_valid(type)) {
8861 errorf(&expr->base.source_position,
8862 "switch quantity is not an integer, but '%T'", type);
8863 type = type_error_type;
8865 statement->switchs.expression = create_implicit_cast(expr, type);
8867 rem_anchor_token(')');
8869 switch_statement_t *rem = current_switch;
8870 current_switch = &statement->switchs;
8871 statement->switchs.body = parse_statement();
8872 current_switch = rem;
8874 if (warning.switch_default &&
8875 statement->switchs.default_label == NULL) {
8876 warningf(&statement->base.source_position, "switch has no default case");
8878 if (warning.switch_enum)
8879 check_enum_cases(&statement->switchs);
8885 return create_invalid_statement();
8888 static statement_t *parse_loop_body(statement_t *const loop)
8890 statement_t *const rem = current_loop;
8891 current_loop = loop;
8893 statement_t *const body = parse_statement();
8900 * Parse a while statement.
8902 static statement_t *parse_while(void)
8906 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
8907 statement->base.source_position = token.source_position;
8909 PUSH_PARENT(statement);
8912 add_anchor_token(')');
8913 statement->whiles.condition = parse_expression();
8914 rem_anchor_token(')');
8917 statement->whiles.body = parse_loop_body(statement);
8923 return create_invalid_statement();
8927 * Parse a do statement.
8929 static statement_t *parse_do(void)
8933 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
8934 statement->base.source_position = token.source_position;
8936 PUSH_PARENT(statement)
8938 add_anchor_token(T_while);
8939 statement->do_while.body = parse_loop_body(statement);
8940 rem_anchor_token(T_while);
8944 add_anchor_token(')');
8945 statement->do_while.condition = parse_expression();
8946 rem_anchor_token(')');
8954 return create_invalid_statement();
8958 * Parse a for statement.
8960 static statement_t *parse_for(void)
8964 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
8965 statement->base.source_position = token.source_position;
8967 PUSH_PARENT(statement);
8969 int top = environment_top();
8970 scope_t *last_scope = scope;
8971 set_scope(&statement->fors.scope);
8974 add_anchor_token(')');
8976 if (token.type != ';') {
8977 if (is_declaration_specifier(&token, false)) {
8978 parse_declaration(record_declaration);
8980 add_anchor_token(';');
8981 expression_t *const init = parse_expression();
8982 statement->fors.initialisation = init;
8983 if (warning.unused_value && !expression_has_effect(init)) {
8984 warningf(&init->base.source_position,
8985 "initialisation of 'for'-statement has no effect");
8987 rem_anchor_token(';');
8994 if (token.type != ';') {
8995 add_anchor_token(';');
8996 statement->fors.condition = parse_expression();
8997 rem_anchor_token(';');
9000 if (token.type != ')') {
9001 expression_t *const step = parse_expression();
9002 statement->fors.step = step;
9003 if (warning.unused_value && !expression_has_effect(step)) {
9004 warningf(&step->base.source_position,
9005 "step of 'for'-statement has no effect");
9008 rem_anchor_token(')');
9010 statement->fors.body = parse_loop_body(statement);
9012 assert(scope == &statement->fors.scope);
9013 set_scope(last_scope);
9014 environment_pop_to(top);
9021 rem_anchor_token(')');
9022 assert(scope == &statement->fors.scope);
9023 set_scope(last_scope);
9024 environment_pop_to(top);
9026 return create_invalid_statement();
9030 * Parse a goto statement.
9032 static statement_t *parse_goto(void)
9034 source_position_t source_position = token.source_position;
9037 statement_t *statement;
9038 if (c_mode & _GNUC && token.type == '*') {
9040 expression_t *expression = parse_expression();
9042 /* Argh: although documentation say the expression must be of type void *,
9043 * gcc excepts anything that can be casted into void * without error */
9044 type_t *type = expression->base.type;
9046 if (type != type_error_type) {
9047 if (!is_type_pointer(type) && !is_type_integer(type)) {
9048 errorf(&source_position, "cannot convert to a pointer type");
9049 } else if (type != type_void_ptr) {
9050 warningf(&source_position,
9051 "type of computed goto expression should be 'void*' not '%T'", type);
9053 expression = create_implicit_cast(expression, type_void_ptr);
9056 statement = allocate_statement_zero(STATEMENT_GOTO);
9057 statement->base.source_position = source_position;
9058 statement->gotos.expression = expression;
9060 if (token.type != T_IDENTIFIER) {
9062 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9064 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9068 symbol_t *symbol = token.v.symbol;
9071 statement = allocate_statement_zero(STATEMENT_GOTO);
9072 statement->base.source_position = source_position;
9073 statement->gotos.label = get_label(symbol);
9076 /* remember the goto's in a list for later checking */
9077 if (goto_last == NULL) {
9078 goto_first = &statement->gotos;
9080 goto_last->next = &statement->gotos;
9082 goto_last = &statement->gotos;
9088 return create_invalid_statement();
9092 * Parse a continue statement.
9094 static statement_t *parse_continue(void)
9096 if (current_loop == NULL) {
9097 errorf(HERE, "continue statement not within loop");
9100 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9101 statement->base.source_position = token.source_position;
9111 * Parse a break statement.
9113 static statement_t *parse_break(void)
9115 if (current_switch == NULL && current_loop == NULL) {
9116 errorf(HERE, "break statement not within loop or switch");
9119 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9120 statement->base.source_position = token.source_position;
9130 * Parse a __leave statement.
9132 static statement_t *parse_leave(void)
9134 if (current_try == NULL) {
9135 errorf(HERE, "__leave statement not within __try");
9138 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9139 statement->base.source_position = token.source_position;
9149 * Check if a given declaration represents a local variable.
9151 static bool is_local_var_declaration(const declaration_t *declaration)
9153 switch ((storage_class_tag_t) declaration->storage_class) {
9154 case STORAGE_CLASS_AUTO:
9155 case STORAGE_CLASS_REGISTER: {
9156 const type_t *type = skip_typeref(declaration->type);
9157 if (is_type_function(type)) {
9169 * Check if a given declaration represents a variable.
9171 static bool is_var_declaration(const declaration_t *declaration)
9173 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
9176 const type_t *type = skip_typeref(declaration->type);
9177 return !is_type_function(type);
9181 * Check if a given expression represents a local variable.
9183 static bool is_local_variable(const expression_t *expression)
9185 if (expression->base.kind != EXPR_REFERENCE) {
9188 const declaration_t *declaration = expression->reference.declaration;
9189 return is_local_var_declaration(declaration);
9193 * Check if a given expression represents a local variable and
9194 * return its declaration then, else return NULL.
9196 declaration_t *expr_is_variable(const expression_t *expression)
9198 if (expression->base.kind != EXPR_REFERENCE) {
9201 declaration_t *declaration = expression->reference.declaration;
9202 if (is_var_declaration(declaration))
9208 * Parse a return statement.
9210 static statement_t *parse_return(void)
9212 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9213 statement->base.source_position = token.source_position;
9217 expression_t *return_value = NULL;
9218 if (token.type != ';') {
9219 return_value = parse_expression();
9222 const type_t *const func_type = current_function->type;
9223 assert(is_type_function(func_type));
9224 type_t *const return_type = skip_typeref(func_type->function.return_type);
9226 if (return_value != NULL) {
9227 type_t *return_value_type = skip_typeref(return_value->base.type);
9229 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
9230 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9231 warningf(&statement->base.source_position,
9232 "'return' with a value, in function returning void");
9233 return_value = NULL;
9235 assign_error_t error = semantic_assign(return_type, return_value);
9236 report_assign_error(error, return_type, return_value, "'return'",
9237 &statement->base.source_position);
9238 return_value = create_implicit_cast(return_value, return_type);
9240 /* check for returning address of a local var */
9241 if (return_value != NULL &&
9242 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9243 const expression_t *expression = return_value->unary.value;
9244 if (is_local_variable(expression)) {
9245 warningf(&statement->base.source_position,
9246 "function returns address of local variable");
9250 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9251 warningf(&statement->base.source_position,
9252 "'return' without value, in function returning non-void");
9255 statement->returns.value = return_value;
9264 * Parse a declaration statement.
9266 static statement_t *parse_declaration_statement(void)
9268 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9270 statement->base.source_position = token.source_position;
9272 declaration_t *before = last_declaration;
9273 parse_declaration(record_declaration);
9275 if (before == NULL) {
9276 statement->declaration.declarations_begin = scope->declarations;
9278 statement->declaration.declarations_begin = before->next;
9280 statement->declaration.declarations_end = last_declaration;
9286 * Parse an expression statement, ie. expr ';'.
9288 static statement_t *parse_expression_statement(void)
9290 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9292 statement->base.source_position = token.source_position;
9293 expression_t *const expr = parse_expression();
9294 statement->expression.expression = expr;
9303 * Parse a microsoft __try { } __finally { } or
9304 * __try{ } __except() { }
9306 static statement_t *parse_ms_try_statment(void)
9308 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9309 statement->base.source_position = token.source_position;
9312 PUSH_PARENT(statement);
9314 ms_try_statement_t *rem = current_try;
9315 current_try = &statement->ms_try;
9316 statement->ms_try.try_statement = parse_compound_statement(false);
9321 if (token.type == T___except) {
9324 add_anchor_token(')');
9325 expression_t *const expr = parse_expression();
9326 type_t * type = skip_typeref(expr->base.type);
9327 if (is_type_integer(type)) {
9328 type = promote_integer(type);
9329 } else if (is_type_valid(type)) {
9330 errorf(&expr->base.source_position,
9331 "__expect expression is not an integer, but '%T'", type);
9332 type = type_error_type;
9334 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9335 rem_anchor_token(')');
9337 statement->ms_try.final_statement = parse_compound_statement(false);
9338 } else if (token.type == T__finally) {
9340 statement->ms_try.final_statement = parse_compound_statement(false);
9342 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9343 return create_invalid_statement();
9347 return create_invalid_statement();
9350 static statement_t *parse_empty_statement(void)
9352 if (warning.empty_statement) {
9353 warningf(HERE, "statement is empty");
9355 statement_t *const statement = create_empty_statement();
9361 * Parse a statement.
9362 * There's also parse_statement() which additionally checks for
9363 * "statement has no effect" warnings
9365 static statement_t *intern_parse_statement(void)
9367 statement_t *statement = NULL;
9369 /* declaration or statement */
9370 add_anchor_token(';');
9371 switch (token.type) {
9372 case T_IDENTIFIER: {
9373 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9374 if (la1_type == ':') {
9375 statement = parse_label_statement();
9376 } else if (is_typedef_symbol(token.v.symbol)) {
9377 statement = parse_declaration_statement();
9378 } else switch (la1_type) {
9382 statement = parse_declaration_statement();
9386 statement = parse_expression_statement();
9392 case T___extension__:
9393 /* This can be a prefix to a declaration or an expression statement.
9394 * We simply eat it now and parse the rest with tail recursion. */
9397 } while (token.type == T___extension__);
9398 statement = parse_statement();
9402 statement = parse_declaration_statement();
9405 case ';': statement = parse_empty_statement(); break;
9406 case '{': statement = parse_compound_statement(false); break;
9407 case T___leave: statement = parse_leave(); break;
9408 case T___try: statement = parse_ms_try_statment(); break;
9409 case T_asm: statement = parse_asm_statement(); break;
9410 case T_break: statement = parse_break(); break;
9411 case T_case: statement = parse_case_statement(); break;
9412 case T_continue: statement = parse_continue(); break;
9413 case T_default: statement = parse_default_statement(); break;
9414 case T_do: statement = parse_do(); break;
9415 case T_for: statement = parse_for(); break;
9416 case T_goto: statement = parse_goto(); break;
9417 case T_if: statement = parse_if (); break;
9418 case T_return: statement = parse_return(); break;
9419 case T_switch: statement = parse_switch(); break;
9420 case T_while: statement = parse_while(); break;
9421 default: statement = parse_expression_statement(); break;
9423 rem_anchor_token(';');
9425 assert(statement != NULL
9426 && statement->base.source_position.input_name != NULL);
9432 * parse a statement and emits "statement has no effect" warning if needed
9433 * (This is really a wrapper around intern_parse_statement with check for 1
9434 * single warning. It is needed, because for statement expressions we have
9435 * to avoid the warning on the last statement)
9437 static statement_t *parse_statement(void)
9439 statement_t *statement = intern_parse_statement();
9441 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
9442 expression_t *expression = statement->expression.expression;
9443 if (!expression_has_effect(expression)) {
9444 warningf(&expression->base.source_position,
9445 "statement has no effect");
9453 * Parse a compound statement.
9455 static statement_t *parse_compound_statement(bool inside_expression_statement)
9457 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9458 statement->base.source_position = token.source_position;
9460 PUSH_PARENT(statement);
9463 add_anchor_token('}');
9465 int top = environment_top();
9466 scope_t *last_scope = scope;
9467 set_scope(&statement->compound.scope);
9469 statement_t **anchor = &statement->compound.statements;
9470 bool only_decls_so_far = true;
9471 while (token.type != '}' && token.type != T_EOF) {
9472 statement_t *sub_statement = intern_parse_statement();
9473 if (is_invalid_statement(sub_statement)) {
9474 /* an error occurred. if we are at an anchor, return */
9480 if (warning.declaration_after_statement) {
9481 if (sub_statement->kind != STATEMENT_DECLARATION) {
9482 only_decls_so_far = false;
9483 } else if (!only_decls_so_far) {
9484 warningf(&sub_statement->base.source_position,
9485 "ISO C90 forbids mixed declarations and code");
9489 *anchor = sub_statement;
9491 while (sub_statement->base.next != NULL)
9492 sub_statement = sub_statement->base.next;
9494 anchor = &sub_statement->base.next;
9497 if (token.type == '}') {
9500 errorf(&statement->base.source_position,
9501 "end of file while looking for closing '}'");
9504 /* look over all statements again to produce no effect warnings */
9505 if (warning.unused_value) {
9506 statement_t *sub_statement = statement->compound.statements;
9507 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9508 if (sub_statement->kind != STATEMENT_EXPRESSION)
9510 /* don't emit a warning for the last expression in an expression
9511 * statement as it has always an effect */
9512 if (inside_expression_statement && sub_statement->base.next == NULL)
9515 expression_t *expression = sub_statement->expression.expression;
9516 if (!expression_has_effect(expression)) {
9517 warningf(&expression->base.source_position,
9518 "statement has no effect");
9524 rem_anchor_token('}');
9525 assert(scope == &statement->compound.scope);
9526 set_scope(last_scope);
9527 environment_pop_to(top);
9534 * Initialize builtin types.
9536 static void initialize_builtin_types(void)
9538 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
9539 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
9540 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
9541 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
9542 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
9543 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
9544 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
9545 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
9547 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
9548 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
9549 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
9550 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
9552 /* const version of wchar_t */
9553 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
9554 type_const_wchar_t->typedeft.declaration = type_wchar_t->typedeft.declaration;
9555 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
9557 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
9561 * Check for unused global static functions and variables
9563 static void check_unused_globals(void)
9565 if (!warning.unused_function && !warning.unused_variable)
9568 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
9570 decl->modifiers & DM_UNUSED ||
9571 decl->modifiers & DM_USED ||
9572 decl->storage_class != STORAGE_CLASS_STATIC)
9575 type_t *const type = decl->type;
9577 if (is_type_function(skip_typeref(type))) {
9578 if (!warning.unused_function || decl->is_inline)
9581 s = (decl->init.statement != NULL ? "defined" : "declared");
9583 if (!warning.unused_variable)
9589 warningf(&decl->source_position, "'%#T' %s but not used",
9590 type, decl->symbol, s);
9594 static void parse_global_asm(void)
9599 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9600 statement->base.source_position = token.source_position;
9601 statement->asms.asm_text = parse_string_literals();
9602 statement->base.next = unit->global_asm;
9603 unit->global_asm = statement;
9612 * Parse a translation unit.
9614 static void parse_translation_unit(void)
9616 for (;;) switch (token.type) {
9619 case T___extension__:
9620 parse_external_declaration();
9631 /* TODO error in strict mode */
9632 warningf(HERE, "stray ';' outside of function");
9637 errorf(HERE, "stray %K outside of function", &token);
9638 if (token.type == '(' || token.type == '{' || token.type == '[')
9639 eat_until_matching_token(token.type);
9648 * @return the translation unit or NULL if errors occurred.
9650 void start_parsing(void)
9652 environment_stack = NEW_ARR_F(stack_entry_t, 0);
9653 label_stack = NEW_ARR_F(stack_entry_t, 0);
9654 diagnostic_count = 0;
9658 type_set_output(stderr);
9659 ast_set_output(stderr);
9661 assert(unit == NULL);
9662 unit = allocate_ast_zero(sizeof(unit[0]));
9664 assert(global_scope == NULL);
9665 global_scope = &unit->scope;
9667 assert(scope == NULL);
9668 set_scope(&unit->scope);
9670 initialize_builtin_types();
9673 translation_unit_t *finish_parsing(void)
9675 assert(scope == &unit->scope);
9677 last_declaration = NULL;
9679 assert(global_scope == &unit->scope);
9680 check_unused_globals();
9681 global_scope = NULL;
9683 DEL_ARR_F(environment_stack);
9684 DEL_ARR_F(label_stack);
9686 translation_unit_t *result = unit;
9693 lookahead_bufpos = 0;
9694 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
9697 parse_translation_unit();
9701 * Initialize the parser.
9703 void init_parser(void)
9706 /* add predefined symbols for extended-decl-modifier */
9707 sym_align = symbol_table_insert("align");
9708 sym_allocate = symbol_table_insert("allocate");
9709 sym_dllimport = symbol_table_insert("dllimport");
9710 sym_dllexport = symbol_table_insert("dllexport");
9711 sym_naked = symbol_table_insert("naked");
9712 sym_noinline = symbol_table_insert("noinline");
9713 sym_noreturn = symbol_table_insert("noreturn");
9714 sym_nothrow = symbol_table_insert("nothrow");
9715 sym_novtable = symbol_table_insert("novtable");
9716 sym_property = symbol_table_insert("property");
9717 sym_get = symbol_table_insert("get");
9718 sym_put = symbol_table_insert("put");
9719 sym_selectany = symbol_table_insert("selectany");
9720 sym_thread = symbol_table_insert("thread");
9721 sym_uuid = symbol_table_insert("uuid");
9722 sym_deprecated = symbol_table_insert("deprecated");
9723 sym_restrict = symbol_table_insert("restrict");
9724 sym_noalias = symbol_table_insert("noalias");
9726 memset(token_anchor_set, 0, sizeof(token_anchor_set));
9728 init_expression_parsers();
9729 obstack_init(&temp_obst);
9731 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
9732 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
9736 * Terminate the parser.
9738 void exit_parser(void)
9740 obstack_free(&temp_obst, NULL);