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 //#define PRINT_TOKENS
43 #define MAX_LOOKAHEAD 2
46 declaration_t *old_declaration;
48 unsigned short namespc;
51 typedef struct gnu_attribute_t gnu_attribute_t;
52 struct gnu_attribute_t {
53 gnu_attribute_kind_t kind;
54 gnu_attribute_t *next;
60 atomic_type_kind_t akind;
64 typedef struct declaration_specifiers_t declaration_specifiers_t;
65 struct declaration_specifiers_t {
66 source_position_t source_position;
67 unsigned char declared_storage_class;
68 unsigned char alignment; /**< Alignment, 0 if not set. */
69 unsigned int is_inline : 1;
70 unsigned int deprecated : 1;
71 decl_modifiers_t modifiers; /**< declaration modifiers */
72 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
73 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
74 symbol_t *get_property_sym; /**< the name of the get property if set. */
75 symbol_t *put_property_sym; /**< the name of the put property if set. */
80 * An environment for parsing initializers (and compound literals).
82 typedef struct parse_initializer_env_t {
83 type_t *type; /**< the type of the initializer. In case of an
84 array type with unspecified size this gets
85 adjusted to the actual size. */
86 declaration_t *declaration; /**< the declaration that is initialized if any */
87 bool must_be_constant;
88 } parse_initializer_env_t;
90 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
93 static token_t lookahead_buffer[MAX_LOOKAHEAD];
94 static int lookahead_bufpos;
95 static stack_entry_t *environment_stack = NULL;
96 static stack_entry_t *label_stack = NULL;
97 static scope_t *global_scope = NULL;
98 static scope_t *scope = NULL;
99 static declaration_t *last_declaration = NULL;
100 static declaration_t *current_function = NULL;
101 static switch_statement_t *current_switch = NULL;
102 static statement_t *current_loop = NULL;
103 static ms_try_statement_t *current_try = NULL;
104 static goto_statement_t *goto_first = NULL;
105 static goto_statement_t *goto_last = NULL;
106 static label_statement_t *label_first = NULL;
107 static label_statement_t *label_last = NULL;
108 static translation_unit_t *unit = NULL;
109 static struct obstack temp_obst;
111 static source_position_t null_position = { NULL, 0 };
113 /* symbols for Microsoft extended-decl-modifier */
114 static const symbol_t *sym_align = NULL;
115 static const symbol_t *sym_allocate = NULL;
116 static const symbol_t *sym_dllimport = NULL;
117 static const symbol_t *sym_dllexport = NULL;
118 static const symbol_t *sym_naked = NULL;
119 static const symbol_t *sym_noinline = NULL;
120 static const symbol_t *sym_noreturn = NULL;
121 static const symbol_t *sym_nothrow = NULL;
122 static const symbol_t *sym_novtable = NULL;
123 static const symbol_t *sym_property = NULL;
124 static const symbol_t *sym_get = NULL;
125 static const symbol_t *sym_put = NULL;
126 static const symbol_t *sym_selectany = NULL;
127 static const symbol_t *sym_thread = NULL;
128 static const symbol_t *sym_uuid = NULL;
129 static const symbol_t *sym_deprecated = NULL;
130 static const symbol_t *sym_restrict = NULL;
131 static const symbol_t *sym_noalias = NULL;
133 /** The token anchor set */
134 static unsigned char token_anchor_set[T_LAST_TOKEN];
136 /** The current source position. */
137 #define HERE (&token.source_position)
139 static type_t *type_valist;
141 static statement_t *parse_compound_statement(bool inside_expression_statement);
142 static statement_t *parse_statement(void);
144 static expression_t *parse_sub_expression(unsigned precedence);
145 static expression_t *parse_expression(void);
146 static type_t *parse_typename(void);
148 static void parse_compound_type_entries(declaration_t *compound_declaration);
149 static declaration_t *parse_declarator(
150 const declaration_specifiers_t *specifiers, bool may_be_abstract);
151 static declaration_t *record_declaration(declaration_t *declaration);
153 static void semantic_comparison(binary_expression_t *expression);
155 #define STORAGE_CLASSES \
162 #define TYPE_QUALIFIERS \
167 case T__forceinline: \
168 case T___attribute__:
170 #ifdef PROVIDE_COMPLEX
171 #define COMPLEX_SPECIFIERS \
173 #define IMAGINARY_SPECIFIERS \
176 #define COMPLEX_SPECIFIERS
177 #define IMAGINARY_SPECIFIERS
180 #define TYPE_SPECIFIERS \
195 case T___builtin_va_list: \
200 #define DECLARATION_START \
205 #define TYPENAME_START \
210 * Allocate an AST node with given size and
211 * initialize all fields with zero.
213 static void *allocate_ast_zero(size_t size)
215 void *res = allocate_ast(size);
216 memset(res, 0, size);
220 static declaration_t *allocate_declaration_zero(void)
222 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
223 declaration->type = type_error_type;
224 declaration->alignment = 0;
229 * Returns the size of a statement node.
231 * @param kind the statement kind
233 static size_t get_statement_struct_size(statement_kind_t kind)
235 static const size_t sizes[] = {
236 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
237 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
238 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
239 [STATEMENT_RETURN] = sizeof(return_statement_t),
240 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
241 [STATEMENT_IF] = sizeof(if_statement_t),
242 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
243 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
244 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
245 [STATEMENT_BREAK] = sizeof(statement_base_t),
246 [STATEMENT_GOTO] = sizeof(goto_statement_t),
247 [STATEMENT_LABEL] = sizeof(label_statement_t),
248 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
249 [STATEMENT_WHILE] = sizeof(while_statement_t),
250 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
251 [STATEMENT_FOR] = sizeof(for_statement_t),
252 [STATEMENT_ASM] = sizeof(asm_statement_t),
253 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
254 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
256 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
257 assert(sizes[kind] != 0);
262 * Returns the size of an expression node.
264 * @param kind the expression kind
266 static size_t get_expression_struct_size(expression_kind_t kind)
268 static const size_t sizes[] = {
269 [EXPR_INVALID] = sizeof(expression_base_t),
270 [EXPR_REFERENCE] = sizeof(reference_expression_t),
271 [EXPR_CONST] = sizeof(const_expression_t),
272 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
273 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
274 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
275 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
276 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
277 [EXPR_CALL] = sizeof(call_expression_t),
278 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
279 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
280 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
281 [EXPR_SELECT] = sizeof(select_expression_t),
282 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
283 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
284 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
285 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
286 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
287 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
288 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
289 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
290 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
291 [EXPR_VA_START] = sizeof(va_start_expression_t),
292 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
293 [EXPR_STATEMENT] = sizeof(statement_expression_t),
295 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
296 return sizes[EXPR_UNARY_FIRST];
298 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
299 return sizes[EXPR_BINARY_FIRST];
301 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
302 assert(sizes[kind] != 0);
307 * Allocate a statement node of given kind and initialize all
310 static statement_t *allocate_statement_zero(statement_kind_t kind)
312 size_t size = get_statement_struct_size(kind);
313 statement_t *res = allocate_ast_zero(size);
315 res->base.kind = kind;
320 * Allocate an expression node of given kind and initialize all
323 static expression_t *allocate_expression_zero(expression_kind_t kind)
325 size_t size = get_expression_struct_size(kind);
326 expression_t *res = allocate_ast_zero(size);
328 res->base.kind = kind;
329 res->base.type = type_error_type;
334 * Creates a new invalid expression.
336 static expression_t *create_invalid_expression(void)
338 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
339 expression->base.source_position = token.source_position;
344 * Creates a new invalid statement.
346 static statement_t *create_invalid_statement(void)
348 statement_t *statement = allocate_statement_zero(STATEMENT_INVALID);
349 statement->base.source_position = token.source_position;
354 * Allocate a new empty statement.
356 static statement_t *create_empty_statement(void)
358 statement_t *statement = allocate_statement_zero(STATEMENT_EMPTY);
359 statement->base.source_position = token.source_position;
364 * Returns the size of a type node.
366 * @param kind the type kind
368 static size_t get_type_struct_size(type_kind_t kind)
370 static const size_t sizes[] = {
371 [TYPE_ATOMIC] = sizeof(atomic_type_t),
372 [TYPE_COMPLEX] = sizeof(complex_type_t),
373 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
374 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
375 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
376 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
377 [TYPE_ENUM] = sizeof(enum_type_t),
378 [TYPE_FUNCTION] = sizeof(function_type_t),
379 [TYPE_POINTER] = sizeof(pointer_type_t),
380 [TYPE_ARRAY] = sizeof(array_type_t),
381 [TYPE_BUILTIN] = sizeof(builtin_type_t),
382 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
383 [TYPE_TYPEOF] = sizeof(typeof_type_t),
385 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
386 assert(kind <= TYPE_TYPEOF);
387 assert(sizes[kind] != 0);
392 * Allocate a type node of given kind and initialize all
395 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
397 size_t size = get_type_struct_size(kind);
398 type_t *res = obstack_alloc(type_obst, size);
399 memset(res, 0, size);
401 res->base.kind = kind;
402 res->base.source_position = *source_position;
407 * Returns the size of an initializer node.
409 * @param kind the initializer kind
411 static size_t get_initializer_size(initializer_kind_t kind)
413 static const size_t sizes[] = {
414 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
415 [INITIALIZER_STRING] = sizeof(initializer_string_t),
416 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
417 [INITIALIZER_LIST] = sizeof(initializer_list_t),
418 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
420 assert(kind < sizeof(sizes) / sizeof(*sizes));
421 assert(sizes[kind] != 0);
426 * Allocate an initializer node of given kind and initialize all
429 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
431 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
438 * Free a type from the type obstack.
440 static void free_type(void *type)
442 obstack_free(type_obst, type);
446 * Returns the index of the top element of the environment stack.
448 static size_t environment_top(void)
450 return ARR_LEN(environment_stack);
454 * Returns the index of the top element of the label stack.
456 static size_t label_top(void)
458 return ARR_LEN(label_stack);
462 * Return the next token.
464 static inline void next_token(void)
466 token = lookahead_buffer[lookahead_bufpos];
467 lookahead_buffer[lookahead_bufpos] = lexer_token;
470 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
473 print_token(stderr, &token);
474 fprintf(stderr, "\n");
479 * Return the next token with a given lookahead.
481 static inline const token_t *look_ahead(int num)
483 assert(num > 0 && num <= MAX_LOOKAHEAD);
484 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
485 return &lookahead_buffer[pos];
489 * Adds a token to the token anchor set (a multi-set).
491 static void add_anchor_token(int token_type) {
492 assert(0 <= token_type && token_type < T_LAST_TOKEN);
493 ++token_anchor_set[token_type];
496 static int save_and_reset_anchor_state(int token_type) {
497 assert(0 <= token_type && token_type < T_LAST_TOKEN);
498 int count = token_anchor_set[token_type];
499 token_anchor_set[token_type] = 0;
503 static void restore_anchor_state(int token_type, int count) {
504 assert(0 <= token_type && token_type < T_LAST_TOKEN);
505 token_anchor_set[token_type] = count;
509 * Remove a token from the token anchor set (a multi-set).
511 static void rem_anchor_token(int token_type) {
512 assert(0 <= token_type && token_type < T_LAST_TOKEN);
513 --token_anchor_set[token_type];
516 static bool at_anchor(void) {
519 return token_anchor_set[token.type];
523 * Eat tokens until a matching token is found.
525 static void eat_until_matching_token(int type) {
526 unsigned parenthesis_count = 0;
527 unsigned brace_count = 0;
528 unsigned bracket_count = 0;
532 case '(': end_token = ')'; break;
533 case '{': end_token = '}'; break;
534 case '[': end_token = ']'; break;
535 default: end_token = type; break;
538 while(token.type != end_token ||
539 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
543 case '(': ++parenthesis_count; break;
544 case '{': ++brace_count; break;
545 case '[': ++bracket_count; break;
547 if (parenthesis_count > 0)
555 if (bracket_count > 0)
566 * Eat input tokens until an anchor is found.
568 static void eat_until_anchor(void) {
569 if (token.type == T_EOF)
571 while(token_anchor_set[token.type] == 0) {
572 if (token.type == '(' || token.type == '{' || token.type == '[')
573 eat_until_matching_token(token.type);
574 if (token.type == T_EOF)
580 static void eat_block(void) {
581 eat_until_matching_token('{');
582 if (token.type == '}')
587 * eat all token until a ';' is reached or a stop token is found.
589 static void eat_statement(void) {
590 eat_until_matching_token(';');
591 if (token.type == ';')
595 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
598 * Report a parse error because an expected token was not found.
601 #if defined __GNUC__ && __GNUC__ >= 4
602 __attribute__((sentinel))
604 void parse_error_expected(const char *message, ...)
606 if (message != NULL) {
607 errorf(HERE, "%s", message);
610 va_start(ap, message);
611 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
616 * Report a type error.
618 static void type_error(const char *msg, const source_position_t *source_position,
621 errorf(source_position, "%s, but found type '%T'", msg, type);
625 * Report an incompatible type.
627 static void type_error_incompatible(const char *msg,
628 const source_position_t *source_position, type_t *type1, type_t *type2)
630 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
635 * Expect the the current token is the expected token.
636 * If not, generate an error, eat the current statement,
637 * and goto the end_error label.
639 #define expect(expected) \
641 if (UNLIKELY(token.type != (expected))) { \
642 parse_error_expected(NULL, (expected), NULL); \
643 add_anchor_token(expected); \
644 eat_until_anchor(); \
645 if (token.type == expected) \
647 rem_anchor_token(expected); \
653 static void set_scope(scope_t *new_scope)
656 scope->last_declaration = last_declaration;
660 last_declaration = new_scope->last_declaration;
664 * Search a symbol in a given namespace and returns its declaration or
665 * NULL if this symbol was not found.
667 static declaration_t *get_declaration(const symbol_t *const symbol,
668 const namespace_t namespc)
670 declaration_t *declaration = symbol->declaration;
671 for( ; declaration != NULL; declaration = declaration->symbol_next) {
672 if (declaration->namespc == namespc)
680 * pushs an environment_entry on the environment stack and links the
681 * corresponding symbol to the new entry
683 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
685 symbol_t *symbol = declaration->symbol;
686 namespace_t namespc = (namespace_t) declaration->namespc;
688 /* replace/add declaration into declaration list of the symbol */
689 declaration_t *iter = symbol->declaration;
691 symbol->declaration = declaration;
693 declaration_t *iter_last = NULL;
694 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
695 /* replace an entry? */
696 if (iter->namespc == namespc) {
697 if (iter_last == NULL) {
698 symbol->declaration = declaration;
700 iter_last->symbol_next = declaration;
702 declaration->symbol_next = iter->symbol_next;
707 assert(iter_last->symbol_next == NULL);
708 iter_last->symbol_next = declaration;
712 /* remember old declaration */
714 entry.symbol = symbol;
715 entry.old_declaration = iter;
716 entry.namespc = (unsigned short) namespc;
717 ARR_APP1(stack_entry_t, *stack_ptr, entry);
720 static void environment_push(declaration_t *declaration)
722 assert(declaration->source_position.input_name != NULL);
723 assert(declaration->parent_scope != NULL);
724 stack_push(&environment_stack, declaration);
727 static void label_push(declaration_t *declaration)
729 declaration->parent_scope = ¤t_function->scope;
730 stack_push(&label_stack, declaration);
734 * pops symbols from the environment stack until @p new_top is the top element
736 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
738 stack_entry_t *stack = *stack_ptr;
739 size_t top = ARR_LEN(stack);
742 assert(new_top <= top);
746 for(i = top; i > new_top; --i) {
747 stack_entry_t *entry = &stack[i - 1];
749 declaration_t *old_declaration = entry->old_declaration;
750 symbol_t *symbol = entry->symbol;
751 namespace_t namespc = (namespace_t)entry->namespc;
753 /* replace/remove declaration */
754 declaration_t *declaration = symbol->declaration;
755 assert(declaration != NULL);
756 if (declaration->namespc == namespc) {
757 if (old_declaration == NULL) {
758 symbol->declaration = declaration->symbol_next;
760 symbol->declaration = old_declaration;
763 declaration_t *iter_last = declaration;
764 declaration_t *iter = declaration->symbol_next;
765 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
766 /* replace an entry? */
767 if (iter->namespc == namespc) {
768 assert(iter_last != NULL);
769 iter_last->symbol_next = old_declaration;
770 if (old_declaration != NULL) {
771 old_declaration->symbol_next = iter->symbol_next;
776 assert(iter != NULL);
780 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
783 static void environment_pop_to(size_t new_top)
785 stack_pop_to(&environment_stack, new_top);
788 static void label_pop_to(size_t new_top)
790 stack_pop_to(&label_stack, new_top);
794 static int get_rank(const type_t *type)
796 assert(!is_typeref(type));
797 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
798 * and esp. footnote 108). However we can't fold constants (yet), so we
799 * can't decide whether unsigned int is possible, while int always works.
800 * (unsigned int would be preferable when possible... for stuff like
801 * struct { enum { ... } bla : 4; } ) */
802 if (type->kind == TYPE_ENUM)
803 return ATOMIC_TYPE_INT;
805 assert(type->kind == TYPE_ATOMIC);
806 return type->atomic.akind;
809 static type_t *promote_integer(type_t *type)
811 if (type->kind == TYPE_BITFIELD)
812 type = type->bitfield.base_type;
814 if (get_rank(type) < ATOMIC_TYPE_INT)
821 * Create a cast expression.
823 * @param expression the expression to cast
824 * @param dest_type the destination type
826 static expression_t *create_cast_expression(expression_t *expression,
829 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
831 cast->unary.value = expression;
832 cast->base.type = dest_type;
838 * Check if a given expression represents the 0 pointer constant.
840 static bool is_null_pointer_constant(const expression_t *expression)
842 /* skip void* cast */
843 if (expression->kind == EXPR_UNARY_CAST
844 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
845 expression = expression->unary.value;
848 /* TODO: not correct yet, should be any constant integer expression
849 * which evaluates to 0 */
850 if (expression->kind != EXPR_CONST)
853 type_t *const type = skip_typeref(expression->base.type);
854 if (!is_type_integer(type))
857 return expression->conste.v.int_value == 0;
861 * Create an implicit cast expression.
863 * @param expression the expression to cast
864 * @param dest_type the destination type
866 static expression_t *create_implicit_cast(expression_t *expression,
869 type_t *const source_type = expression->base.type;
871 if (source_type == dest_type)
874 return create_cast_expression(expression, dest_type);
877 typedef enum assign_error_t {
879 ASSIGN_ERROR_INCOMPATIBLE,
880 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
881 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
882 ASSIGN_WARNING_POINTER_FROM_INT,
883 ASSIGN_WARNING_INT_FROM_POINTER
886 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
887 const expression_t *const right,
889 const source_position_t *source_position)
891 type_t *const orig_type_right = right->base.type;
892 type_t *const type_left = skip_typeref(orig_type_left);
893 type_t *const type_right = skip_typeref(orig_type_right);
898 case ASSIGN_ERROR_INCOMPATIBLE:
899 errorf(source_position,
900 "destination type '%T' in %s is incompatible with type '%T'",
901 orig_type_left, context, orig_type_right);
904 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
905 type_t *points_to_left
906 = skip_typeref(type_left->pointer.points_to);
907 type_t *points_to_right
908 = skip_typeref(type_right->pointer.points_to);
910 /* the left type has all qualifiers from the right type */
911 unsigned missing_qualifiers
912 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
913 errorf(source_position,
914 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
915 orig_type_left, context, orig_type_right, missing_qualifiers);
919 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
920 warningf(source_position,
921 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
922 orig_type_left, context, right, orig_type_right);
925 case ASSIGN_WARNING_POINTER_FROM_INT:
926 warningf(source_position,
927 "%s makes integer '%T' from pointer '%T' without a cast",
928 context, orig_type_left, orig_type_right);
931 case ASSIGN_WARNING_INT_FROM_POINTER:
932 warningf(source_position,
933 "%s makes integer '%T' from pointer '%T' without a cast",
934 context, orig_type_left, orig_type_right);
938 panic("invalid error value");
942 /** Implements the rules from § 6.5.16.1 */
943 static assign_error_t semantic_assign(type_t *orig_type_left,
944 const expression_t *const right)
946 type_t *const orig_type_right = right->base.type;
947 type_t *const type_left = skip_typeref(orig_type_left);
948 type_t *const type_right = skip_typeref(orig_type_right);
950 if (is_type_pointer(type_left)) {
951 if (is_null_pointer_constant(right)) {
952 return ASSIGN_SUCCESS;
953 } else if (is_type_pointer(type_right)) {
954 type_t *points_to_left
955 = skip_typeref(type_left->pointer.points_to);
956 type_t *points_to_right
957 = skip_typeref(type_right->pointer.points_to);
959 /* the left type has all qualifiers from the right type */
960 unsigned missing_qualifiers
961 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
962 if (missing_qualifiers != 0) {
963 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
966 points_to_left = get_unqualified_type(points_to_left);
967 points_to_right = get_unqualified_type(points_to_right);
969 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
970 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
971 return ASSIGN_SUCCESS;
974 if (!types_compatible(points_to_left, points_to_right)) {
975 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
978 return ASSIGN_SUCCESS;
979 } else if (is_type_integer(type_right)) {
980 return ASSIGN_WARNING_POINTER_FROM_INT;
982 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
983 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
984 && is_type_pointer(type_right))) {
985 return ASSIGN_SUCCESS;
986 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
987 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
988 type_t *const unqual_type_left = get_unqualified_type(type_left);
989 type_t *const unqual_type_right = get_unqualified_type(type_right);
990 if (types_compatible(unqual_type_left, unqual_type_right)) {
991 return ASSIGN_SUCCESS;
993 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
994 return ASSIGN_WARNING_INT_FROM_POINTER;
997 if (!is_type_valid(type_left) || !is_type_valid(type_right))
998 return ASSIGN_SUCCESS;
1000 return ASSIGN_ERROR_INCOMPATIBLE;
1003 static expression_t *parse_constant_expression(void)
1005 /* start parsing at precedence 7 (conditional expression) */
1006 expression_t *result = parse_sub_expression(7);
1008 if (!is_constant_expression(result)) {
1009 errorf(&result->base.source_position,
1010 "expression '%E' is not constant\n", result);
1016 static expression_t *parse_assignment_expression(void)
1018 /* start parsing at precedence 2 (assignment expression) */
1019 return parse_sub_expression(2);
1022 static type_t *make_global_typedef(const char *name, type_t *type)
1024 symbol_t *const symbol = symbol_table_insert(name);
1026 declaration_t *const declaration = allocate_declaration_zero();
1027 declaration->namespc = NAMESPACE_NORMAL;
1028 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1029 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1030 declaration->type = type;
1031 declaration->symbol = symbol;
1032 declaration->source_position = builtin_source_position;
1034 record_declaration(declaration);
1036 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1037 typedef_type->typedeft.declaration = declaration;
1039 return typedef_type;
1042 static string_t parse_string_literals(void)
1044 assert(token.type == T_STRING_LITERAL);
1045 string_t result = token.v.string;
1049 while (token.type == T_STRING_LITERAL) {
1050 result = concat_strings(&result, &token.v.string);
1057 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1058 [GNU_AK_CONST] = "const",
1059 [GNU_AK_VOLATILE] = "volatile",
1060 [GNU_AK_CDECL] = "cdecl",
1061 [GNU_AK_STDCALL] = "stdcall",
1062 [GNU_AK_FASTCALL] = "fastcall",
1063 [GNU_AK_DEPRECATED] = "deprecated",
1064 [GNU_AK_NOINLINE] = "noinline",
1065 [GNU_AK_NORETURN] = "noreturn",
1066 [GNU_AK_NAKED] = "naked",
1067 [GNU_AK_PURE] = "pure",
1068 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1069 [GNU_AK_MALLOC] = "malloc",
1070 [GNU_AK_WEAK] = "weak",
1071 [GNU_AK_CONSTRUCTOR] = "constructor",
1072 [GNU_AK_DESTRUCTOR] = "destructor",
1073 [GNU_AK_NOTHROW] = "nothrow",
1074 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1075 [GNU_AK_COMMON] = "common",
1076 [GNU_AK_NOCOMMON] = "nocommon",
1077 [GNU_AK_PACKED] = "packed",
1078 [GNU_AK_SHARED] = "shared",
1079 [GNU_AK_NOTSHARED] = "notshared",
1080 [GNU_AK_USED] = "used",
1081 [GNU_AK_UNUSED] = "unused",
1082 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1083 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1084 [GNU_AK_LONGCALL] = "longcall",
1085 [GNU_AK_SHORTCALL] = "shortcall",
1086 [GNU_AK_LONG_CALL] = "long_call",
1087 [GNU_AK_SHORT_CALL] = "short_call",
1088 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1089 [GNU_AK_INTERRUPT] = "interrupt",
1090 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1091 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1092 [GNU_AK_NESTING] = "nesting",
1093 [GNU_AK_NEAR] = "near",
1094 [GNU_AK_FAR] = "far",
1095 [GNU_AK_SIGNAL] = "signal",
1096 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1097 [GNU_AK_TINY_DATA] = "tiny_data",
1098 [GNU_AK_SAVEALL] = "saveall",
1099 [GNU_AK_FLATTEN] = "flatten",
1100 [GNU_AK_SSEREGPARM] = "sseregparm",
1101 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1102 [GNU_AK_RETURN_TWICE] = "return_twice",
1103 [GNU_AK_MAY_ALIAS] = "may_alias",
1104 [GNU_AK_MS_STRUCT] = "ms_struct",
1105 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1106 [GNU_AK_DLLIMPORT] = "dllimport",
1107 [GNU_AK_DLLEXPORT] = "dllexport",
1108 [GNU_AK_ALIGNED] = "aligned",
1109 [GNU_AK_ALIAS] = "alias",
1110 [GNU_AK_SECTION] = "section",
1111 [GNU_AK_FORMAT] = "format",
1112 [GNU_AK_FORMAT_ARG] = "format_arg",
1113 [GNU_AK_WEAKREF] = "weakref",
1114 [GNU_AK_NONNULL] = "nonnull",
1115 [GNU_AK_TLS_MODEL] = "tls_model",
1116 [GNU_AK_VISIBILITY] = "visibility",
1117 [GNU_AK_REGPARM] = "regparm",
1118 [GNU_AK_MODE] = "mode",
1119 [GNU_AK_MODEL] = "model",
1120 [GNU_AK_TRAP_EXIT] = "trap_exit",
1121 [GNU_AK_SP_SWITCH] = "sp_switch",
1122 [GNU_AK_SENTINEL] = "sentinel"
1126 * compare two string, ignoring double underscores on the second.
1128 static int strcmp_underscore(const char *s1, const char *s2) {
1129 if (s2[0] == '_' && s2[1] == '_') {
1130 size_t len2 = strlen(s2);
1131 size_t len1 = strlen(s1);
1132 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1133 return strncmp(s1, s2+2, len2-4);
1137 return strcmp(s1, s2);
1141 * Allocate a new gnu temporal attribute.
1143 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1144 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1145 attribute->kind = kind;
1146 attribute->next = NULL;
1147 attribute->invalid = false;
1148 attribute->have_arguments = false;
1154 * parse one constant expression argument.
1156 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1157 expression_t *expression;
1158 add_anchor_token(')');
1159 expression = parse_constant_expression();
1160 rem_anchor_token(')');
1165 attribute->invalid = true;
1169 * parse a list of constant expressions arguments.
1171 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1172 expression_t *expression;
1173 add_anchor_token(')');
1174 add_anchor_token(',');
1176 expression = parse_constant_expression();
1177 if (token.type != ',')
1181 rem_anchor_token(',');
1182 rem_anchor_token(')');
1187 attribute->invalid = true;
1191 * parse one string literal argument.
1193 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1196 add_anchor_token('(');
1197 if (token.type != T_STRING_LITERAL) {
1198 parse_error_expected("while parsing attribute directive",
1199 T_STRING_LITERAL, NULL);
1202 *string = parse_string_literals();
1203 rem_anchor_token('(');
1207 attribute->invalid = true;
1211 * parse one tls model.
1213 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1214 static const char *tls_models[] = {
1220 string_t string = { NULL, 0 };
1221 parse_gnu_attribute_string_arg(attribute, &string);
1222 if (string.begin != NULL) {
1223 for(size_t i = 0; i < 4; ++i) {
1224 if (strcmp(tls_models[i], string.begin) == 0) {
1225 attribute->u.value = i;
1229 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1231 attribute->invalid = true;
1235 * parse one tls model.
1237 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1238 static const char *visibilities[] = {
1244 string_t string = { NULL, 0 };
1245 parse_gnu_attribute_string_arg(attribute, &string);
1246 if (string.begin != NULL) {
1247 for(size_t i = 0; i < 4; ++i) {
1248 if (strcmp(visibilities[i], string.begin) == 0) {
1249 attribute->u.value = i;
1253 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1255 attribute->invalid = true;
1259 * parse one (code) model.
1261 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1262 static const char *visibilities[] = {
1267 string_t string = { NULL, 0 };
1268 parse_gnu_attribute_string_arg(attribute, &string);
1269 if (string.begin != NULL) {
1270 for(int i = 0; i < 3; ++i) {
1271 if (strcmp(visibilities[i], string.begin) == 0) {
1272 attribute->u.value = i;
1276 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1278 attribute->invalid = true;
1281 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1283 /* TODO: find out what is allowed here... */
1285 /* at least: byte, word, pointer, list of machine modes
1286 * __XXX___ is interpreted as XXX */
1287 add_anchor_token(')');
1289 if (token.type != T_IDENTIFIER) {
1290 expect(T_IDENTIFIER);
1293 /* This isn't really correct, the backend should provide a list of machine
1294 * specific modes (according to gcc philosophy that is...) */
1295 const char *symbol_str = token.v.symbol->string;
1296 if (strcmp_underscore("QI", symbol_str) == 0 ||
1297 strcmp_underscore("byte", symbol_str) == 0) {
1298 attribute->u.akind = ATOMIC_TYPE_CHAR;
1299 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1300 attribute->u.akind = ATOMIC_TYPE_SHORT;
1301 } else if (strcmp_underscore("SI", symbol_str) == 0
1302 || strcmp_underscore("word", symbol_str) == 0
1303 || strcmp_underscore("pointer", symbol_str) == 0) {
1304 attribute->u.akind = ATOMIC_TYPE_INT;
1305 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1306 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1308 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1309 attribute->invalid = true;
1313 rem_anchor_token(')');
1317 attribute->invalid = true;
1321 * parse one interrupt argument.
1323 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1324 static const char *interrupts[] = {
1331 string_t string = { NULL, 0 };
1332 parse_gnu_attribute_string_arg(attribute, &string);
1333 if (string.begin != NULL) {
1334 for(size_t i = 0; i < 5; ++i) {
1335 if (strcmp(interrupts[i], string.begin) == 0) {
1336 attribute->u.value = i;
1340 errorf(HERE, "'%s' is not an interrupt", string.begin);
1342 attribute->invalid = true;
1346 * parse ( identifier, const expression, const expression )
1348 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1349 static const char *format_names[] = {
1357 if (token.type != T_IDENTIFIER) {
1358 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1361 const char *name = token.v.symbol->string;
1362 for(i = 0; i < 4; ++i) {
1363 if (strcmp_underscore(format_names[i], name) == 0)
1367 if (warning.attribute)
1368 warningf(HERE, "'%s' is an unrecognized format function type", name);
1373 add_anchor_token(')');
1374 add_anchor_token(',');
1375 parse_constant_expression();
1376 rem_anchor_token(',');
1377 rem_anchor_token('(');
1380 add_anchor_token(')');
1381 parse_constant_expression();
1382 rem_anchor_token('(');
1386 attribute->u.value = true;
1389 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1391 if (!attribute->have_arguments)
1394 /* should have no arguments */
1395 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1396 eat_until_matching_token('(');
1397 /* we have already consumed '(', so we stop before ')', eat it */
1399 attribute->invalid = true;
1403 * Parse one GNU attribute.
1405 * Note that attribute names can be specified WITH or WITHOUT
1406 * double underscores, ie const or __const__.
1408 * The following attributes are parsed without arguments
1433 * no_instrument_function
1434 * warn_unused_result
1451 * externally_visible
1459 * The following attributes are parsed with arguments
1460 * aligned( const expression )
1461 * alias( string literal )
1462 * section( string literal )
1463 * format( identifier, const expression, const expression )
1464 * format_arg( const expression )
1465 * tls_model( string literal )
1466 * visibility( string literal )
1467 * regparm( const expression )
1468 * model( string leteral )
1469 * trap_exit( const expression )
1470 * sp_switch( string literal )
1472 * The following attributes might have arguments
1473 * weak_ref( string literal )
1474 * non_null( const expression // ',' )
1475 * interrupt( string literal )
1476 * sentinel( constant expression )
1478 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1480 gnu_attribute_t *head = *attributes;
1481 gnu_attribute_t *last = *attributes;
1482 decl_modifiers_t modifiers = 0;
1483 gnu_attribute_t *attribute;
1485 eat(T___attribute__);
1489 if (token.type != ')') {
1490 /* find the end of the list */
1492 while(last->next != NULL)
1496 /* non-empty attribute list */
1499 if (token.type == T_const) {
1501 } else if (token.type == T_volatile) {
1503 } else if (token.type == T_cdecl) {
1504 /* __attribute__((cdecl)), WITH ms mode */
1506 } else if (token.type == T_IDENTIFIER) {
1507 const symbol_t *sym = token.v.symbol;
1510 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1517 for(i = 0; i < GNU_AK_LAST; ++i) {
1518 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1521 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1524 if (kind == GNU_AK_LAST) {
1525 if (warning.attribute)
1526 warningf(HERE, "'%s' attribute directive ignored", name);
1528 /* skip possible arguments */
1529 if (token.type == '(') {
1530 eat_until_matching_token(')');
1533 /* check for arguments */
1534 attribute = allocate_gnu_attribute(kind);
1535 if (token.type == '(') {
1537 if (token.type == ')') {
1538 /* empty args are allowed */
1541 attribute->have_arguments = true;
1546 case GNU_AK_VOLATILE:
1547 case GNU_AK_DEPRECATED:
1552 case GNU_AK_NOCOMMON:
1554 case GNU_AK_NOTSHARED:
1556 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1557 case GNU_AK_WARN_UNUSED_RESULT:
1558 case GNU_AK_LONGCALL:
1559 case GNU_AK_SHORTCALL:
1560 case GNU_AK_LONG_CALL:
1561 case GNU_AK_SHORT_CALL:
1562 case GNU_AK_FUNCTION_VECTOR:
1563 case GNU_AK_INTERRUPT_HANDLER:
1564 case GNU_AK_NMI_HANDLER:
1565 case GNU_AK_NESTING:
1569 case GNU_AK_EIGTHBIT_DATA:
1570 case GNU_AK_TINY_DATA:
1571 case GNU_AK_SAVEALL:
1572 case GNU_AK_FLATTEN:
1573 case GNU_AK_SSEREGPARM:
1574 case GNU_AK_EXTERNALLY_VISIBLE:
1575 case GNU_AK_RETURN_TWICE:
1576 case GNU_AK_MAY_ALIAS:
1577 case GNU_AK_MS_STRUCT:
1578 case GNU_AK_GCC_STRUCT:
1581 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1582 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1583 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1584 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1585 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1586 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1587 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1588 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1589 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1590 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1591 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1592 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1593 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1594 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1595 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1597 case GNU_AK_ALIGNED:
1598 /* __align__ may be used without an argument */
1599 if (attribute->have_arguments) {
1600 parse_gnu_attribute_const_arg(attribute);
1604 case GNU_AK_FORMAT_ARG:
1605 case GNU_AK_REGPARM:
1606 case GNU_AK_TRAP_EXIT:
1607 if (!attribute->have_arguments) {
1608 /* should have arguments */
1609 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1610 attribute->invalid = true;
1612 parse_gnu_attribute_const_arg(attribute);
1615 case GNU_AK_SECTION:
1616 case GNU_AK_SP_SWITCH:
1617 if (!attribute->have_arguments) {
1618 /* should have arguments */
1619 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1620 attribute->invalid = true;
1622 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1625 if (!attribute->have_arguments) {
1626 /* should have arguments */
1627 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1628 attribute->invalid = true;
1630 parse_gnu_attribute_format_args(attribute);
1632 case GNU_AK_WEAKREF:
1633 /* may have one string argument */
1634 if (attribute->have_arguments)
1635 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1637 case GNU_AK_NONNULL:
1638 if (attribute->have_arguments)
1639 parse_gnu_attribute_const_arg_list(attribute);
1641 case GNU_AK_TLS_MODEL:
1642 if (!attribute->have_arguments) {
1643 /* should have arguments */
1644 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1646 parse_gnu_attribute_tls_model_arg(attribute);
1648 case GNU_AK_VISIBILITY:
1649 if (!attribute->have_arguments) {
1650 /* should have arguments */
1651 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1653 parse_gnu_attribute_visibility_arg(attribute);
1656 if (!attribute->have_arguments) {
1657 /* should have arguments */
1658 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1660 parse_gnu_attribute_model_arg(attribute);
1664 if (!attribute->have_arguments) {
1665 /* should have arguments */
1666 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1668 parse_gnu_attribute_mode_arg(attribute);
1671 case GNU_AK_INTERRUPT:
1672 /* may have one string argument */
1673 if (attribute->have_arguments)
1674 parse_gnu_attribute_interrupt_arg(attribute);
1676 case GNU_AK_SENTINEL:
1677 /* may have one string argument */
1678 if (attribute->have_arguments)
1679 parse_gnu_attribute_const_arg(attribute);
1682 /* already handled */
1686 check_no_argument(attribute, name);
1689 if (attribute != NULL) {
1691 last->next = attribute;
1694 head = last = attribute;
1698 if (token.type != ',')
1712 * Parse GNU attributes.
1714 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1716 decl_modifiers_t modifiers = 0;
1719 switch(token.type) {
1720 case T___attribute__:
1721 modifiers |= parse_gnu_attribute(attributes);
1727 if (token.type != T_STRING_LITERAL) {
1728 parse_error_expected("while parsing assembler attribute",
1729 T_STRING_LITERAL, NULL);
1730 eat_until_matching_token('(');
1733 parse_string_literals();
1738 case T_cdecl: modifiers |= DM_CDECL; break;
1739 case T__fastcall: modifiers |= DM_FASTCALL; break;
1740 case T__stdcall: modifiers |= DM_STDCALL; break;
1743 /* TODO record modifier */
1744 warningf(HERE, "Ignoring declaration modifier %K", &token);
1748 default: return modifiers;
1755 static designator_t *parse_designation(void)
1757 designator_t *result = NULL;
1758 designator_t *last = NULL;
1761 designator_t *designator;
1762 switch(token.type) {
1764 designator = allocate_ast_zero(sizeof(designator[0]));
1765 designator->source_position = token.source_position;
1767 add_anchor_token(']');
1768 designator->array_index = parse_constant_expression();
1769 rem_anchor_token(']');
1773 designator = allocate_ast_zero(sizeof(designator[0]));
1774 designator->source_position = token.source_position;
1776 if (token.type != T_IDENTIFIER) {
1777 parse_error_expected("while parsing designator",
1778 T_IDENTIFIER, NULL);
1781 designator->symbol = token.v.symbol;
1789 assert(designator != NULL);
1791 last->next = designator;
1793 result = designator;
1801 static initializer_t *initializer_from_string(array_type_t *type,
1802 const string_t *const string)
1804 /* TODO: check len vs. size of array type */
1807 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1808 initializer->string.string = *string;
1813 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1814 wide_string_t *const string)
1816 /* TODO: check len vs. size of array type */
1819 initializer_t *const initializer =
1820 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1821 initializer->wide_string.string = *string;
1827 * Build an initializer from a given expression.
1829 static initializer_t *initializer_from_expression(type_t *orig_type,
1830 expression_t *expression)
1832 /* TODO check that expression is a constant expression */
1834 /* § 6.7.8.14/15 char array may be initialized by string literals */
1835 type_t *type = skip_typeref(orig_type);
1836 type_t *expr_type_orig = expression->base.type;
1837 type_t *expr_type = skip_typeref(expr_type_orig);
1838 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1839 array_type_t *const array_type = &type->array;
1840 type_t *const element_type = skip_typeref(array_type->element_type);
1842 if (element_type->kind == TYPE_ATOMIC) {
1843 atomic_type_kind_t akind = element_type->atomic.akind;
1844 switch (expression->kind) {
1845 case EXPR_STRING_LITERAL:
1846 if (akind == ATOMIC_TYPE_CHAR
1847 || akind == ATOMIC_TYPE_SCHAR
1848 || akind == ATOMIC_TYPE_UCHAR) {
1849 return initializer_from_string(array_type,
1850 &expression->string.value);
1853 case EXPR_WIDE_STRING_LITERAL: {
1854 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1855 if (get_unqualified_type(element_type) == bare_wchar_type) {
1856 return initializer_from_wide_string(array_type,
1857 &expression->wide_string.value);
1867 assign_error_t error = semantic_assign(type, expression);
1868 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1870 report_assign_error(error, type, expression, "initializer",
1871 &expression->base.source_position);
1873 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1874 result->value.value = create_implicit_cast(expression, type);
1880 * Checks if a given expression can be used as an constant initializer.
1882 static bool is_initializer_constant(const expression_t *expression)
1884 return is_constant_expression(expression)
1885 || is_address_constant(expression);
1889 * Parses an scalar initializer.
1891 * § 6.7.8.11; eat {} without warning
1893 static initializer_t *parse_scalar_initializer(type_t *type,
1894 bool must_be_constant)
1896 /* there might be extra {} hierarchies */
1898 if (token.type == '{') {
1899 warningf(HERE, "extra curly braces around scalar initializer");
1903 } while (token.type == '{');
1906 expression_t *expression = parse_assignment_expression();
1907 if (must_be_constant && !is_initializer_constant(expression)) {
1908 errorf(&expression->base.source_position,
1909 "Initialisation expression '%E' is not constant\n",
1913 initializer_t *initializer = initializer_from_expression(type, expression);
1915 if (initializer == NULL) {
1916 errorf(&expression->base.source_position,
1917 "expression '%E' (type '%T') doesn't match expected type '%T'",
1918 expression, expression->base.type, type);
1923 bool additional_warning_displayed = false;
1925 if (token.type == ',') {
1928 if (token.type != '}') {
1929 if (!additional_warning_displayed) {
1930 warningf(HERE, "additional elements in scalar initializer");
1931 additional_warning_displayed = true;
1942 * An entry in the type path.
1944 typedef struct type_path_entry_t type_path_entry_t;
1945 struct type_path_entry_t {
1946 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1948 size_t index; /**< For array types: the current index. */
1949 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1954 * A type path expression a position inside compound or array types.
1956 typedef struct type_path_t type_path_t;
1957 struct type_path_t {
1958 type_path_entry_t *path; /**< An flexible array containing the current path. */
1959 type_t *top_type; /**< type of the element the path points */
1960 size_t max_index; /**< largest index in outermost array */
1964 * Prints a type path for debugging.
1966 static __attribute__((unused)) void debug_print_type_path(
1967 const type_path_t *path)
1969 size_t len = ARR_LEN(path->path);
1971 for(size_t i = 0; i < len; ++i) {
1972 const type_path_entry_t *entry = & path->path[i];
1974 type_t *type = skip_typeref(entry->type);
1975 if (is_type_compound(type)) {
1976 /* in gcc mode structs can have no members */
1977 if (entry->v.compound_entry == NULL) {
1981 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1982 } else if (is_type_array(type)) {
1983 fprintf(stderr, "[%zd]", entry->v.index);
1985 fprintf(stderr, "-INVALID-");
1988 if (path->top_type != NULL) {
1989 fprintf(stderr, " (");
1990 print_type(path->top_type);
1991 fprintf(stderr, ")");
1996 * Return the top type path entry, ie. in a path
1997 * (type).a.b returns the b.
1999 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2001 size_t len = ARR_LEN(path->path);
2003 return &path->path[len-1];
2007 * Enlarge the type path by an (empty) element.
2009 static type_path_entry_t *append_to_type_path(type_path_t *path)
2011 size_t len = ARR_LEN(path->path);
2012 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2014 type_path_entry_t *result = & path->path[len];
2015 memset(result, 0, sizeof(result[0]));
2020 * Descending into a sub-type. Enter the scope of the current
2023 static void descend_into_subtype(type_path_t *path)
2025 type_t *orig_top_type = path->top_type;
2026 type_t *top_type = skip_typeref(orig_top_type);
2028 assert(is_type_compound(top_type) || is_type_array(top_type));
2030 type_path_entry_t *top = append_to_type_path(path);
2031 top->type = top_type;
2033 if (is_type_compound(top_type)) {
2034 declaration_t *declaration = top_type->compound.declaration;
2035 declaration_t *entry = declaration->scope.declarations;
2036 top->v.compound_entry = entry;
2038 if (entry != NULL) {
2039 path->top_type = entry->type;
2041 path->top_type = NULL;
2044 assert(is_type_array(top_type));
2047 path->top_type = top_type->array.element_type;
2052 * Pop an entry from the given type path, ie. returning from
2053 * (type).a.b to (type).a
2055 static void ascend_from_subtype(type_path_t *path)
2057 type_path_entry_t *top = get_type_path_top(path);
2059 path->top_type = top->type;
2061 size_t len = ARR_LEN(path->path);
2062 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2066 * Pop entries from the given type path until the given
2067 * path level is reached.
2069 static void ascend_to(type_path_t *path, size_t top_path_level)
2071 size_t len = ARR_LEN(path->path);
2073 while(len > top_path_level) {
2074 ascend_from_subtype(path);
2075 len = ARR_LEN(path->path);
2079 static bool walk_designator(type_path_t *path, const designator_t *designator,
2080 bool used_in_offsetof)
2082 for( ; designator != NULL; designator = designator->next) {
2083 type_path_entry_t *top = get_type_path_top(path);
2084 type_t *orig_type = top->type;
2086 type_t *type = skip_typeref(orig_type);
2088 if (designator->symbol != NULL) {
2089 symbol_t *symbol = designator->symbol;
2090 if (!is_type_compound(type)) {
2091 if (is_type_valid(type)) {
2092 errorf(&designator->source_position,
2093 "'.%Y' designator used for non-compound type '%T'",
2099 declaration_t *declaration = type->compound.declaration;
2100 declaration_t *iter = declaration->scope.declarations;
2101 for( ; iter != NULL; iter = iter->next) {
2102 if (iter->symbol == symbol) {
2107 errorf(&designator->source_position,
2108 "'%T' has no member named '%Y'", orig_type, symbol);
2111 if (used_in_offsetof) {
2112 type_t *real_type = skip_typeref(iter->type);
2113 if (real_type->kind == TYPE_BITFIELD) {
2114 errorf(&designator->source_position,
2115 "offsetof designator '%Y' may not specify bitfield",
2121 top->type = orig_type;
2122 top->v.compound_entry = iter;
2123 orig_type = iter->type;
2125 expression_t *array_index = designator->array_index;
2126 assert(designator->array_index != NULL);
2128 if (!is_type_array(type)) {
2129 if (is_type_valid(type)) {
2130 errorf(&designator->source_position,
2131 "[%E] designator used for non-array type '%T'",
2132 array_index, orig_type);
2136 if (!is_type_valid(array_index->base.type)) {
2140 long index = fold_constant(array_index);
2141 if (!used_in_offsetof) {
2143 errorf(&designator->source_position,
2144 "array index [%E] must be positive", array_index);
2147 if (type->array.size_constant == true) {
2148 long array_size = type->array.size;
2149 if (index >= array_size) {
2150 errorf(&designator->source_position,
2151 "designator [%E] (%d) exceeds array size %d",
2152 array_index, index, array_size);
2158 top->type = orig_type;
2159 top->v.index = (size_t) index;
2160 orig_type = type->array.element_type;
2162 path->top_type = orig_type;
2164 if (designator->next != NULL) {
2165 descend_into_subtype(path);
2174 static void advance_current_object(type_path_t *path, size_t top_path_level)
2176 type_path_entry_t *top = get_type_path_top(path);
2178 type_t *type = skip_typeref(top->type);
2179 if (is_type_union(type)) {
2180 /* in unions only the first element is initialized */
2181 top->v.compound_entry = NULL;
2182 } else if (is_type_struct(type)) {
2183 declaration_t *entry = top->v.compound_entry;
2185 entry = entry->next;
2186 top->v.compound_entry = entry;
2187 if (entry != NULL) {
2188 path->top_type = entry->type;
2192 assert(is_type_array(type));
2196 if (!type->array.size_constant || top->v.index < type->array.size) {
2201 /* we're past the last member of the current sub-aggregate, try if we
2202 * can ascend in the type hierarchy and continue with another subobject */
2203 size_t len = ARR_LEN(path->path);
2205 if (len > top_path_level) {
2206 ascend_from_subtype(path);
2207 advance_current_object(path, top_path_level);
2209 path->top_type = NULL;
2214 * skip until token is found.
2216 static void skip_until(int type) {
2217 while(token.type != type) {
2218 if (token.type == T_EOF)
2225 * skip any {...} blocks until a closing bracket is reached.
2227 static void skip_initializers(void)
2229 if (token.type == '{')
2232 while(token.type != '}') {
2233 if (token.type == T_EOF)
2235 if (token.type == '{') {
2243 static initializer_t *create_empty_initializer(void)
2245 static initializer_t empty_initializer
2246 = { .list = { { INITIALIZER_LIST }, 0 } };
2247 return &empty_initializer;
2251 * Parse a part of an initialiser for a struct or union,
2253 static initializer_t *parse_sub_initializer(type_path_t *path,
2254 type_t *outer_type, size_t top_path_level,
2255 parse_initializer_env_t *env)
2257 if (token.type == '}') {
2258 /* empty initializer */
2259 return create_empty_initializer();
2262 type_t *orig_type = path->top_type;
2263 type_t *type = NULL;
2265 if (orig_type == NULL) {
2266 /* We are initializing an empty compound. */
2268 type = skip_typeref(orig_type);
2270 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2271 * initializers in this case. */
2272 if (!is_type_valid(type)) {
2273 skip_initializers();
2274 return create_empty_initializer();
2278 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2281 designator_t *designator = NULL;
2282 if (token.type == '.' || token.type == '[') {
2283 designator = parse_designation();
2285 /* reset path to toplevel, evaluate designator from there */
2286 ascend_to(path, top_path_level);
2287 if (!walk_designator(path, designator, false)) {
2288 /* can't continue after designation error */
2292 initializer_t *designator_initializer
2293 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2294 designator_initializer->designator.designator = designator;
2295 ARR_APP1(initializer_t*, initializers, designator_initializer);
2297 orig_type = path->top_type;
2298 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2303 if (token.type == '{') {
2304 if (type != NULL && is_type_scalar(type)) {
2305 sub = parse_scalar_initializer(type, env->must_be_constant);
2309 if (env->declaration != NULL) {
2310 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2311 env->declaration->symbol);
2313 errorf(HERE, "extra brace group at end of initializer");
2316 descend_into_subtype(path);
2318 add_anchor_token('}');
2319 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2321 rem_anchor_token('}');
2324 ascend_from_subtype(path);
2328 goto error_parse_next;
2332 /* must be an expression */
2333 expression_t *expression = parse_assignment_expression();
2335 if (env->must_be_constant && !is_initializer_constant(expression)) {
2336 errorf(&expression->base.source_position,
2337 "Initialisation expression '%E' is not constant\n",
2342 /* we are already outside, ... */
2346 /* handle { "string" } special case */
2347 if ((expression->kind == EXPR_STRING_LITERAL
2348 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2349 && outer_type != NULL) {
2350 sub = initializer_from_expression(outer_type, expression);
2352 if (token.type == ',') {
2355 if (token.type != '}') {
2356 warningf(HERE, "excessive elements in initializer for type '%T'",
2359 /* TODO: eat , ... */
2364 /* descend into subtypes until expression matches type */
2366 orig_type = path->top_type;
2367 type = skip_typeref(orig_type);
2369 sub = initializer_from_expression(orig_type, expression);
2373 if (!is_type_valid(type)) {
2376 if (is_type_scalar(type)) {
2377 errorf(&expression->base.source_position,
2378 "expression '%E' doesn't match expected type '%T'",
2379 expression, orig_type);
2383 descend_into_subtype(path);
2387 /* update largest index of top array */
2388 const type_path_entry_t *first = &path->path[0];
2389 type_t *first_type = first->type;
2390 first_type = skip_typeref(first_type);
2391 if (is_type_array(first_type)) {
2392 size_t index = first->v.index;
2393 if (index > path->max_index)
2394 path->max_index = index;
2398 /* append to initializers list */
2399 ARR_APP1(initializer_t*, initializers, sub);
2402 if (env->declaration != NULL)
2403 warningf(HERE, "excess elements in struct initializer for '%Y'",
2404 env->declaration->symbol);
2406 warningf(HERE, "excess elements in struct initializer");
2410 if (token.type == '}') {
2414 if (token.type == '}') {
2419 /* advance to the next declaration if we are not at the end */
2420 advance_current_object(path, top_path_level);
2421 orig_type = path->top_type;
2422 if (orig_type != NULL)
2423 type = skip_typeref(orig_type);
2429 size_t len = ARR_LEN(initializers);
2430 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2431 initializer_t *result = allocate_ast_zero(size);
2432 result->kind = INITIALIZER_LIST;
2433 result->list.len = len;
2434 memcpy(&result->list.initializers, initializers,
2435 len * sizeof(initializers[0]));
2437 DEL_ARR_F(initializers);
2438 ascend_to(path, top_path_level+1);
2443 skip_initializers();
2444 DEL_ARR_F(initializers);
2445 ascend_to(path, top_path_level+1);
2450 * Parses an initializer. Parsers either a compound literal
2451 * (env->declaration == NULL) or an initializer of a declaration.
2453 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2455 type_t *type = skip_typeref(env->type);
2456 initializer_t *result = NULL;
2459 if (is_type_scalar(type)) {
2460 result = parse_scalar_initializer(type, env->must_be_constant);
2461 } else if (token.type == '{') {
2465 memset(&path, 0, sizeof(path));
2466 path.top_type = env->type;
2467 path.path = NEW_ARR_F(type_path_entry_t, 0);
2469 descend_into_subtype(&path);
2471 add_anchor_token('}');
2472 result = parse_sub_initializer(&path, env->type, 1, env);
2473 rem_anchor_token('}');
2475 max_index = path.max_index;
2476 DEL_ARR_F(path.path);
2480 /* parse_scalar_initializer() also works in this case: we simply
2481 * have an expression without {} around it */
2482 result = parse_scalar_initializer(type, env->must_be_constant);
2485 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2486 * the array type size */
2487 if (is_type_array(type) && type->array.size_expression == NULL
2488 && result != NULL) {
2490 switch (result->kind) {
2491 case INITIALIZER_LIST:
2492 size = max_index + 1;
2495 case INITIALIZER_STRING:
2496 size = result->string.string.size;
2499 case INITIALIZER_WIDE_STRING:
2500 size = result->wide_string.string.size;
2503 case INITIALIZER_DESIGNATOR:
2504 case INITIALIZER_VALUE:
2505 /* can happen for parse errors */
2510 internal_errorf(HERE, "invalid initializer type");
2513 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2514 cnst->base.type = type_size_t;
2515 cnst->conste.v.int_value = size;
2517 type_t *new_type = duplicate_type(type);
2519 new_type->array.size_expression = cnst;
2520 new_type->array.size_constant = true;
2521 new_type->array.size = size;
2522 env->type = new_type;
2530 static declaration_t *append_declaration(declaration_t *declaration);
2532 static declaration_t *parse_compound_type_specifier(bool is_struct)
2534 gnu_attribute_t *attributes = NULL;
2535 decl_modifiers_t modifiers = 0;
2542 symbol_t *symbol = NULL;
2543 declaration_t *declaration = NULL;
2545 if (token.type == T___attribute__) {
2546 modifiers |= parse_attributes(&attributes);
2549 if (token.type == T_IDENTIFIER) {
2550 symbol = token.v.symbol;
2553 namespace_t const namespc =
2554 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2555 declaration = get_declaration(symbol, namespc);
2556 if (declaration != NULL) {
2557 if (declaration->parent_scope != scope &&
2558 (token.type == '{' || token.type == ';')) {
2560 } else if (declaration->init.complete &&
2561 token.type == '{') {
2562 assert(symbol != NULL);
2563 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2564 is_struct ? "struct" : "union", symbol,
2565 &declaration->source_position);
2566 declaration->scope.declarations = NULL;
2569 } else if (token.type != '{') {
2571 parse_error_expected("while parsing struct type specifier",
2572 T_IDENTIFIER, '{', NULL);
2574 parse_error_expected("while parsing union type specifier",
2575 T_IDENTIFIER, '{', NULL);
2581 if (declaration == NULL) {
2582 declaration = allocate_declaration_zero();
2583 declaration->namespc =
2584 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2585 declaration->source_position = token.source_position;
2586 declaration->symbol = symbol;
2587 declaration->parent_scope = scope;
2588 if (symbol != NULL) {
2589 environment_push(declaration);
2591 append_declaration(declaration);
2594 if (token.type == '{') {
2595 declaration->init.complete = true;
2597 parse_compound_type_entries(declaration);
2598 modifiers |= parse_attributes(&attributes);
2601 declaration->modifiers |= modifiers;
2605 static void parse_enum_entries(type_t *const enum_type)
2609 if (token.type == '}') {
2611 errorf(HERE, "empty enum not allowed");
2615 add_anchor_token('}');
2617 if (token.type != T_IDENTIFIER) {
2618 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2620 rem_anchor_token('}');
2624 declaration_t *const entry = allocate_declaration_zero();
2625 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2626 entry->type = enum_type;
2627 entry->symbol = token.v.symbol;
2628 entry->source_position = token.source_position;
2631 if (token.type == '=') {
2633 expression_t *value = parse_constant_expression();
2635 value = create_implicit_cast(value, enum_type);
2636 entry->init.enum_value = value;
2641 record_declaration(entry);
2643 if (token.type != ',')
2646 } while(token.type != '}');
2647 rem_anchor_token('}');
2655 static type_t *parse_enum_specifier(void)
2657 gnu_attribute_t *attributes = NULL;
2658 declaration_t *declaration;
2662 if (token.type == T_IDENTIFIER) {
2663 symbol = token.v.symbol;
2666 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2667 } else if (token.type != '{') {
2668 parse_error_expected("while parsing enum type specifier",
2669 T_IDENTIFIER, '{', NULL);
2676 if (declaration == NULL) {
2677 declaration = allocate_declaration_zero();
2678 declaration->namespc = NAMESPACE_ENUM;
2679 declaration->source_position = token.source_position;
2680 declaration->symbol = symbol;
2681 declaration->parent_scope = scope;
2684 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2685 type->enumt.declaration = declaration;
2687 if (token.type == '{') {
2688 if (declaration->init.complete) {
2689 errorf(HERE, "multiple definitions of enum %Y", symbol);
2691 if (symbol != NULL) {
2692 environment_push(declaration);
2694 append_declaration(declaration);
2695 declaration->init.complete = true;
2697 parse_enum_entries(type);
2698 parse_attributes(&attributes);
2705 * if a symbol is a typedef to another type, return true
2707 static bool is_typedef_symbol(symbol_t *symbol)
2709 const declaration_t *const declaration =
2710 get_declaration(symbol, NAMESPACE_NORMAL);
2712 declaration != NULL &&
2713 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2716 static type_t *parse_typeof(void)
2723 add_anchor_token(')');
2725 expression_t *expression = NULL;
2728 switch(token.type) {
2729 case T___extension__:
2730 /* this can be a prefix to a typename or an expression */
2731 /* we simply eat it now. */
2734 } while(token.type == T___extension__);
2738 if (is_typedef_symbol(token.v.symbol)) {
2739 type = parse_typename();
2741 expression = parse_expression();
2742 type = expression->base.type;
2747 type = parse_typename();
2751 expression = parse_expression();
2752 type = expression->base.type;
2756 rem_anchor_token(')');
2759 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2760 typeof_type->typeoft.expression = expression;
2761 typeof_type->typeoft.typeof_type = type;
2768 typedef enum specifiers_t {
2769 SPECIFIER_SIGNED = 1 << 0,
2770 SPECIFIER_UNSIGNED = 1 << 1,
2771 SPECIFIER_LONG = 1 << 2,
2772 SPECIFIER_INT = 1 << 3,
2773 SPECIFIER_DOUBLE = 1 << 4,
2774 SPECIFIER_CHAR = 1 << 5,
2775 SPECIFIER_SHORT = 1 << 6,
2776 SPECIFIER_LONG_LONG = 1 << 7,
2777 SPECIFIER_FLOAT = 1 << 8,
2778 SPECIFIER_BOOL = 1 << 9,
2779 SPECIFIER_VOID = 1 << 10,
2780 SPECIFIER_INT8 = 1 << 11,
2781 SPECIFIER_INT16 = 1 << 12,
2782 SPECIFIER_INT32 = 1 << 13,
2783 SPECIFIER_INT64 = 1 << 14,
2784 SPECIFIER_INT128 = 1 << 15,
2785 SPECIFIER_COMPLEX = 1 << 16,
2786 SPECIFIER_IMAGINARY = 1 << 17,
2789 static type_t *create_builtin_type(symbol_t *const symbol,
2790 type_t *const real_type)
2792 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2793 type->builtin.symbol = symbol;
2794 type->builtin.real_type = real_type;
2796 type_t *result = typehash_insert(type);
2797 if (type != result) {
2804 static type_t *get_typedef_type(symbol_t *symbol)
2806 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2807 if (declaration == NULL ||
2808 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2811 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2812 type->typedeft.declaration = declaration;
2818 * check for the allowed MS alignment values.
2820 static bool check_elignment_value(long long intvalue) {
2821 if (intvalue < 1 || intvalue > 8192) {
2822 errorf(HERE, "illegal alignment value");
2825 unsigned v = (unsigned)intvalue;
2826 for(unsigned i = 1; i <= 8192; i += i) {
2830 errorf(HERE, "alignment must be power of two");
2834 #define DET_MOD(name, tag) do { \
2835 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2836 *modifiers |= tag; \
2839 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2841 decl_modifiers_t *modifiers = &specifiers->modifiers;
2844 if (token.type == T_restrict) {
2846 DET_MOD(restrict, DM_RESTRICT);
2848 } else if (token.type != T_IDENTIFIER)
2850 symbol_t *symbol = token.v.symbol;
2851 if (symbol == sym_align) {
2854 if (token.type != T_INTEGER)
2856 if (check_elignment_value(token.v.intvalue)) {
2857 if (specifiers->alignment != 0)
2858 warningf(HERE, "align used more than once");
2859 specifiers->alignment = (unsigned char)token.v.intvalue;
2863 } else if (symbol == sym_allocate) {
2866 if (token.type != T_IDENTIFIER)
2868 (void)token.v.symbol;
2870 } else if (symbol == sym_dllimport) {
2872 DET_MOD(dllimport, DM_DLLIMPORT);
2873 } else if (symbol == sym_dllexport) {
2875 DET_MOD(dllexport, DM_DLLEXPORT);
2876 } else if (symbol == sym_thread) {
2878 DET_MOD(thread, DM_THREAD);
2879 } else if (symbol == sym_naked) {
2881 DET_MOD(naked, DM_NAKED);
2882 } else if (symbol == sym_noinline) {
2884 DET_MOD(noinline, DM_NOINLINE);
2885 } else if (symbol == sym_noreturn) {
2887 DET_MOD(noreturn, DM_NORETURN);
2888 } else if (symbol == sym_nothrow) {
2890 DET_MOD(nothrow, DM_NOTHROW);
2891 } else if (symbol == sym_novtable) {
2893 DET_MOD(novtable, DM_NOVTABLE);
2894 } else if (symbol == sym_property) {
2898 bool is_get = false;
2899 if (token.type != T_IDENTIFIER)
2901 if (token.v.symbol == sym_get) {
2903 } else if (token.v.symbol == sym_put) {
2905 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2910 if (token.type != T_IDENTIFIER)
2913 if (specifiers->get_property_sym != NULL) {
2914 errorf(HERE, "get property name already specified");
2916 specifiers->get_property_sym = token.v.symbol;
2919 if (specifiers->put_property_sym != NULL) {
2920 errorf(HERE, "put property name already specified");
2922 specifiers->put_property_sym = token.v.symbol;
2926 if (token.type == ',') {
2933 } else if (symbol == sym_selectany) {
2935 DET_MOD(selectany, DM_SELECTANY);
2936 } else if (symbol == sym_uuid) {
2939 if (token.type != T_STRING_LITERAL)
2943 } else if (symbol == sym_deprecated) {
2945 if (specifiers->deprecated != 0)
2946 warningf(HERE, "deprecated used more than once");
2947 specifiers->deprecated = 1;
2948 if (token.type == '(') {
2950 if (token.type == T_STRING_LITERAL) {
2951 specifiers->deprecated_string = token.v.string.begin;
2954 errorf(HERE, "string literal expected");
2958 } else if (symbol == sym_noalias) {
2960 DET_MOD(noalias, DM_NOALIAS);
2962 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2964 if (token.type == '(')
2968 if (token.type == ',')
2975 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2977 type_t *type = NULL;
2978 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2979 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2980 unsigned type_specifiers = 0;
2983 specifiers->source_position = token.source_position;
2986 specifiers->modifiers
2987 |= parse_attributes(&specifiers->gnu_attributes);
2988 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
2989 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
2991 switch(token.type) {
2994 #define MATCH_STORAGE_CLASS(token, class) \
2996 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2997 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2999 specifiers->declared_storage_class = class; \
3003 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3004 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3005 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3006 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3007 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3012 add_anchor_token(')');
3013 parse_microsoft_extended_decl_modifier(specifiers);
3014 rem_anchor_token(')');
3019 switch (specifiers->declared_storage_class) {
3020 case STORAGE_CLASS_NONE:
3021 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3024 case STORAGE_CLASS_EXTERN:
3025 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3028 case STORAGE_CLASS_STATIC:
3029 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3033 errorf(HERE, "multiple storage classes in declaration specifiers");
3039 /* type qualifiers */
3040 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3042 qualifiers |= qualifier; \
3046 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3047 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3048 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3049 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3050 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3051 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3052 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3053 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3055 case T___extension__:
3060 /* type specifiers */
3061 #define MATCH_SPECIFIER(token, specifier, name) \
3064 if (type_specifiers & specifier) { \
3065 errorf(HERE, "multiple " name " type specifiers given"); \
3067 type_specifiers |= specifier; \
3071 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3072 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3073 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3074 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3075 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3076 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3077 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3078 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3079 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3080 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3081 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3082 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3083 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3084 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3085 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3086 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3088 case T__forceinline:
3089 /* only in microsoft mode */
3090 specifiers->modifiers |= DM_FORCEINLINE;
3094 specifiers->is_inline = true;
3099 if (type_specifiers & SPECIFIER_LONG_LONG) {
3100 errorf(HERE, "multiple type specifiers given");
3101 } else if (type_specifiers & SPECIFIER_LONG) {
3102 type_specifiers |= SPECIFIER_LONG_LONG;
3104 type_specifiers |= SPECIFIER_LONG;
3109 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3111 type->compound.declaration = parse_compound_type_specifier(true);
3115 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3116 type->compound.declaration = parse_compound_type_specifier(false);
3117 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3118 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3122 type = parse_enum_specifier();
3125 type = parse_typeof();
3127 case T___builtin_va_list:
3128 type = duplicate_type(type_valist);
3132 case T_IDENTIFIER: {
3133 /* only parse identifier if we haven't found a type yet */
3134 if (type != NULL || type_specifiers != 0)
3135 goto finish_specifiers;
3137 type_t *typedef_type = get_typedef_type(token.v.symbol);
3139 if (typedef_type == NULL)
3140 goto finish_specifiers;
3143 type = typedef_type;
3147 /* function specifier */
3149 goto finish_specifiers;
3156 atomic_type_kind_t atomic_type;
3158 /* match valid basic types */
3159 switch(type_specifiers) {
3160 case SPECIFIER_VOID:
3161 atomic_type = ATOMIC_TYPE_VOID;
3163 case SPECIFIER_CHAR:
3164 atomic_type = ATOMIC_TYPE_CHAR;
3166 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3167 atomic_type = ATOMIC_TYPE_SCHAR;
3169 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3170 atomic_type = ATOMIC_TYPE_UCHAR;
3172 case SPECIFIER_SHORT:
3173 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3174 case SPECIFIER_SHORT | SPECIFIER_INT:
3175 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3176 atomic_type = ATOMIC_TYPE_SHORT;
3178 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3179 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3180 atomic_type = ATOMIC_TYPE_USHORT;
3183 case SPECIFIER_SIGNED:
3184 case SPECIFIER_SIGNED | SPECIFIER_INT:
3185 atomic_type = ATOMIC_TYPE_INT;
3187 case SPECIFIER_UNSIGNED:
3188 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3189 atomic_type = ATOMIC_TYPE_UINT;
3191 case SPECIFIER_LONG:
3192 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3193 case SPECIFIER_LONG | SPECIFIER_INT:
3194 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3195 atomic_type = ATOMIC_TYPE_LONG;
3197 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3198 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3199 atomic_type = ATOMIC_TYPE_ULONG;
3201 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3202 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3203 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3204 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3206 atomic_type = ATOMIC_TYPE_LONGLONG;
3208 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3209 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3211 atomic_type = ATOMIC_TYPE_ULONGLONG;
3214 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3215 atomic_type = unsigned_int8_type_kind;
3218 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3219 atomic_type = unsigned_int16_type_kind;
3222 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3223 atomic_type = unsigned_int32_type_kind;
3226 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3227 atomic_type = unsigned_int64_type_kind;
3230 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3231 atomic_type = unsigned_int128_type_kind;
3234 case SPECIFIER_INT8:
3235 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3236 atomic_type = int8_type_kind;
3239 case SPECIFIER_INT16:
3240 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3241 atomic_type = int16_type_kind;
3244 case SPECIFIER_INT32:
3245 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3246 atomic_type = int32_type_kind;
3249 case SPECIFIER_INT64:
3250 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3251 atomic_type = int64_type_kind;
3254 case SPECIFIER_INT128:
3255 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3256 atomic_type = int128_type_kind;
3259 case SPECIFIER_FLOAT:
3260 atomic_type = ATOMIC_TYPE_FLOAT;
3262 case SPECIFIER_DOUBLE:
3263 atomic_type = ATOMIC_TYPE_DOUBLE;
3265 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3266 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3268 case SPECIFIER_BOOL:
3269 atomic_type = ATOMIC_TYPE_BOOL;
3271 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3272 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3273 atomic_type = ATOMIC_TYPE_FLOAT;
3275 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3276 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3277 atomic_type = ATOMIC_TYPE_DOUBLE;
3279 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3280 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3281 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3284 /* invalid specifier combination, give an error message */
3285 if (type_specifiers == 0) {
3286 if (! strict_mode) {
3287 if (warning.implicit_int) {
3288 warningf(HERE, "no type specifiers in declaration, using 'int'");
3290 atomic_type = ATOMIC_TYPE_INT;
3293 errorf(HERE, "no type specifiers given in declaration");
3295 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3296 (type_specifiers & SPECIFIER_UNSIGNED)) {
3297 errorf(HERE, "signed and unsigned specifiers gives");
3298 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3299 errorf(HERE, "only integer types can be signed or unsigned");
3301 errorf(HERE, "multiple datatypes in declaration");
3303 atomic_type = ATOMIC_TYPE_INVALID;
3306 if (type_specifiers & SPECIFIER_COMPLEX &&
3307 atomic_type != ATOMIC_TYPE_INVALID) {
3308 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3309 type->complex.akind = atomic_type;
3310 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3311 atomic_type != ATOMIC_TYPE_INVALID) {
3312 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3313 type->imaginary.akind = atomic_type;
3315 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3316 type->atomic.akind = atomic_type;
3320 if (type_specifiers != 0) {
3321 errorf(HERE, "multiple datatypes in declaration");
3325 /* FIXME: check type qualifiers here */
3327 type->base.qualifiers = qualifiers;
3328 type->base.modifiers = modifiers;
3330 type_t *result = typehash_insert(type);
3331 if (newtype && result != type) {
3335 specifiers->type = result;
3340 static type_qualifiers_t parse_type_qualifiers(void)
3342 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3345 switch(token.type) {
3346 /* type qualifiers */
3347 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3348 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3349 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3350 /* microsoft extended type modifiers */
3351 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3352 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3353 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3354 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3355 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3363 static declaration_t *parse_identifier_list(void)
3365 declaration_t *declarations = NULL;
3366 declaration_t *last_declaration = NULL;
3368 declaration_t *const declaration = allocate_declaration_zero();
3369 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3370 declaration->source_position = token.source_position;
3371 declaration->symbol = token.v.symbol;
3374 if (last_declaration != NULL) {
3375 last_declaration->next = declaration;
3377 declarations = declaration;
3379 last_declaration = declaration;
3381 if (token.type != ',') {
3385 } while(token.type == T_IDENTIFIER);
3387 return declarations;
3390 static type_t *automatic_type_conversion(type_t *orig_type);
3392 static void semantic_parameter(declaration_t *declaration)
3394 /* TODO: improve error messages */
3396 if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3397 errorf(HERE, "typedef not allowed in parameter list");
3398 } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3399 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3400 errorf(HERE, "parameter may only have none or register storage class");
3403 type_t *const orig_type = declaration->type;
3404 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3405 * sugar. Turn it into a pointer.
3406 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3407 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3409 type_t *const type = automatic_type_conversion(orig_type);
3410 declaration->type = type;
3412 if (is_type_incomplete(skip_typeref(type))) {
3413 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3414 orig_type, declaration->symbol);
3418 static declaration_t *parse_parameter(void)
3420 declaration_specifiers_t specifiers;
3421 memset(&specifiers, 0, sizeof(specifiers));
3423 parse_declaration_specifiers(&specifiers);
3425 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3430 static declaration_t *parse_parameters(function_type_t *type)
3432 declaration_t *declarations = NULL;
3435 add_anchor_token(')');
3436 int saved_comma_state = save_and_reset_anchor_state(',');
3438 if (token.type == T_IDENTIFIER) {
3439 symbol_t *symbol = token.v.symbol;
3440 if (!is_typedef_symbol(symbol)) {
3441 type->kr_style_parameters = true;
3442 declarations = parse_identifier_list();
3443 goto parameters_finished;
3447 if (token.type == ')') {
3448 type->unspecified_parameters = 1;
3449 goto parameters_finished;
3452 declaration_t *declaration;
3453 declaration_t *last_declaration = NULL;
3454 function_parameter_t *parameter;
3455 function_parameter_t *last_parameter = NULL;
3458 switch(token.type) {
3462 goto parameters_finished;
3465 case T___extension__:
3467 declaration = parse_parameter();
3469 /* func(void) is not a parameter */
3470 if (last_parameter == NULL
3471 && token.type == ')'
3472 && declaration->symbol == NULL
3473 && skip_typeref(declaration->type) == type_void) {
3474 goto parameters_finished;
3476 semantic_parameter(declaration);
3478 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3479 memset(parameter, 0, sizeof(parameter[0]));
3480 parameter->type = declaration->type;
3482 if (last_parameter != NULL) {
3483 last_declaration->next = declaration;
3484 last_parameter->next = parameter;
3486 type->parameters = parameter;
3487 declarations = declaration;
3489 last_parameter = parameter;
3490 last_declaration = declaration;
3494 goto parameters_finished;
3496 if (token.type != ',') {
3497 goto parameters_finished;
3503 parameters_finished:
3504 rem_anchor_token(')');
3507 restore_anchor_state(',', saved_comma_state);
3508 return declarations;
3511 restore_anchor_state(',', saved_comma_state);
3515 typedef enum construct_type_kind_t {
3520 } construct_type_kind_t;
3522 typedef struct construct_type_t construct_type_t;
3523 struct construct_type_t {
3524 construct_type_kind_t kind;
3525 construct_type_t *next;
3528 typedef struct parsed_pointer_t parsed_pointer_t;
3529 struct parsed_pointer_t {
3530 construct_type_t construct_type;
3531 type_qualifiers_t type_qualifiers;
3534 typedef struct construct_function_type_t construct_function_type_t;
3535 struct construct_function_type_t {
3536 construct_type_t construct_type;
3537 type_t *function_type;
3540 typedef struct parsed_array_t parsed_array_t;
3541 struct parsed_array_t {
3542 construct_type_t construct_type;
3543 type_qualifiers_t type_qualifiers;
3549 typedef struct construct_base_type_t construct_base_type_t;
3550 struct construct_base_type_t {
3551 construct_type_t construct_type;
3555 static construct_type_t *parse_pointer_declarator(void)
3559 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3560 memset(pointer, 0, sizeof(pointer[0]));
3561 pointer->construct_type.kind = CONSTRUCT_POINTER;
3562 pointer->type_qualifiers = parse_type_qualifiers();
3564 return (construct_type_t*) pointer;
3567 static construct_type_t *parse_array_declarator(void)
3570 add_anchor_token(']');
3572 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3573 memset(array, 0, sizeof(array[0]));
3574 array->construct_type.kind = CONSTRUCT_ARRAY;
3576 if (token.type == T_static) {
3577 array->is_static = true;
3581 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3582 if (type_qualifiers != 0) {
3583 if (token.type == T_static) {
3584 array->is_static = true;
3588 array->type_qualifiers = type_qualifiers;
3590 if (token.type == '*' && look_ahead(1)->type == ']') {
3591 array->is_variable = true;
3593 } else if (token.type != ']') {
3594 array->size = parse_assignment_expression();
3597 rem_anchor_token(']');
3600 return (construct_type_t*) array;
3605 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3608 if (declaration != NULL) {
3609 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3611 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3614 declaration_t *parameters = parse_parameters(&type->function);
3615 if (declaration != NULL) {
3616 declaration->scope.declarations = parameters;
3619 construct_function_type_t *construct_function_type =
3620 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3621 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3622 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3623 construct_function_type->function_type = type;
3625 return (construct_type_t*) construct_function_type;
3628 static void fix_declaration_type(declaration_t *declaration)
3630 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3631 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3633 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3634 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3636 if (declaration->type->base.modifiers == type_modifiers)
3639 type_t *copy = duplicate_type(declaration->type);
3640 copy->base.modifiers = type_modifiers;
3642 type_t *result = typehash_insert(copy);
3643 if (result != copy) {
3644 obstack_free(type_obst, copy);
3647 declaration->type = result;
3650 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3651 bool may_be_abstract)
3653 /* construct a single linked list of construct_type_t's which describe
3654 * how to construct the final declarator type */
3655 construct_type_t *first = NULL;
3656 construct_type_t *last = NULL;
3657 gnu_attribute_t *attributes = NULL;
3659 decl_modifiers_t modifiers = parse_attributes(&attributes);
3662 while(token.type == '*') {
3663 construct_type_t *type = parse_pointer_declarator();
3673 /* TODO: find out if this is correct */
3674 modifiers |= parse_attributes(&attributes);
3677 construct_type_t *inner_types = NULL;
3679 switch(token.type) {
3681 if (declaration == NULL) {
3682 errorf(HERE, "no identifier expected in typename");
3684 declaration->symbol = token.v.symbol;
3685 declaration->source_position = token.source_position;
3691 add_anchor_token(')');
3692 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3693 rem_anchor_token(')');
3697 if (may_be_abstract)
3699 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3700 /* avoid a loop in the outermost scope, because eat_statement doesn't
3702 if (token.type == '}' && current_function == NULL) {
3710 construct_type_t *p = last;
3713 construct_type_t *type;
3714 switch(token.type) {
3716 type = parse_function_declarator(declaration);
3719 type = parse_array_declarator();
3722 goto declarator_finished;
3725 /* insert in the middle of the list (behind p) */
3727 type->next = p->next;
3738 declarator_finished:
3739 /* append inner_types at the end of the list, we don't to set last anymore
3740 * as it's not needed anymore */
3742 assert(first == NULL);
3743 first = inner_types;
3745 last->next = inner_types;
3753 static void parse_declaration_attributes(declaration_t *declaration)
3755 gnu_attribute_t *attributes = NULL;
3756 decl_modifiers_t modifiers = parse_attributes(&attributes);
3758 if (declaration == NULL)
3761 declaration->modifiers |= modifiers;
3762 /* check if we have these stupid mode attributes... */
3763 type_t *old_type = declaration->type;
3764 if (old_type == NULL)
3767 gnu_attribute_t *attribute = attributes;
3768 for ( ; attribute != NULL; attribute = attribute->next) {
3769 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3772 atomic_type_kind_t akind = attribute->u.akind;
3773 if (!is_type_signed(old_type)) {
3775 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3776 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3777 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3778 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3780 panic("invalid akind in mode attribute");
3784 = make_atomic_type(akind, old_type->base.qualifiers);
3788 static type_t *construct_declarator_type(construct_type_t *construct_list,
3791 construct_type_t *iter = construct_list;
3792 for( ; iter != NULL; iter = iter->next) {
3793 switch(iter->kind) {
3794 case CONSTRUCT_INVALID:
3795 internal_errorf(HERE, "invalid type construction found");
3796 case CONSTRUCT_FUNCTION: {
3797 construct_function_type_t *construct_function_type
3798 = (construct_function_type_t*) iter;
3800 type_t *function_type = construct_function_type->function_type;
3802 function_type->function.return_type = type;
3804 type_t *skipped_return_type = skip_typeref(type);
3805 if (is_type_function(skipped_return_type)) {
3806 errorf(HERE, "function returning function is not allowed");
3807 type = type_error_type;
3808 } else if (is_type_array(skipped_return_type)) {
3809 errorf(HERE, "function returning array is not allowed");
3810 type = type_error_type;
3812 type = function_type;
3817 case CONSTRUCT_POINTER: {
3818 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3819 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3820 pointer_type->pointer.points_to = type;
3821 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3823 type = pointer_type;
3827 case CONSTRUCT_ARRAY: {
3828 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3829 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3831 expression_t *size_expression = parsed_array->size;
3832 if (size_expression != NULL) {
3834 = create_implicit_cast(size_expression, type_size_t);
3837 array_type->base.qualifiers = parsed_array->type_qualifiers;
3838 array_type->array.element_type = type;
3839 array_type->array.is_static = parsed_array->is_static;
3840 array_type->array.is_variable = parsed_array->is_variable;
3841 array_type->array.size_expression = size_expression;
3843 if (size_expression != NULL) {
3844 if (is_constant_expression(size_expression)) {
3845 array_type->array.size_constant = true;
3846 array_type->array.size
3847 = fold_constant(size_expression);
3849 array_type->array.is_vla = true;
3853 type_t *skipped_type = skip_typeref(type);
3854 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3855 errorf(HERE, "array of void is not allowed");
3856 type = type_error_type;
3864 type_t *hashed_type = typehash_insert(type);
3865 if (hashed_type != type) {
3866 /* the function type was constructed earlier freeing it here will
3867 * destroy other types... */
3868 if (iter->kind != CONSTRUCT_FUNCTION) {
3878 static declaration_t *parse_declarator(
3879 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3881 declaration_t *const declaration = allocate_declaration_zero();
3882 declaration->declared_storage_class = specifiers->declared_storage_class;
3883 declaration->modifiers = specifiers->modifiers;
3884 declaration->deprecated = specifiers->deprecated;
3885 declaration->deprecated_string = specifiers->deprecated_string;
3886 declaration->get_property_sym = specifiers->get_property_sym;
3887 declaration->put_property_sym = specifiers->put_property_sym;
3888 declaration->is_inline = specifiers->is_inline;
3890 declaration->storage_class = specifiers->declared_storage_class;
3891 if (declaration->storage_class == STORAGE_CLASS_NONE
3892 && scope != global_scope) {
3893 declaration->storage_class = STORAGE_CLASS_AUTO;
3896 if (specifiers->alignment != 0) {
3897 /* TODO: add checks here */
3898 declaration->alignment = specifiers->alignment;
3901 construct_type_t *construct_type
3902 = parse_inner_declarator(declaration, may_be_abstract);
3903 type_t *const type = specifiers->type;
3904 declaration->type = construct_declarator_type(construct_type, type);
3906 parse_declaration_attributes(declaration);
3908 fix_declaration_type(declaration);
3910 if (construct_type != NULL) {
3911 obstack_free(&temp_obst, construct_type);
3917 static type_t *parse_abstract_declarator(type_t *base_type)
3919 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3921 type_t *result = construct_declarator_type(construct_type, base_type);
3922 if (construct_type != NULL) {
3923 obstack_free(&temp_obst, construct_type);
3929 static declaration_t *append_declaration(declaration_t* const declaration)
3931 if (last_declaration != NULL) {
3932 last_declaration->next = declaration;
3934 scope->declarations = declaration;
3936 last_declaration = declaration;
3941 * Check if the declaration of main is suspicious. main should be a
3942 * function with external linkage, returning int, taking either zero
3943 * arguments, two, or three arguments of appropriate types, ie.
3945 * int main([ int argc, char **argv [, char **env ] ]).
3947 * @param decl the declaration to check
3948 * @param type the function type of the declaration
3950 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3952 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3953 warningf(&decl->source_position,
3954 "'main' is normally a non-static function");
3956 if (skip_typeref(func_type->return_type) != type_int) {
3957 warningf(&decl->source_position,
3958 "return type of 'main' should be 'int', but is '%T'",
3959 func_type->return_type);
3961 const function_parameter_t *parm = func_type->parameters;
3963 type_t *const first_type = parm->type;
3964 if (!types_compatible(skip_typeref(first_type), type_int)) {
3965 warningf(&decl->source_position,
3966 "first argument of 'main' should be 'int', but is '%T'", first_type);
3970 type_t *const second_type = parm->type;
3971 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
3972 warningf(&decl->source_position,
3973 "second argument of 'main' should be 'char**', but is '%T'", second_type);
3977 type_t *const third_type = parm->type;
3978 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
3979 warningf(&decl->source_position,
3980 "third argument of 'main' should be 'char**', but is '%T'", third_type);
3984 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3988 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
3994 * Check if a symbol is the equal to "main".
3996 static bool is_sym_main(const symbol_t *const sym)
3998 return strcmp(sym->string, "main") == 0;
4001 static declaration_t *internal_record_declaration(
4002 declaration_t *const declaration,
4003 const bool is_function_definition)
4005 const symbol_t *const symbol = declaration->symbol;
4006 const namespace_t namespc = (namespace_t)declaration->namespc;
4008 assert(declaration->symbol != NULL);
4009 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4011 type_t *const orig_type = declaration->type;
4012 type_t *const type = skip_typeref(orig_type);
4013 if (is_type_function(type) &&
4014 type->function.unspecified_parameters &&
4015 warning.strict_prototypes &&
4016 previous_declaration == NULL) {
4017 warningf(&declaration->source_position,
4018 "function declaration '%#T' is not a prototype",
4019 orig_type, declaration->symbol);
4022 if (is_function_definition && warning.main && is_sym_main(symbol)) {
4023 check_type_of_main(declaration, &type->function);
4026 assert(declaration != previous_declaration);
4027 if (previous_declaration != NULL
4028 && previous_declaration->parent_scope == scope) {
4029 /* can happen for K&R style declarations */
4030 if (previous_declaration->type == NULL) {
4031 previous_declaration->type = declaration->type;
4034 const type_t *prev_type = skip_typeref(previous_declaration->type);
4035 if (!types_compatible(type, prev_type)) {
4036 errorf(&declaration->source_position,
4037 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4038 orig_type, symbol, previous_declaration->type, symbol,
4039 &previous_declaration->source_position);
4041 unsigned old_storage_class = previous_declaration->storage_class;
4042 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4043 errorf(&declaration->source_position,
4044 "redeclaration of enum entry '%Y' (declared %P)",
4045 symbol, &previous_declaration->source_position);
4046 return previous_declaration;
4049 unsigned new_storage_class = declaration->storage_class;
4051 if (is_type_incomplete(prev_type)) {
4052 previous_declaration->type = type;
4056 /* pretend no storage class means extern for function
4057 * declarations (except if the previous declaration is neither
4058 * none nor extern) */
4059 if (is_type_function(type)) {
4060 if (prev_type->function.unspecified_parameters) {
4061 previous_declaration->type = type;
4065 switch (old_storage_class) {
4066 case STORAGE_CLASS_NONE:
4067 old_storage_class = STORAGE_CLASS_EXTERN;
4070 case STORAGE_CLASS_EXTERN:
4071 if (is_function_definition) {
4072 if (warning.missing_prototypes &&
4073 prev_type->function.unspecified_parameters &&
4074 !is_sym_main(symbol)) {
4075 warningf(&declaration->source_position,
4076 "no previous prototype for '%#T'",
4079 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4080 new_storage_class = STORAGE_CLASS_EXTERN;
4089 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4090 new_storage_class == STORAGE_CLASS_EXTERN) {
4091 warn_redundant_declaration:
4092 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4093 warningf(&declaration->source_position,
4094 "redundant declaration for '%Y' (declared %P)",
4095 symbol, &previous_declaration->source_position);
4097 } else if (current_function == NULL) {
4098 if (old_storage_class != STORAGE_CLASS_STATIC &&
4099 new_storage_class == STORAGE_CLASS_STATIC) {
4100 errorf(&declaration->source_position,
4101 "static declaration of '%Y' follows non-static declaration (declared %P)",
4102 symbol, &previous_declaration->source_position);
4103 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4104 && !is_function_definition) {
4105 goto warn_redundant_declaration;
4106 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4107 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4108 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4110 } else if (old_storage_class == new_storage_class) {
4111 errorf(&declaration->source_position,
4112 "redeclaration of '%Y' (declared %P)",
4113 symbol, &previous_declaration->source_position);
4115 errorf(&declaration->source_position,
4116 "redeclaration of '%Y' with different linkage (declared %P)",
4117 symbol, &previous_declaration->source_position);
4121 if (declaration->is_inline)
4122 previous_declaration->is_inline = true;
4123 return previous_declaration;
4124 } else if (is_function_definition) {
4125 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4126 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4127 warningf(&declaration->source_position,
4128 "no previous prototype for '%#T'", orig_type, symbol);
4129 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4130 warningf(&declaration->source_position,
4131 "no previous declaration for '%#T'", orig_type,
4135 } else if (warning.missing_declarations &&
4136 scope == global_scope &&
4137 !is_type_function(type) && (
4138 declaration->storage_class == STORAGE_CLASS_NONE ||
4139 declaration->storage_class == STORAGE_CLASS_THREAD
4141 warningf(&declaration->source_position,
4142 "no previous declaration for '%#T'", orig_type, symbol);
4145 assert(declaration->parent_scope == NULL);
4146 assert(scope != NULL);
4148 declaration->parent_scope = scope;
4150 environment_push(declaration);
4151 return append_declaration(declaration);
4154 static declaration_t *record_declaration(declaration_t *declaration)
4156 return internal_record_declaration(declaration, false);
4159 static declaration_t *record_function_definition(declaration_t *declaration)
4161 return internal_record_declaration(declaration, true);
4164 static void parser_error_multiple_definition(declaration_t *declaration,
4165 const source_position_t *source_position)
4167 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4168 declaration->symbol, &declaration->source_position);
4171 static bool is_declaration_specifier(const token_t *token,
4172 bool only_specifiers_qualifiers)
4174 switch(token->type) {
4179 return is_typedef_symbol(token->v.symbol);
4181 case T___extension__:
4183 return !only_specifiers_qualifiers;
4190 static void parse_init_declarator_rest(declaration_t *declaration)
4194 type_t *orig_type = declaration->type;
4195 type_t *type = skip_typeref(orig_type);
4197 if (declaration->init.initializer != NULL) {
4198 parser_error_multiple_definition(declaration, HERE);
4201 bool must_be_constant = false;
4202 if (declaration->storage_class == STORAGE_CLASS_STATIC
4203 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4204 || declaration->parent_scope == global_scope) {
4205 must_be_constant = true;
4208 parse_initializer_env_t env;
4209 env.type = orig_type;
4210 env.must_be_constant = must_be_constant;
4211 env.declaration = declaration;
4213 initializer_t *initializer = parse_initializer(&env);
4215 if (env.type != orig_type) {
4216 orig_type = env.type;
4217 type = skip_typeref(orig_type);
4218 declaration->type = env.type;
4221 if (is_type_function(type)) {
4222 errorf(&declaration->source_position,
4223 "initializers not allowed for function types at declator '%Y' (type '%T')",
4224 declaration->symbol, orig_type);
4226 declaration->init.initializer = initializer;
4230 /* parse rest of a declaration without any declarator */
4231 static void parse_anonymous_declaration_rest(
4232 const declaration_specifiers_t *specifiers,
4233 parsed_declaration_func finished_declaration)
4237 declaration_t *const declaration = allocate_declaration_zero();
4238 declaration->type = specifiers->type;
4239 declaration->declared_storage_class = specifiers->declared_storage_class;
4240 declaration->source_position = specifiers->source_position;
4241 declaration->modifiers = specifiers->modifiers;
4243 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4244 warningf(&declaration->source_position,
4245 "useless storage class in empty declaration");
4247 declaration->storage_class = STORAGE_CLASS_NONE;
4249 type_t *type = declaration->type;
4250 switch (type->kind) {
4251 case TYPE_COMPOUND_STRUCT:
4252 case TYPE_COMPOUND_UNION: {
4253 if (type->compound.declaration->symbol == NULL) {
4254 warningf(&declaration->source_position,
4255 "unnamed struct/union that defines no instances");
4264 warningf(&declaration->source_position, "empty declaration");
4268 finished_declaration(declaration);
4271 static void parse_declaration_rest(declaration_t *ndeclaration,
4272 const declaration_specifiers_t *specifiers,
4273 parsed_declaration_func finished_declaration)
4275 add_anchor_token(';');
4276 add_anchor_token('=');
4277 add_anchor_token(',');
4279 declaration_t *declaration = finished_declaration(ndeclaration);
4281 type_t *orig_type = declaration->type;
4282 type_t *type = skip_typeref(orig_type);
4284 if (type->kind != TYPE_FUNCTION &&
4285 declaration->is_inline &&
4286 is_type_valid(type)) {
4287 warningf(&declaration->source_position,
4288 "variable '%Y' declared 'inline'\n", declaration->symbol);
4291 if (token.type == '=') {
4292 parse_init_declarator_rest(declaration);
4295 if (token.type != ',')
4299 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4304 rem_anchor_token(';');
4305 rem_anchor_token('=');
4306 rem_anchor_token(',');
4309 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4311 symbol_t *symbol = declaration->symbol;
4312 if (symbol == NULL) {
4313 errorf(HERE, "anonymous declaration not valid as function parameter");
4316 namespace_t namespc = (namespace_t) declaration->namespc;
4317 if (namespc != NAMESPACE_NORMAL) {
4318 return record_declaration(declaration);
4321 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4322 if (previous_declaration == NULL ||
4323 previous_declaration->parent_scope != scope) {
4324 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4329 if (previous_declaration->type == NULL) {
4330 previous_declaration->type = declaration->type;
4331 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4332 previous_declaration->storage_class = declaration->storage_class;
4333 previous_declaration->parent_scope = scope;
4334 return previous_declaration;
4336 return record_declaration(declaration);
4340 static void parse_declaration(parsed_declaration_func finished_declaration)
4342 declaration_specifiers_t specifiers;
4343 memset(&specifiers, 0, sizeof(specifiers));
4344 parse_declaration_specifiers(&specifiers);
4346 if (token.type == ';') {
4347 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4349 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4350 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4354 static type_t *get_default_promoted_type(type_t *orig_type)
4356 type_t *result = orig_type;
4358 type_t *type = skip_typeref(orig_type);
4359 if (is_type_integer(type)) {
4360 result = promote_integer(type);
4361 } else if (type == type_float) {
4362 result = type_double;
4368 static void parse_kr_declaration_list(declaration_t *declaration)
4370 type_t *type = skip_typeref(declaration->type);
4371 if (!is_type_function(type))
4374 if (!type->function.kr_style_parameters)
4377 /* push function parameters */
4378 int top = environment_top();
4379 scope_t *last_scope = scope;
4380 set_scope(&declaration->scope);
4382 declaration_t *parameter = declaration->scope.declarations;
4383 for ( ; parameter != NULL; parameter = parameter->next) {
4384 assert(parameter->parent_scope == NULL);
4385 parameter->parent_scope = scope;
4386 environment_push(parameter);
4389 /* parse declaration list */
4390 while (is_declaration_specifier(&token, false)) {
4391 parse_declaration(finished_kr_declaration);
4394 /* pop function parameters */
4395 assert(scope == &declaration->scope);
4396 set_scope(last_scope);
4397 environment_pop_to(top);
4399 /* update function type */
4400 type_t *new_type = duplicate_type(type);
4402 function_parameter_t *parameters = NULL;
4403 function_parameter_t *last_parameter = NULL;
4405 declaration_t *parameter_declaration = declaration->scope.declarations;
4406 for( ; parameter_declaration != NULL;
4407 parameter_declaration = parameter_declaration->next) {
4408 type_t *parameter_type = parameter_declaration->type;
4409 if (parameter_type == NULL) {
4411 errorf(HERE, "no type specified for function parameter '%Y'",
4412 parameter_declaration->symbol);
4414 if (warning.implicit_int) {
4415 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4416 parameter_declaration->symbol);
4418 parameter_type = type_int;
4419 parameter_declaration->type = parameter_type;
4423 semantic_parameter(parameter_declaration);
4424 parameter_type = parameter_declaration->type;
4427 * we need the default promoted types for the function type
4429 parameter_type = get_default_promoted_type(parameter_type);
4431 function_parameter_t *function_parameter
4432 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4433 memset(function_parameter, 0, sizeof(function_parameter[0]));
4435 function_parameter->type = parameter_type;
4436 if (last_parameter != NULL) {
4437 last_parameter->next = function_parameter;
4439 parameters = function_parameter;
4441 last_parameter = function_parameter;
4444 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4446 new_type->function.parameters = parameters;
4447 new_type->function.unspecified_parameters = true;
4449 type = typehash_insert(new_type);
4450 if (type != new_type) {
4451 obstack_free(type_obst, new_type);
4454 declaration->type = type;
4457 static bool first_err = true;
4460 * When called with first_err set, prints the name of the current function,
4463 static void print_in_function(void) {
4466 diagnosticf("%s: In function '%Y':\n",
4467 current_function->source_position.input_name,
4468 current_function->symbol);
4473 * Check if all labels are defined in the current function.
4474 * Check if all labels are used in the current function.
4476 static void check_labels(void)
4478 for (const goto_statement_t *goto_statement = goto_first;
4479 goto_statement != NULL;
4480 goto_statement = goto_statement->next) {
4481 declaration_t *label = goto_statement->label;
4484 if (label->source_position.input_name == NULL) {
4485 print_in_function();
4486 errorf(&goto_statement->base.source_position,
4487 "label '%Y' used but not defined", label->symbol);
4490 goto_first = goto_last = NULL;
4492 if (warning.unused_label) {
4493 for (const label_statement_t *label_statement = label_first;
4494 label_statement != NULL;
4495 label_statement = label_statement->next) {
4496 const declaration_t *label = label_statement->label;
4498 if (! label->used) {
4499 print_in_function();
4500 warningf(&label_statement->base.source_position,
4501 "label '%Y' defined but not used", label->symbol);
4505 label_first = label_last = NULL;
4509 * Check declarations of current_function for unused entities.
4511 static void check_declarations(void)
4513 if (warning.unused_parameter) {
4514 const scope_t *scope = ¤t_function->scope;
4516 const declaration_t *parameter = scope->declarations;
4517 for (; parameter != NULL; parameter = parameter->next) {
4518 if (! parameter->used) {
4519 print_in_function();
4520 warningf(¶meter->source_position,
4521 "unused parameter '%Y'", parameter->symbol);
4525 if (warning.unused_variable) {
4529 static void parse_external_declaration(void)
4531 /* function-definitions and declarations both start with declaration
4533 declaration_specifiers_t specifiers;
4534 memset(&specifiers, 0, sizeof(specifiers));
4536 add_anchor_token(';');
4537 parse_declaration_specifiers(&specifiers);
4538 rem_anchor_token(';');
4540 /* must be a declaration */
4541 if (token.type == ';') {
4542 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4546 add_anchor_token(',');
4547 add_anchor_token('=');
4548 rem_anchor_token(';');
4550 /* declarator is common to both function-definitions and declarations */
4551 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4553 rem_anchor_token(',');
4554 rem_anchor_token('=');
4555 rem_anchor_token(';');
4557 /* must be a declaration */
4558 if (token.type == ',' || token.type == '=' || token.type == ';') {
4559 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4563 /* must be a function definition */
4564 parse_kr_declaration_list(ndeclaration);
4566 if (token.type != '{') {
4567 parse_error_expected("while parsing function definition", '{', NULL);
4568 eat_until_matching_token(';');
4572 type_t *type = ndeclaration->type;
4574 /* note that we don't skip typerefs: the standard doesn't allow them here
4575 * (so we can't use is_type_function here) */
4576 if (type->kind != TYPE_FUNCTION) {
4577 if (is_type_valid(type)) {
4578 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4579 type, ndeclaration->symbol);
4585 /* § 6.7.5.3 (14) a function definition with () means no
4586 * parameters (and not unspecified parameters) */
4587 if (type->function.unspecified_parameters
4588 && type->function.parameters == NULL
4589 && !type->function.kr_style_parameters) {
4590 type_t *duplicate = duplicate_type(type);
4591 duplicate->function.unspecified_parameters = false;
4593 type = typehash_insert(duplicate);
4594 if (type != duplicate) {
4595 obstack_free(type_obst, duplicate);
4597 ndeclaration->type = type;
4600 declaration_t *const declaration = record_function_definition(ndeclaration);
4601 if (ndeclaration != declaration) {
4602 declaration->scope = ndeclaration->scope;
4604 type = skip_typeref(declaration->type);
4606 /* push function parameters and switch scope */
4607 int top = environment_top();
4608 scope_t *last_scope = scope;
4609 set_scope(&declaration->scope);
4611 declaration_t *parameter = declaration->scope.declarations;
4612 for( ; parameter != NULL; parameter = parameter->next) {
4613 if (parameter->parent_scope == &ndeclaration->scope) {
4614 parameter->parent_scope = scope;
4616 assert(parameter->parent_scope == NULL
4617 || parameter->parent_scope == scope);
4618 parameter->parent_scope = scope;
4619 if (parameter->symbol == NULL) {
4620 errorf(&ndeclaration->source_position, "parameter name omitted");
4623 environment_push(parameter);
4626 if (declaration->init.statement != NULL) {
4627 parser_error_multiple_definition(declaration, HERE);
4629 goto end_of_parse_external_declaration;
4631 /* parse function body */
4632 int label_stack_top = label_top();
4633 declaration_t *old_current_function = current_function;
4634 current_function = declaration;
4636 declaration->init.statement = parse_compound_statement(false);
4639 check_declarations();
4641 assert(current_function == declaration);
4642 current_function = old_current_function;
4643 label_pop_to(label_stack_top);
4646 end_of_parse_external_declaration:
4647 assert(scope == &declaration->scope);
4648 set_scope(last_scope);
4649 environment_pop_to(top);
4652 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4653 source_position_t *source_position)
4655 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4657 type->bitfield.base_type = base_type;
4658 type->bitfield.size = size;
4663 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4666 declaration_t *iter = compound_declaration->scope.declarations;
4667 for( ; iter != NULL; iter = iter->next) {
4668 if (iter->namespc != NAMESPACE_NORMAL)
4671 if (iter->symbol == NULL) {
4672 type_t *type = skip_typeref(iter->type);
4673 if (is_type_compound(type)) {
4674 declaration_t *result
4675 = find_compound_entry(type->compound.declaration, symbol);
4682 if (iter->symbol == symbol) {
4690 static void parse_compound_declarators(declaration_t *struct_declaration,
4691 const declaration_specifiers_t *specifiers)
4693 declaration_t *last_declaration = struct_declaration->scope.declarations;
4694 if (last_declaration != NULL) {
4695 while(last_declaration->next != NULL) {
4696 last_declaration = last_declaration->next;
4701 declaration_t *declaration;
4703 if (token.type == ':') {
4704 source_position_t source_position = *HERE;
4707 type_t *base_type = specifiers->type;
4708 expression_t *size = parse_constant_expression();
4710 if (!is_type_integer(skip_typeref(base_type))) {
4711 errorf(HERE, "bitfield base type '%T' is not an integer type",
4715 type_t *type = make_bitfield_type(base_type, size, &source_position);
4717 declaration = allocate_declaration_zero();
4718 declaration->namespc = NAMESPACE_NORMAL;
4719 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4720 declaration->storage_class = STORAGE_CLASS_NONE;
4721 declaration->source_position = source_position;
4722 declaration->modifiers = specifiers->modifiers;
4723 declaration->type = type;
4725 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4727 type_t *orig_type = declaration->type;
4728 type_t *type = skip_typeref(orig_type);
4730 if (token.type == ':') {
4731 source_position_t source_position = *HERE;
4733 expression_t *size = parse_constant_expression();
4735 if (!is_type_integer(type)) {
4736 errorf(HERE, "bitfield base type '%T' is not an "
4737 "integer type", orig_type);
4740 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4741 declaration->type = bitfield_type;
4743 /* TODO we ignore arrays for now... what is missing is a check
4744 * that they're at the end of the struct */
4745 if (is_type_incomplete(type) && !is_type_array(type)) {
4747 "compound member '%Y' has incomplete type '%T'",
4748 declaration->symbol, orig_type);
4749 } else if (is_type_function(type)) {
4750 errorf(HERE, "compound member '%Y' must not have function "
4751 "type '%T'", declaration->symbol, orig_type);
4756 /* make sure we don't define a symbol multiple times */
4757 symbol_t *symbol = declaration->symbol;
4758 if (symbol != NULL) {
4759 declaration_t *prev_decl
4760 = find_compound_entry(struct_declaration, symbol);
4762 if (prev_decl != NULL) {
4763 assert(prev_decl->symbol == symbol);
4764 errorf(&declaration->source_position,
4765 "multiple declarations of symbol '%Y' (declared %P)",
4766 symbol, &prev_decl->source_position);
4770 /* append declaration */
4771 if (last_declaration != NULL) {
4772 last_declaration->next = declaration;
4774 struct_declaration->scope.declarations = declaration;
4776 last_declaration = declaration;
4778 if (token.type != ',')
4788 static void parse_compound_type_entries(declaration_t *compound_declaration)
4791 add_anchor_token('}');
4793 while(token.type != '}' && token.type != T_EOF) {
4794 declaration_specifiers_t specifiers;
4795 memset(&specifiers, 0, sizeof(specifiers));
4796 parse_declaration_specifiers(&specifiers);
4798 parse_compound_declarators(compound_declaration, &specifiers);
4800 rem_anchor_token('}');
4802 if (token.type == T_EOF) {
4803 errorf(HERE, "EOF while parsing struct");
4808 static type_t *parse_typename(void)
4810 declaration_specifiers_t specifiers;
4811 memset(&specifiers, 0, sizeof(specifiers));
4812 parse_declaration_specifiers(&specifiers);
4813 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4814 /* TODO: improve error message, user does probably not know what a
4815 * storage class is...
4817 errorf(HERE, "typename may not have a storage class");
4820 type_t *result = parse_abstract_declarator(specifiers.type);
4828 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4829 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4830 expression_t *left);
4832 typedef struct expression_parser_function_t expression_parser_function_t;
4833 struct expression_parser_function_t {
4834 unsigned precedence;
4835 parse_expression_function parser;
4836 unsigned infix_precedence;
4837 parse_expression_infix_function infix_parser;
4840 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4843 * Prints an error message if an expression was expected but not read
4845 static expression_t *expected_expression_error(void)
4847 /* skip the error message if the error token was read */
4848 if (token.type != T_ERROR) {
4849 errorf(HERE, "expected expression, got token '%K'", &token);
4853 return create_invalid_expression();
4857 * Parse a string constant.
4859 static expression_t *parse_string_const(void)
4862 if (token.type == T_STRING_LITERAL) {
4863 string_t res = token.v.string;
4865 while (token.type == T_STRING_LITERAL) {
4866 res = concat_strings(&res, &token.v.string);
4869 if (token.type != T_WIDE_STRING_LITERAL) {
4870 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4871 /* note: that we use type_char_ptr here, which is already the
4872 * automatic converted type. revert_automatic_type_conversion
4873 * will construct the array type */
4874 cnst->base.type = type_char_ptr;
4875 cnst->string.value = res;
4879 wres = concat_string_wide_string(&res, &token.v.wide_string);
4881 wres = token.v.wide_string;
4886 switch (token.type) {
4887 case T_WIDE_STRING_LITERAL:
4888 wres = concat_wide_strings(&wres, &token.v.wide_string);
4891 case T_STRING_LITERAL:
4892 wres = concat_wide_string_string(&wres, &token.v.string);
4896 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4897 cnst->base.type = type_wchar_t_ptr;
4898 cnst->wide_string.value = wres;
4907 * Parse an integer constant.
4909 static expression_t *parse_int_const(void)
4911 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4912 cnst->base.source_position = *HERE;
4913 cnst->base.type = token.datatype;
4914 cnst->conste.v.int_value = token.v.intvalue;
4922 * Parse a character constant.
4924 static expression_t *parse_character_constant(void)
4926 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4928 cnst->base.source_position = *HERE;
4929 cnst->base.type = token.datatype;
4930 cnst->conste.v.character = token.v.string;
4932 if (cnst->conste.v.character.size != 1) {
4933 if (warning.multichar && (c_mode & _GNUC)) {
4935 warningf(HERE, "multi-character character constant");
4937 errorf(HERE, "more than 1 characters in character constant");
4946 * Parse a wide character constant.
4948 static expression_t *parse_wide_character_constant(void)
4950 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4952 cnst->base.source_position = *HERE;
4953 cnst->base.type = token.datatype;
4954 cnst->conste.v.wide_character = token.v.wide_string;
4956 if (cnst->conste.v.wide_character.size != 1) {
4957 if (warning.multichar && (c_mode & _GNUC)) {
4959 warningf(HERE, "multi-character character constant");
4961 errorf(HERE, "more than 1 characters in character constant");
4970 * Parse a float constant.
4972 static expression_t *parse_float_const(void)
4974 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4975 cnst->base.type = token.datatype;
4976 cnst->conste.v.float_value = token.v.floatvalue;
4983 static declaration_t *create_implicit_function(symbol_t *symbol,
4984 const source_position_t *source_position)
4986 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
4987 ntype->function.return_type = type_int;
4988 ntype->function.unspecified_parameters = true;
4990 type_t *type = typehash_insert(ntype);
4991 if (type != ntype) {
4995 declaration_t *const declaration = allocate_declaration_zero();
4996 declaration->storage_class = STORAGE_CLASS_EXTERN;
4997 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
4998 declaration->type = type;
4999 declaration->symbol = symbol;
5000 declaration->source_position = *source_position;
5002 bool strict_prototypes_old = warning.strict_prototypes;
5003 warning.strict_prototypes = false;
5004 record_declaration(declaration);
5005 warning.strict_prototypes = strict_prototypes_old;
5011 * Creates a return_type (func)(argument_type) function type if not
5014 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5015 type_t *argument_type2)
5017 function_parameter_t *parameter2
5018 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5019 memset(parameter2, 0, sizeof(parameter2[0]));
5020 parameter2->type = argument_type2;
5022 function_parameter_t *parameter1
5023 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5024 memset(parameter1, 0, sizeof(parameter1[0]));
5025 parameter1->type = argument_type1;
5026 parameter1->next = parameter2;
5028 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5029 type->function.return_type = return_type;
5030 type->function.parameters = parameter1;
5032 type_t *result = typehash_insert(type);
5033 if (result != type) {
5041 * Creates a return_type (func)(argument_type) function type if not
5044 * @param return_type the return type
5045 * @param argument_type the argument type
5047 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5049 function_parameter_t *parameter
5050 = obstack_alloc(type_obst, sizeof(parameter[0]));
5051 memset(parameter, 0, sizeof(parameter[0]));
5052 parameter->type = argument_type;
5054 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5055 type->function.return_type = return_type;
5056 type->function.parameters = parameter;
5058 type_t *result = typehash_insert(type);
5059 if (result != type) {
5066 static type_t *make_function_0_type(type_t *return_type)
5068 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5069 type->function.return_type = return_type;
5070 type->function.parameters = NULL;
5072 type_t *result = typehash_insert(type);
5073 if (result != type) {
5081 * Creates a function type for some function like builtins.
5083 * @param symbol the symbol describing the builtin
5085 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5087 switch(symbol->ID) {
5088 case T___builtin_alloca:
5089 return make_function_1_type(type_void_ptr, type_size_t);
5090 case T___builtin_huge_val:
5091 return make_function_0_type(type_double);
5092 case T___builtin_nan:
5093 return make_function_1_type(type_double, type_char_ptr);
5094 case T___builtin_nanf:
5095 return make_function_1_type(type_float, type_char_ptr);
5096 case T___builtin_nand:
5097 return make_function_1_type(type_long_double, type_char_ptr);
5098 case T___builtin_va_end:
5099 return make_function_1_type(type_void, type_valist);
5100 case T___builtin_expect:
5101 return make_function_2_type(type_long, type_long, type_long);
5103 internal_errorf(HERE, "not implemented builtin symbol found");
5108 * Performs automatic type cast as described in § 6.3.2.1.
5110 * @param orig_type the original type
5112 static type_t *automatic_type_conversion(type_t *orig_type)
5114 type_t *type = skip_typeref(orig_type);
5115 if (is_type_array(type)) {
5116 array_type_t *array_type = &type->array;
5117 type_t *element_type = array_type->element_type;
5118 unsigned qualifiers = array_type->base.qualifiers;
5120 return make_pointer_type(element_type, qualifiers);
5123 if (is_type_function(type)) {
5124 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5131 * reverts the automatic casts of array to pointer types and function
5132 * to function-pointer types as defined § 6.3.2.1
5134 type_t *revert_automatic_type_conversion(const expression_t *expression)
5136 switch (expression->kind) {
5137 case EXPR_REFERENCE: return expression->reference.declaration->type;
5138 case EXPR_SELECT: return expression->select.compound_entry->type;
5140 case EXPR_UNARY_DEREFERENCE: {
5141 const expression_t *const value = expression->unary.value;
5142 type_t *const type = skip_typeref(value->base.type);
5143 assert(is_type_pointer(type));
5144 return type->pointer.points_to;
5147 case EXPR_BUILTIN_SYMBOL:
5148 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5150 case EXPR_ARRAY_ACCESS: {
5151 const expression_t *array_ref = expression->array_access.array_ref;
5152 type_t *type_left = skip_typeref(array_ref->base.type);
5153 if (!is_type_valid(type_left))
5155 assert(is_type_pointer(type_left));
5156 return type_left->pointer.points_to;
5159 case EXPR_STRING_LITERAL: {
5160 size_t size = expression->string.value.size;
5161 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5164 case EXPR_WIDE_STRING_LITERAL: {
5165 size_t size = expression->wide_string.value.size;
5166 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5169 case EXPR_COMPOUND_LITERAL:
5170 return expression->compound_literal.type;
5175 return expression->base.type;
5178 static expression_t *parse_reference(void)
5180 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5182 reference_expression_t *ref = &expression->reference;
5183 symbol_t *const symbol = token.v.symbol;
5185 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5187 source_position_t source_position = token.source_position;
5190 if (declaration == NULL) {
5191 if (! strict_mode && token.type == '(') {
5192 /* an implicitly defined function */
5193 if (warning.implicit_function_declaration) {
5194 warningf(HERE, "implicit declaration of function '%Y'",
5198 declaration = create_implicit_function(symbol,
5201 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5202 return create_invalid_expression();
5206 type_t *type = declaration->type;
5208 /* we always do the auto-type conversions; the & and sizeof parser contains
5209 * code to revert this! */
5210 type = automatic_type_conversion(type);
5212 ref->declaration = declaration;
5213 ref->base.type = type;
5215 /* this declaration is used */
5216 declaration->used = true;
5218 /* check for deprecated functions */
5219 if (declaration->deprecated != 0) {
5220 const char *prefix = "";
5221 if (is_type_function(declaration->type))
5222 prefix = "function ";
5224 if (declaration->deprecated_string != NULL) {
5225 warningf(&source_position,
5226 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5227 declaration->deprecated_string);
5229 warningf(&source_position,
5230 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5237 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5241 /* TODO check if explicit cast is allowed and issue warnings/errors */
5244 static expression_t *parse_compound_literal(type_t *type)
5246 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5248 parse_initializer_env_t env;
5250 env.declaration = NULL;
5251 env.must_be_constant = false;
5252 initializer_t *initializer = parse_initializer(&env);
5255 expression->compound_literal.initializer = initializer;
5256 expression->compound_literal.type = type;
5257 expression->base.type = automatic_type_conversion(type);
5263 * Parse a cast expression.
5265 static expression_t *parse_cast(void)
5267 source_position_t source_position = token.source_position;
5269 type_t *type = parse_typename();
5271 /* matching add_anchor_token() is at call site */
5272 rem_anchor_token(')');
5275 if (token.type == '{') {
5276 return parse_compound_literal(type);
5279 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5280 cast->base.source_position = source_position;
5282 expression_t *value = parse_sub_expression(20);
5284 check_cast_allowed(value, type);
5286 cast->base.type = type;
5287 cast->unary.value = value;
5291 return create_invalid_expression();
5295 * Parse a statement expression.
5297 static expression_t *parse_statement_expression(void)
5299 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5301 statement_t *statement = parse_compound_statement(true);
5302 expression->statement.statement = statement;
5303 expression->base.source_position = statement->base.source_position;
5305 /* find last statement and use its type */
5306 type_t *type = type_void;
5307 const statement_t *stmt = statement->compound.statements;
5309 while (stmt->base.next != NULL)
5310 stmt = stmt->base.next;
5312 if (stmt->kind == STATEMENT_EXPRESSION) {
5313 type = stmt->expression.expression->base.type;
5316 warningf(&expression->base.source_position, "empty statement expression ({})");
5318 expression->base.type = type;
5324 return create_invalid_expression();
5328 * Parse a braced expression.
5330 static expression_t *parse_brace_expression(void)
5333 add_anchor_token(')');
5335 switch(token.type) {
5337 /* gcc extension: a statement expression */
5338 return parse_statement_expression();
5342 return parse_cast();
5344 if (is_typedef_symbol(token.v.symbol)) {
5345 return parse_cast();
5349 expression_t *result = parse_expression();
5350 rem_anchor_token(')');
5355 return create_invalid_expression();
5358 static expression_t *parse_function_keyword(void)
5363 if (current_function == NULL) {
5364 errorf(HERE, "'__func__' used outside of a function");
5367 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5368 expression->base.type = type_char_ptr;
5369 expression->funcname.kind = FUNCNAME_FUNCTION;
5374 static expression_t *parse_pretty_function_keyword(void)
5376 eat(T___PRETTY_FUNCTION__);
5378 if (current_function == NULL) {
5379 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5382 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5383 expression->base.type = type_char_ptr;
5384 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5389 static expression_t *parse_funcsig_keyword(void)
5393 if (current_function == NULL) {
5394 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5397 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5398 expression->base.type = type_char_ptr;
5399 expression->funcname.kind = FUNCNAME_FUNCSIG;
5404 static expression_t *parse_funcdname_keyword(void)
5406 eat(T___FUNCDNAME__);
5408 if (current_function == NULL) {
5409 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5412 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5413 expression->base.type = type_char_ptr;
5414 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5419 static designator_t *parse_designator(void)
5421 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5422 result->source_position = *HERE;
5424 if (token.type != T_IDENTIFIER) {
5425 parse_error_expected("while parsing member designator",
5426 T_IDENTIFIER, NULL);
5429 result->symbol = token.v.symbol;
5432 designator_t *last_designator = result;
5434 if (token.type == '.') {
5436 if (token.type != T_IDENTIFIER) {
5437 parse_error_expected("while parsing member designator",
5438 T_IDENTIFIER, NULL);
5441 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5442 designator->source_position = *HERE;
5443 designator->symbol = token.v.symbol;
5446 last_designator->next = designator;
5447 last_designator = designator;
5450 if (token.type == '[') {
5452 add_anchor_token(']');
5453 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5454 designator->source_position = *HERE;
5455 designator->array_index = parse_expression();
5456 rem_anchor_token(']');
5458 if (designator->array_index == NULL) {
5462 last_designator->next = designator;
5463 last_designator = designator;
5475 * Parse the __builtin_offsetof() expression.
5477 static expression_t *parse_offsetof(void)
5479 eat(T___builtin_offsetof);
5481 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5482 expression->base.type = type_size_t;
5485 add_anchor_token(',');
5486 type_t *type = parse_typename();
5487 rem_anchor_token(',');
5489 add_anchor_token(')');
5490 designator_t *designator = parse_designator();
5491 rem_anchor_token(')');
5494 expression->offsetofe.type = type;
5495 expression->offsetofe.designator = designator;
5498 memset(&path, 0, sizeof(path));
5499 path.top_type = type;
5500 path.path = NEW_ARR_F(type_path_entry_t, 0);
5502 descend_into_subtype(&path);
5504 if (!walk_designator(&path, designator, true)) {
5505 return create_invalid_expression();
5508 DEL_ARR_F(path.path);
5512 return create_invalid_expression();
5516 * Parses a _builtin_va_start() expression.
5518 static expression_t *parse_va_start(void)
5520 eat(T___builtin_va_start);
5522 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5525 add_anchor_token(',');
5526 expression->va_starte.ap = parse_assignment_expression();
5527 rem_anchor_token(',');
5529 expression_t *const expr = parse_assignment_expression();
5530 if (expr->kind == EXPR_REFERENCE) {
5531 declaration_t *const decl = expr->reference.declaration;
5533 return create_invalid_expression();
5534 if (decl->parent_scope == ¤t_function->scope &&
5535 decl->next == NULL) {
5536 expression->va_starte.parameter = decl;
5541 errorf(&expr->base.source_position,
5542 "second argument of 'va_start' must be last parameter of the current function");
5544 return create_invalid_expression();
5548 * Parses a _builtin_va_arg() expression.
5550 static expression_t *parse_va_arg(void)
5552 eat(T___builtin_va_arg);
5554 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5557 expression->va_arge.ap = parse_assignment_expression();
5559 expression->base.type = parse_typename();
5564 return create_invalid_expression();
5567 static expression_t *parse_builtin_symbol(void)
5569 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5571 symbol_t *symbol = token.v.symbol;
5573 expression->builtin_symbol.symbol = symbol;
5576 type_t *type = get_builtin_symbol_type(symbol);
5577 type = automatic_type_conversion(type);
5579 expression->base.type = type;
5584 * Parses a __builtin_constant() expression.
5586 static expression_t *parse_builtin_constant(void)
5588 eat(T___builtin_constant_p);
5590 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5593 add_anchor_token(')');
5594 expression->builtin_constant.value = parse_assignment_expression();
5595 rem_anchor_token(')');
5597 expression->base.type = type_int;
5601 return create_invalid_expression();
5605 * Parses a __builtin_prefetch() expression.
5607 static expression_t *parse_builtin_prefetch(void)
5609 eat(T___builtin_prefetch);
5611 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5614 add_anchor_token(')');
5615 expression->builtin_prefetch.adr = parse_assignment_expression();
5616 if (token.type == ',') {
5618 expression->builtin_prefetch.rw = parse_assignment_expression();
5620 if (token.type == ',') {
5622 expression->builtin_prefetch.locality = parse_assignment_expression();
5624 rem_anchor_token(')');
5626 expression->base.type = type_void;
5630 return create_invalid_expression();
5634 * Parses a __builtin_is_*() compare expression.
5636 static expression_t *parse_compare_builtin(void)
5638 expression_t *expression;
5640 switch(token.type) {
5641 case T___builtin_isgreater:
5642 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5644 case T___builtin_isgreaterequal:
5645 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5647 case T___builtin_isless:
5648 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5650 case T___builtin_islessequal:
5651 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5653 case T___builtin_islessgreater:
5654 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5656 case T___builtin_isunordered:
5657 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5660 internal_errorf(HERE, "invalid compare builtin found");
5663 expression->base.source_position = *HERE;
5667 expression->binary.left = parse_assignment_expression();
5669 expression->binary.right = parse_assignment_expression();
5672 type_t *const orig_type_left = expression->binary.left->base.type;
5673 type_t *const orig_type_right = expression->binary.right->base.type;
5675 type_t *const type_left = skip_typeref(orig_type_left);
5676 type_t *const type_right = skip_typeref(orig_type_right);
5677 if (!is_type_float(type_left) && !is_type_float(type_right)) {
5678 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5679 type_error_incompatible("invalid operands in comparison",
5680 &expression->base.source_position, orig_type_left, orig_type_right);
5683 semantic_comparison(&expression->binary);
5688 return create_invalid_expression();
5693 * Parses a __builtin_expect() expression.
5695 static expression_t *parse_builtin_expect(void)
5697 eat(T___builtin_expect);
5699 expression_t *expression
5700 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5703 expression->binary.left = parse_assignment_expression();
5705 expression->binary.right = parse_constant_expression();
5708 expression->base.type = expression->binary.left->base.type;
5712 return create_invalid_expression();
5717 * Parses a MS assume() expression.
5719 static expression_t *parse_assume(void) {
5722 expression_t *expression
5723 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5726 add_anchor_token(')');
5727 expression->unary.value = parse_assignment_expression();
5728 rem_anchor_token(')');
5731 expression->base.type = type_void;
5734 return create_invalid_expression();
5738 * Parse a microsoft __noop expression.
5740 static expression_t *parse_noop_expression(void) {
5741 source_position_t source_position = *HERE;
5744 if (token.type == '(') {
5745 /* parse arguments */
5747 add_anchor_token(')');
5748 add_anchor_token(',');
5750 if (token.type != ')') {
5752 (void)parse_assignment_expression();
5753 if (token.type != ',')
5759 rem_anchor_token(',');
5760 rem_anchor_token(')');
5763 /* the result is a (int)0 */
5764 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5765 cnst->base.source_position = source_position;
5766 cnst->base.type = type_int;
5767 cnst->conste.v.int_value = 0;
5768 cnst->conste.is_ms_noop = true;
5773 return create_invalid_expression();
5777 * Parses a primary expression.
5779 static expression_t *parse_primary_expression(void)
5781 switch (token.type) {
5782 case T_INTEGER: return parse_int_const();
5783 case T_CHARACTER_CONSTANT: return parse_character_constant();
5784 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5785 case T_FLOATINGPOINT: return parse_float_const();
5786 case T_STRING_LITERAL:
5787 case T_WIDE_STRING_LITERAL: return parse_string_const();
5788 case T_IDENTIFIER: return parse_reference();
5789 case T___FUNCTION__:
5790 case T___func__: return parse_function_keyword();
5791 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5792 case T___FUNCSIG__: return parse_funcsig_keyword();
5793 case T___FUNCDNAME__: return parse_funcdname_keyword();
5794 case T___builtin_offsetof: return parse_offsetof();
5795 case T___builtin_va_start: return parse_va_start();
5796 case T___builtin_va_arg: return parse_va_arg();
5797 case T___builtin_expect:
5798 case T___builtin_alloca:
5799 case T___builtin_nan:
5800 case T___builtin_nand:
5801 case T___builtin_nanf:
5802 case T___builtin_huge_val:
5803 case T___builtin_va_end: return parse_builtin_symbol();
5804 case T___builtin_isgreater:
5805 case T___builtin_isgreaterequal:
5806 case T___builtin_isless:
5807 case T___builtin_islessequal:
5808 case T___builtin_islessgreater:
5809 case T___builtin_isunordered: return parse_compare_builtin();
5810 case T___builtin_constant_p: return parse_builtin_constant();
5811 case T___builtin_prefetch: return parse_builtin_prefetch();
5812 case T__assume: return parse_assume();
5814 case '(': return parse_brace_expression();
5815 case T___noop: return parse_noop_expression();
5818 errorf(HERE, "unexpected token %K, expected an expression", &token);
5819 return create_invalid_expression();
5823 * Check if the expression has the character type and issue a warning then.
5825 static void check_for_char_index_type(const expression_t *expression) {
5826 type_t *const type = expression->base.type;
5827 const type_t *const base_type = skip_typeref(type);
5829 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5830 warning.char_subscripts) {
5831 warningf(&expression->base.source_position,
5832 "array subscript has type '%T'", type);
5836 static expression_t *parse_array_expression(unsigned precedence,
5842 add_anchor_token(']');
5844 expression_t *inside = parse_expression();
5846 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5848 array_access_expression_t *array_access = &expression->array_access;
5850 type_t *const orig_type_left = left->base.type;
5851 type_t *const orig_type_inside = inside->base.type;
5853 type_t *const type_left = skip_typeref(orig_type_left);
5854 type_t *const type_inside = skip_typeref(orig_type_inside);
5856 type_t *return_type;
5857 if (is_type_pointer(type_left)) {
5858 return_type = type_left->pointer.points_to;
5859 array_access->array_ref = left;
5860 array_access->index = inside;
5861 check_for_char_index_type(inside);
5862 } else if (is_type_pointer(type_inside)) {
5863 return_type = type_inside->pointer.points_to;
5864 array_access->array_ref = inside;
5865 array_access->index = left;
5866 array_access->flipped = true;
5867 check_for_char_index_type(left);
5869 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5871 "array access on object with non-pointer types '%T', '%T'",
5872 orig_type_left, orig_type_inside);
5874 return_type = type_error_type;
5875 array_access->array_ref = create_invalid_expression();
5878 rem_anchor_token(']');
5879 if (token.type != ']') {
5880 parse_error_expected("Problem while parsing array access", ']', NULL);
5885 return_type = automatic_type_conversion(return_type);
5886 expression->base.type = return_type;
5891 static expression_t *parse_typeprop(expression_kind_t const kind,
5892 source_position_t const pos,
5893 unsigned const precedence)
5895 expression_t *tp_expression = allocate_expression_zero(kind);
5896 tp_expression->base.type = type_size_t;
5897 tp_expression->base.source_position = pos;
5899 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5901 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5903 add_anchor_token(')');
5904 type_t* const orig_type = parse_typename();
5905 tp_expression->typeprop.type = orig_type;
5907 type_t const* const type = skip_typeref(orig_type);
5908 char const* const wrong_type =
5909 is_type_incomplete(type) ? "incomplete" :
5910 type->kind == TYPE_FUNCTION ? "function designator" :
5911 type->kind == TYPE_BITFIELD ? "bitfield" :
5913 if (wrong_type != NULL) {
5914 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5915 what, wrong_type, type);
5918 rem_anchor_token(')');
5921 expression_t *expression = parse_sub_expression(precedence);
5923 type_t* const orig_type = revert_automatic_type_conversion(expression);
5924 expression->base.type = orig_type;
5926 type_t const* const type = skip_typeref(orig_type);
5927 char const* const wrong_type =
5928 is_type_incomplete(type) ? "incomplete" :
5929 type->kind == TYPE_FUNCTION ? "function designator" :
5930 type->kind == TYPE_BITFIELD ? "bitfield" :
5932 if (wrong_type != NULL) {
5933 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5936 tp_expression->typeprop.type = expression->base.type;
5937 tp_expression->typeprop.tp_expression = expression;
5940 return tp_expression;
5942 return create_invalid_expression();
5945 static expression_t *parse_sizeof(unsigned precedence)
5947 source_position_t pos = *HERE;
5949 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5952 static expression_t *parse_alignof(unsigned precedence)
5954 source_position_t pos = *HERE;
5956 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5959 static expression_t *parse_select_expression(unsigned precedence,
5960 expression_t *compound)
5963 assert(token.type == '.' || token.type == T_MINUSGREATER);
5965 bool is_pointer = (token.type == T_MINUSGREATER);
5968 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5969 select->select.compound = compound;
5971 if (token.type != T_IDENTIFIER) {
5972 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
5975 symbol_t *symbol = token.v.symbol;
5976 select->select.symbol = symbol;
5979 type_t *const orig_type = compound->base.type;
5980 type_t *const type = skip_typeref(orig_type);
5982 type_t *type_left = type;
5984 if (!is_type_pointer(type)) {
5985 if (is_type_valid(type)) {
5986 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
5988 return create_invalid_expression();
5990 type_left = type->pointer.points_to;
5992 type_left = skip_typeref(type_left);
5994 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
5995 type_left->kind != TYPE_COMPOUND_UNION) {
5996 if (is_type_valid(type_left)) {
5997 errorf(HERE, "request for member '%Y' in something not a struct or "
5998 "union, but '%T'", symbol, type_left);
6000 return create_invalid_expression();
6003 declaration_t *const declaration = type_left->compound.declaration;
6005 if (!declaration->init.complete) {
6006 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6008 return create_invalid_expression();
6011 declaration_t *iter = find_compound_entry(declaration, symbol);
6013 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6014 return create_invalid_expression();
6017 /* we always do the auto-type conversions; the & and sizeof parser contains
6018 * code to revert this! */
6019 type_t *expression_type = automatic_type_conversion(iter->type);
6021 select->select.compound_entry = iter;
6022 select->base.type = expression_type;
6024 type_t *skipped = skip_typeref(iter->type);
6025 if (skipped->kind == TYPE_BITFIELD) {
6026 select->base.type = skipped->bitfield.base_type;
6032 static void check_call_argument(const function_parameter_t *parameter,
6033 call_argument_t *argument)
6035 type_t *expected_type = parameter->type;
6036 type_t *expected_type_skip = skip_typeref(expected_type);
6037 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6038 expression_t *arg_expr = argument->expression;
6040 /* handle transparent union gnu extension */
6041 if (is_type_union(expected_type_skip)
6042 && (expected_type_skip->base.modifiers
6043 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6044 declaration_t *union_decl = expected_type_skip->compound.declaration;
6046 declaration_t *declaration = union_decl->scope.declarations;
6047 type_t *best_type = NULL;
6048 for ( ; declaration != NULL; declaration = declaration->next) {
6049 type_t *decl_type = declaration->type;
6050 error = semantic_assign(decl_type, arg_expr);
6051 if (error == ASSIGN_ERROR_INCOMPATIBLE
6052 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6055 if (error == ASSIGN_SUCCESS) {
6056 best_type = decl_type;
6057 } else if (best_type == NULL) {
6058 best_type = decl_type;
6062 if (best_type != NULL) {
6063 expected_type = best_type;
6067 error = semantic_assign(expected_type, arg_expr);
6068 argument->expression = create_implicit_cast(argument->expression,
6071 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6072 report_assign_error(error, expected_type, arg_expr, "function call",
6073 &arg_expr->base.source_position);
6077 * Parse a call expression, ie. expression '( ... )'.
6079 * @param expression the function address
6081 static expression_t *parse_call_expression(unsigned precedence,
6082 expression_t *expression)
6085 expression_t *result = allocate_expression_zero(EXPR_CALL);
6086 result->base.source_position = expression->base.source_position;
6088 call_expression_t *call = &result->call;
6089 call->function = expression;
6091 type_t *const orig_type = expression->base.type;
6092 type_t *const type = skip_typeref(orig_type);
6094 function_type_t *function_type = NULL;
6095 if (is_type_pointer(type)) {
6096 type_t *const to_type = skip_typeref(type->pointer.points_to);
6098 if (is_type_function(to_type)) {
6099 function_type = &to_type->function;
6100 call->base.type = function_type->return_type;
6104 if (function_type == NULL && is_type_valid(type)) {
6105 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6108 /* parse arguments */
6110 add_anchor_token(')');
6111 add_anchor_token(',');
6113 if (token.type != ')') {
6114 call_argument_t *last_argument = NULL;
6117 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6119 argument->expression = parse_assignment_expression();
6120 if (last_argument == NULL) {
6121 call->arguments = argument;
6123 last_argument->next = argument;
6125 last_argument = argument;
6127 if (token.type != ',')
6132 rem_anchor_token(',');
6133 rem_anchor_token(')');
6136 if (function_type == NULL)
6139 function_parameter_t *parameter = function_type->parameters;
6140 call_argument_t *argument = call->arguments;
6141 if (!function_type->unspecified_parameters) {
6142 for( ; parameter != NULL && argument != NULL;
6143 parameter = parameter->next, argument = argument->next) {
6144 check_call_argument(parameter, argument);
6147 if (parameter != NULL) {
6148 errorf(HERE, "too few arguments to function '%E'", expression);
6149 } else if (argument != NULL && !function_type->variadic) {
6150 errorf(HERE, "too many arguments to function '%E'", expression);
6154 /* do default promotion */
6155 for( ; argument != NULL; argument = argument->next) {
6156 type_t *type = argument->expression->base.type;
6158 type = get_default_promoted_type(type);
6160 argument->expression
6161 = create_implicit_cast(argument->expression, type);
6164 check_format(&result->call);
6168 return create_invalid_expression();
6171 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6173 static bool same_compound_type(const type_t *type1, const type_t *type2)
6176 is_type_compound(type1) &&
6177 type1->kind == type2->kind &&
6178 type1->compound.declaration == type2->compound.declaration;
6182 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6184 * @param expression the conditional expression
6186 static expression_t *parse_conditional_expression(unsigned precedence,
6187 expression_t *expression)
6190 add_anchor_token(':');
6192 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6194 conditional_expression_t *conditional = &result->conditional;
6195 conditional->condition = expression;
6198 type_t *const condition_type_orig = expression->base.type;
6199 type_t *const condition_type = skip_typeref(condition_type_orig);
6200 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6201 type_error("expected a scalar type in conditional condition",
6202 &expression->base.source_position, condition_type_orig);
6205 expression_t *true_expression = parse_expression();
6206 rem_anchor_token(':');
6208 expression_t *false_expression = parse_sub_expression(precedence);
6210 type_t *const orig_true_type = true_expression->base.type;
6211 type_t *const orig_false_type = false_expression->base.type;
6212 type_t *const true_type = skip_typeref(orig_true_type);
6213 type_t *const false_type = skip_typeref(orig_false_type);
6216 type_t *result_type;
6217 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6218 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6219 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6220 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6221 warningf(&expression->base.source_position,
6222 "ISO C forbids conditional expression with only one void side");
6224 result_type = type_void;
6225 } else if (is_type_arithmetic(true_type)
6226 && is_type_arithmetic(false_type)) {
6227 result_type = semantic_arithmetic(true_type, false_type);
6229 true_expression = create_implicit_cast(true_expression, result_type);
6230 false_expression = create_implicit_cast(false_expression, result_type);
6232 conditional->true_expression = true_expression;
6233 conditional->false_expression = false_expression;
6234 conditional->base.type = result_type;
6235 } else if (same_compound_type(true_type, false_type)) {
6236 /* just take 1 of the 2 types */
6237 result_type = true_type;
6238 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6239 type_t *pointer_type;
6241 expression_t *other_expression;
6242 if (is_type_pointer(true_type) &&
6243 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6244 pointer_type = true_type;
6245 other_type = false_type;
6246 other_expression = false_expression;
6248 pointer_type = false_type;
6249 other_type = true_type;
6250 other_expression = true_expression;
6253 if (is_null_pointer_constant(other_expression)) {
6254 result_type = pointer_type;
6255 } else if (is_type_pointer(other_type)) {
6256 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6257 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6260 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6261 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6263 } else if (types_compatible(get_unqualified_type(to1),
6264 get_unqualified_type(to2))) {
6267 warningf(&expression->base.source_position,
6268 "pointer types '%T' and '%T' in conditional expression are incompatible",
6269 true_type, false_type);
6273 type_t *const copy = duplicate_type(to);
6274 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6276 type_t *const type = typehash_insert(copy);
6280 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6281 } else if (is_type_integer(other_type)) {
6282 warningf(&expression->base.source_position,
6283 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6284 result_type = pointer_type;
6286 type_error_incompatible("while parsing conditional",
6287 &expression->base.source_position, true_type, false_type);
6288 result_type = type_error_type;
6291 /* TODO: one pointer to void*, other some pointer */
6293 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6294 type_error_incompatible("while parsing conditional",
6295 &expression->base.source_position, true_type,
6298 result_type = type_error_type;
6301 conditional->true_expression
6302 = create_implicit_cast(true_expression, result_type);
6303 conditional->false_expression
6304 = create_implicit_cast(false_expression, result_type);
6305 conditional->base.type = result_type;
6308 return create_invalid_expression();
6312 * Parse an extension expression.
6314 static expression_t *parse_extension(unsigned precedence)
6316 eat(T___extension__);
6318 /* TODO enable extensions */
6319 expression_t *expression = parse_sub_expression(precedence);
6320 /* TODO disable extensions */
6325 * Parse a __builtin_classify_type() expression.
6327 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6329 eat(T___builtin_classify_type);
6331 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6332 result->base.type = type_int;
6335 add_anchor_token(')');
6336 expression_t *expression = parse_sub_expression(precedence);
6337 rem_anchor_token(')');
6339 result->classify_type.type_expression = expression;
6343 return create_invalid_expression();
6346 static void check_pointer_arithmetic(const source_position_t *source_position,
6347 type_t *pointer_type,
6348 type_t *orig_pointer_type)
6350 type_t *points_to = pointer_type->pointer.points_to;
6351 points_to = skip_typeref(points_to);
6353 if (is_type_incomplete(points_to) &&
6355 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6356 errorf(source_position,
6357 "arithmetic with pointer to incomplete type '%T' not allowed",
6359 } else if (is_type_function(points_to)) {
6360 errorf(source_position,
6361 "arithmetic with pointer to function type '%T' not allowed",
6366 static void semantic_incdec(unary_expression_t *expression)
6368 type_t *const orig_type = expression->value->base.type;
6369 type_t *const type = skip_typeref(orig_type);
6370 if (is_type_pointer(type)) {
6371 check_pointer_arithmetic(&expression->base.source_position,
6373 } else if (!is_type_real(type) && is_type_valid(type)) {
6374 /* TODO: improve error message */
6375 errorf(HERE, "operation needs an arithmetic or pointer type");
6377 expression->base.type = orig_type;
6380 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6382 type_t *const orig_type = expression->value->base.type;
6383 type_t *const type = skip_typeref(orig_type);
6384 if (!is_type_arithmetic(type)) {
6385 if (is_type_valid(type)) {
6386 /* TODO: improve error message */
6387 errorf(HERE, "operation needs an arithmetic type");
6392 expression->base.type = orig_type;
6395 static void semantic_unexpr_scalar(unary_expression_t *expression)
6397 type_t *const orig_type = expression->value->base.type;
6398 type_t *const type = skip_typeref(orig_type);
6399 if (!is_type_scalar(type)) {
6400 if (is_type_valid(type)) {
6401 errorf(HERE, "operand of ! must be of scalar type");
6406 expression->base.type = orig_type;
6409 static void semantic_unexpr_integer(unary_expression_t *expression)
6411 type_t *const orig_type = expression->value->base.type;
6412 type_t *const type = skip_typeref(orig_type);
6413 if (!is_type_integer(type)) {
6414 if (is_type_valid(type)) {
6415 errorf(HERE, "operand of ~ must be of integer type");
6420 expression->base.type = orig_type;
6423 static void semantic_dereference(unary_expression_t *expression)
6425 type_t *const orig_type = expression->value->base.type;
6426 type_t *const type = skip_typeref(orig_type);
6427 if (!is_type_pointer(type)) {
6428 if (is_type_valid(type)) {
6429 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6434 type_t *result_type = type->pointer.points_to;
6435 result_type = automatic_type_conversion(result_type);
6436 expression->base.type = result_type;
6439 static void set_address_taken(expression_t *expression, bool may_be_register)
6441 if (expression->kind != EXPR_REFERENCE)
6444 declaration_t *const declaration = expression->reference.declaration;
6445 /* happens for parse errors */
6446 if (declaration == NULL)
6449 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6450 errorf(&expression->base.source_position,
6451 "address of register variable '%Y' requested",
6452 declaration->symbol);
6454 declaration->address_taken = 1;
6459 * Check the semantic of the address taken expression.
6461 static void semantic_take_addr(unary_expression_t *expression)
6463 expression_t *value = expression->value;
6464 value->base.type = revert_automatic_type_conversion(value);
6466 type_t *orig_type = value->base.type;
6467 if (!is_type_valid(orig_type))
6470 set_address_taken(value, false);
6472 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6475 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6476 static expression_t *parse_##unexpression_type(unsigned precedence) \
6480 expression_t *unary_expression \
6481 = allocate_expression_zero(unexpression_type); \
6482 unary_expression->base.source_position = *HERE; \
6483 unary_expression->unary.value = parse_sub_expression(precedence); \
6485 sfunc(&unary_expression->unary); \
6487 return unary_expression; \
6490 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6491 semantic_unexpr_arithmetic)
6492 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6493 semantic_unexpr_arithmetic)
6494 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6495 semantic_unexpr_scalar)
6496 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6497 semantic_dereference)
6498 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6500 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6501 semantic_unexpr_integer)
6502 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6504 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6507 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6509 static expression_t *parse_##unexpression_type(unsigned precedence, \
6510 expression_t *left) \
6512 (void) precedence; \
6515 expression_t *unary_expression \
6516 = allocate_expression_zero(unexpression_type); \
6517 unary_expression->unary.value = left; \
6519 sfunc(&unary_expression->unary); \
6521 return unary_expression; \
6524 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6525 EXPR_UNARY_POSTFIX_INCREMENT,
6527 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6528 EXPR_UNARY_POSTFIX_DECREMENT,
6531 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6533 /* TODO: handle complex + imaginary types */
6535 /* § 6.3.1.8 Usual arithmetic conversions */
6536 if (type_left == type_long_double || type_right == type_long_double) {
6537 return type_long_double;
6538 } else if (type_left == type_double || type_right == type_double) {
6540 } else if (type_left == type_float || type_right == type_float) {
6544 type_right = promote_integer(type_right);
6545 type_left = promote_integer(type_left);
6547 if (type_left == type_right)
6550 bool signed_left = is_type_signed(type_left);
6551 bool signed_right = is_type_signed(type_right);
6552 int rank_left = get_rank(type_left);
6553 int rank_right = get_rank(type_right);
6554 if (rank_left < rank_right) {
6555 if (signed_left == signed_right || !signed_right) {
6561 if (signed_left == signed_right || !signed_left) {
6570 * Check the semantic restrictions for a binary expression.
6572 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6574 expression_t *const left = expression->left;
6575 expression_t *const right = expression->right;
6576 type_t *const orig_type_left = left->base.type;
6577 type_t *const orig_type_right = right->base.type;
6578 type_t *const type_left = skip_typeref(orig_type_left);
6579 type_t *const type_right = skip_typeref(orig_type_right);
6581 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6582 /* TODO: improve error message */
6583 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6584 errorf(HERE, "operation needs arithmetic types");
6589 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6590 expression->left = create_implicit_cast(left, arithmetic_type);
6591 expression->right = create_implicit_cast(right, arithmetic_type);
6592 expression->base.type = arithmetic_type;
6595 static void semantic_shift_op(binary_expression_t *expression)
6597 expression_t *const left = expression->left;
6598 expression_t *const right = expression->right;
6599 type_t *const orig_type_left = left->base.type;
6600 type_t *const orig_type_right = right->base.type;
6601 type_t * type_left = skip_typeref(orig_type_left);
6602 type_t * type_right = skip_typeref(orig_type_right);
6604 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6605 /* TODO: improve error message */
6606 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6607 errorf(HERE, "operation needs integer types");
6612 type_left = promote_integer(type_left);
6613 type_right = promote_integer(type_right);
6615 expression->left = create_implicit_cast(left, type_left);
6616 expression->right = create_implicit_cast(right, type_right);
6617 expression->base.type = type_left;
6620 static void semantic_add(binary_expression_t *expression)
6622 expression_t *const left = expression->left;
6623 expression_t *const right = expression->right;
6624 type_t *const orig_type_left = left->base.type;
6625 type_t *const orig_type_right = right->base.type;
6626 type_t *const type_left = skip_typeref(orig_type_left);
6627 type_t *const type_right = skip_typeref(orig_type_right);
6630 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6631 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6632 expression->left = create_implicit_cast(left, arithmetic_type);
6633 expression->right = create_implicit_cast(right, arithmetic_type);
6634 expression->base.type = arithmetic_type;
6636 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6637 check_pointer_arithmetic(&expression->base.source_position,
6638 type_left, orig_type_left);
6639 expression->base.type = type_left;
6640 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6641 check_pointer_arithmetic(&expression->base.source_position,
6642 type_right, orig_type_right);
6643 expression->base.type = type_right;
6644 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6645 errorf(&expression->base.source_position,
6646 "invalid operands to binary + ('%T', '%T')",
6647 orig_type_left, orig_type_right);
6651 static void semantic_sub(binary_expression_t *expression)
6653 expression_t *const left = expression->left;
6654 expression_t *const right = expression->right;
6655 type_t *const orig_type_left = left->base.type;
6656 type_t *const orig_type_right = right->base.type;
6657 type_t *const type_left = skip_typeref(orig_type_left);
6658 type_t *const type_right = skip_typeref(orig_type_right);
6661 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6662 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6663 expression->left = create_implicit_cast(left, arithmetic_type);
6664 expression->right = create_implicit_cast(right, arithmetic_type);
6665 expression->base.type = arithmetic_type;
6667 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6668 check_pointer_arithmetic(&expression->base.source_position,
6669 type_left, orig_type_left);
6670 expression->base.type = type_left;
6671 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6672 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6673 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6674 if (!types_compatible(unqual_left, unqual_right)) {
6675 errorf(&expression->base.source_position,
6676 "subtracting pointers to incompatible types '%T' and '%T'",
6677 orig_type_left, orig_type_right);
6678 } else if (!is_type_object(unqual_left)) {
6679 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6680 warningf(&expression->base.source_position,
6681 "subtracting pointers to void");
6683 errorf(&expression->base.source_position,
6684 "subtracting pointers to non-object types '%T'",
6688 expression->base.type = type_ptrdiff_t;
6689 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6690 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6691 orig_type_left, orig_type_right);
6696 * Check the semantics of comparison expressions.
6698 * @param expression The expression to check.
6700 static void semantic_comparison(binary_expression_t *expression)
6702 expression_t *left = expression->left;
6703 expression_t *right = expression->right;
6704 type_t *orig_type_left = left->base.type;
6705 type_t *orig_type_right = right->base.type;
6707 type_t *type_left = skip_typeref(orig_type_left);
6708 type_t *type_right = skip_typeref(orig_type_right);
6710 /* TODO non-arithmetic types */
6711 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6712 /* test for signed vs unsigned compares */
6713 if (warning.sign_compare &&
6714 (expression->base.kind != EXPR_BINARY_EQUAL &&
6715 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6716 (is_type_signed(type_left) != is_type_signed(type_right))) {
6718 /* check if 1 of the operands is a constant, in this case we just
6719 * check wether we can safely represent the resulting constant in
6720 * the type of the other operand. */
6721 expression_t *const_expr = NULL;
6722 expression_t *other_expr = NULL;
6724 if (is_constant_expression(left)) {
6727 } else if (is_constant_expression(right)) {
6732 if (const_expr != NULL) {
6733 type_t *other_type = skip_typeref(other_expr->base.type);
6734 long val = fold_constant(const_expr);
6735 /* TODO: check if val can be represented by other_type */
6739 warningf(&expression->base.source_position,
6740 "comparison between signed and unsigned");
6742 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6743 expression->left = create_implicit_cast(left, arithmetic_type);
6744 expression->right = create_implicit_cast(right, arithmetic_type);
6745 expression->base.type = arithmetic_type;
6746 if (warning.float_equal &&
6747 (expression->base.kind == EXPR_BINARY_EQUAL ||
6748 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6749 is_type_float(arithmetic_type)) {
6750 warningf(&expression->base.source_position,
6751 "comparing floating point with == or != is unsafe");
6753 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6754 /* TODO check compatibility */
6755 } else if (is_type_pointer(type_left)) {
6756 expression->right = create_implicit_cast(right, type_left);
6757 } else if (is_type_pointer(type_right)) {
6758 expression->left = create_implicit_cast(left, type_right);
6759 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6760 type_error_incompatible("invalid operands in comparison",
6761 &expression->base.source_position,
6762 type_left, type_right);
6764 expression->base.type = type_int;
6768 * Checks if a compound type has constant fields.
6770 static bool has_const_fields(const compound_type_t *type)
6772 const scope_t *scope = &type->declaration->scope;
6773 const declaration_t *declaration = scope->declarations;
6775 for (; declaration != NULL; declaration = declaration->next) {
6776 if (declaration->namespc != NAMESPACE_NORMAL)
6779 const type_t *decl_type = skip_typeref(declaration->type);
6780 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6787 static bool is_lvalue(const expression_t *expression)
6789 switch (expression->kind) {
6790 case EXPR_REFERENCE:
6791 case EXPR_ARRAY_ACCESS:
6793 case EXPR_UNARY_DEREFERENCE:
6801 static bool is_valid_assignment_lhs(expression_t const* const left)
6803 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6804 type_t *const type_left = skip_typeref(orig_type_left);
6806 if (!is_lvalue(left)) {
6807 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6812 if (is_type_array(type_left)) {
6813 errorf(HERE, "cannot assign to arrays ('%E')", left);
6816 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6817 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6821 if (is_type_incomplete(type_left)) {
6822 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6823 left, orig_type_left);
6826 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6827 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6828 left, orig_type_left);
6835 static void semantic_arithmetic_assign(binary_expression_t *expression)
6837 expression_t *left = expression->left;
6838 expression_t *right = expression->right;
6839 type_t *orig_type_left = left->base.type;
6840 type_t *orig_type_right = right->base.type;
6842 if (!is_valid_assignment_lhs(left))
6845 type_t *type_left = skip_typeref(orig_type_left);
6846 type_t *type_right = skip_typeref(orig_type_right);
6848 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6849 /* TODO: improve error message */
6850 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6851 errorf(HERE, "operation needs arithmetic types");
6856 /* combined instructions are tricky. We can't create an implicit cast on
6857 * the left side, because we need the uncasted form for the store.
6858 * The ast2firm pass has to know that left_type must be right_type
6859 * for the arithmetic operation and create a cast by itself */
6860 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6861 expression->right = create_implicit_cast(right, arithmetic_type);
6862 expression->base.type = type_left;
6865 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6867 expression_t *const left = expression->left;
6868 expression_t *const right = expression->right;
6869 type_t *const orig_type_left = left->base.type;
6870 type_t *const orig_type_right = right->base.type;
6871 type_t *const type_left = skip_typeref(orig_type_left);
6872 type_t *const type_right = skip_typeref(orig_type_right);
6874 if (!is_valid_assignment_lhs(left))
6877 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6878 /* combined instructions are tricky. We can't create an implicit cast on
6879 * the left side, because we need the uncasted form for the store.
6880 * The ast2firm pass has to know that left_type must be right_type
6881 * for the arithmetic operation and create a cast by itself */
6882 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6883 expression->right = create_implicit_cast(right, arithmetic_type);
6884 expression->base.type = type_left;
6885 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6886 check_pointer_arithmetic(&expression->base.source_position,
6887 type_left, orig_type_left);
6888 expression->base.type = type_left;
6889 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6890 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6895 * Check the semantic restrictions of a logical expression.
6897 static void semantic_logical_op(binary_expression_t *expression)
6899 expression_t *const left = expression->left;
6900 expression_t *const right = expression->right;
6901 type_t *const orig_type_left = left->base.type;
6902 type_t *const orig_type_right = right->base.type;
6903 type_t *const type_left = skip_typeref(orig_type_left);
6904 type_t *const type_right = skip_typeref(orig_type_right);
6906 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6907 /* TODO: improve error message */
6908 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6909 errorf(HERE, "operation needs scalar types");
6914 expression->base.type = type_int;
6918 * Check the semantic restrictions of a binary assign expression.
6920 static void semantic_binexpr_assign(binary_expression_t *expression)
6922 expression_t *left = expression->left;
6923 type_t *orig_type_left = left->base.type;
6925 type_t *type_left = revert_automatic_type_conversion(left);
6926 type_left = skip_typeref(orig_type_left);
6928 if (!is_valid_assignment_lhs(left))
6931 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6932 report_assign_error(error, orig_type_left, expression->right,
6933 "assignment", &left->base.source_position);
6934 expression->right = create_implicit_cast(expression->right, orig_type_left);
6935 expression->base.type = orig_type_left;
6939 * Determine if the outermost operation (or parts thereof) of the given
6940 * expression has no effect in order to generate a warning about this fact.
6941 * Therefore in some cases this only examines some of the operands of the
6942 * expression (see comments in the function and examples below).
6944 * f() + 23; // warning, because + has no effect
6945 * x || f(); // no warning, because x controls execution of f()
6946 * x ? y : f(); // warning, because y has no effect
6947 * (void)x; // no warning to be able to suppress the warning
6948 * This function can NOT be used for an "expression has definitely no effect"-
6950 static bool expression_has_effect(const expression_t *const expr)
6952 switch (expr->kind) {
6953 case EXPR_UNKNOWN: break;
6954 case EXPR_INVALID: return true; /* do NOT warn */
6955 case EXPR_REFERENCE: return false;
6956 /* suppress the warning for microsoft __noop operations */
6957 case EXPR_CONST: return expr->conste.is_ms_noop;
6958 case EXPR_CHARACTER_CONSTANT: return false;
6959 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6960 case EXPR_STRING_LITERAL: return false;
6961 case EXPR_WIDE_STRING_LITERAL: return false;
6964 const call_expression_t *const call = &expr->call;
6965 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
6968 switch (call->function->builtin_symbol.symbol->ID) {
6969 case T___builtin_va_end: return true;
6970 default: return false;
6974 /* Generate the warning if either the left or right hand side of a
6975 * conditional expression has no effect */
6976 case EXPR_CONDITIONAL: {
6977 const conditional_expression_t *const cond = &expr->conditional;
6979 expression_has_effect(cond->true_expression) &&
6980 expression_has_effect(cond->false_expression);
6983 case EXPR_SELECT: return false;
6984 case EXPR_ARRAY_ACCESS: return false;
6985 case EXPR_SIZEOF: return false;
6986 case EXPR_CLASSIFY_TYPE: return false;
6987 case EXPR_ALIGNOF: return false;
6989 case EXPR_FUNCNAME: return false;
6990 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
6991 case EXPR_BUILTIN_CONSTANT_P: return false;
6992 case EXPR_BUILTIN_PREFETCH: return true;
6993 case EXPR_OFFSETOF: return false;
6994 case EXPR_VA_START: return true;
6995 case EXPR_VA_ARG: return true;
6996 case EXPR_STATEMENT: return true; // TODO
6997 case EXPR_COMPOUND_LITERAL: return false;
6999 case EXPR_UNARY_NEGATE: return false;
7000 case EXPR_UNARY_PLUS: return false;
7001 case EXPR_UNARY_BITWISE_NEGATE: return false;
7002 case EXPR_UNARY_NOT: return false;
7003 case EXPR_UNARY_DEREFERENCE: return false;
7004 case EXPR_UNARY_TAKE_ADDRESS: return false;
7005 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7006 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7007 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7008 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7010 /* Treat void casts as if they have an effect in order to being able to
7011 * suppress the warning */
7012 case EXPR_UNARY_CAST: {
7013 type_t *const type = skip_typeref(expr->base.type);
7014 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7017 case EXPR_UNARY_CAST_IMPLICIT: return true;
7018 case EXPR_UNARY_ASSUME: return true;
7020 case EXPR_BINARY_ADD: return false;
7021 case EXPR_BINARY_SUB: return false;
7022 case EXPR_BINARY_MUL: return false;
7023 case EXPR_BINARY_DIV: return false;
7024 case EXPR_BINARY_MOD: return false;
7025 case EXPR_BINARY_EQUAL: return false;
7026 case EXPR_BINARY_NOTEQUAL: return false;
7027 case EXPR_BINARY_LESS: return false;
7028 case EXPR_BINARY_LESSEQUAL: return false;
7029 case EXPR_BINARY_GREATER: return false;
7030 case EXPR_BINARY_GREATEREQUAL: return false;
7031 case EXPR_BINARY_BITWISE_AND: return false;
7032 case EXPR_BINARY_BITWISE_OR: return false;
7033 case EXPR_BINARY_BITWISE_XOR: return false;
7034 case EXPR_BINARY_SHIFTLEFT: return false;
7035 case EXPR_BINARY_SHIFTRIGHT: return false;
7036 case EXPR_BINARY_ASSIGN: return true;
7037 case EXPR_BINARY_MUL_ASSIGN: return true;
7038 case EXPR_BINARY_DIV_ASSIGN: return true;
7039 case EXPR_BINARY_MOD_ASSIGN: return true;
7040 case EXPR_BINARY_ADD_ASSIGN: return true;
7041 case EXPR_BINARY_SUB_ASSIGN: return true;
7042 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7043 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7044 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7045 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7046 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7048 /* Only examine the right hand side of && and ||, because the left hand
7049 * side already has the effect of controlling the execution of the right
7051 case EXPR_BINARY_LOGICAL_AND:
7052 case EXPR_BINARY_LOGICAL_OR:
7053 /* Only examine the right hand side of a comma expression, because the left
7054 * hand side has a separate warning */
7055 case EXPR_BINARY_COMMA:
7056 return expression_has_effect(expr->binary.right);
7058 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7059 case EXPR_BINARY_ISGREATER: return false;
7060 case EXPR_BINARY_ISGREATEREQUAL: return false;
7061 case EXPR_BINARY_ISLESS: return false;
7062 case EXPR_BINARY_ISLESSEQUAL: return false;
7063 case EXPR_BINARY_ISLESSGREATER: return false;
7064 case EXPR_BINARY_ISUNORDERED: return false;
7067 internal_errorf(HERE, "unexpected expression");
7070 static void semantic_comma(binary_expression_t *expression)
7072 if (warning.unused_value) {
7073 const expression_t *const left = expression->left;
7074 if (!expression_has_effect(left)) {
7075 warningf(&left->base.source_position,
7076 "left-hand operand of comma expression has no effect");
7079 expression->base.type = expression->right->base.type;
7082 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7083 static expression_t *parse_##binexpression_type(unsigned precedence, \
7084 expression_t *left) \
7087 source_position_t pos = *HERE; \
7089 expression_t *right = parse_sub_expression(precedence + lr); \
7091 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7092 binexpr->base.source_position = pos; \
7093 binexpr->binary.left = left; \
7094 binexpr->binary.right = right; \
7095 sfunc(&binexpr->binary); \
7100 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7101 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7102 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7103 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7104 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7105 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7106 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7107 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7108 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7110 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7111 semantic_comparison, 1)
7112 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7113 semantic_comparison, 1)
7114 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7115 semantic_comparison, 1)
7116 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7117 semantic_comparison, 1)
7119 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7120 semantic_binexpr_arithmetic, 1)
7121 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7122 semantic_binexpr_arithmetic, 1)
7123 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7124 semantic_binexpr_arithmetic, 1)
7125 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7126 semantic_logical_op, 1)
7127 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7128 semantic_logical_op, 1)
7129 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7130 semantic_shift_op, 1)
7131 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7132 semantic_shift_op, 1)
7133 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7134 semantic_arithmetic_addsubb_assign, 0)
7135 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7136 semantic_arithmetic_addsubb_assign, 0)
7137 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7138 semantic_arithmetic_assign, 0)
7139 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7140 semantic_arithmetic_assign, 0)
7141 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7142 semantic_arithmetic_assign, 0)
7143 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7144 semantic_arithmetic_assign, 0)
7145 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7146 semantic_arithmetic_assign, 0)
7147 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7148 semantic_arithmetic_assign, 0)
7149 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7150 semantic_arithmetic_assign, 0)
7151 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7152 semantic_arithmetic_assign, 0)
7154 static expression_t *parse_sub_expression(unsigned precedence)
7156 if (token.type < 0) {
7157 return expected_expression_error();
7160 expression_parser_function_t *parser
7161 = &expression_parsers[token.type];
7162 source_position_t source_position = token.source_position;
7165 if (parser->parser != NULL) {
7166 left = parser->parser(parser->precedence);
7168 left = parse_primary_expression();
7170 assert(left != NULL);
7171 left->base.source_position = source_position;
7174 if (token.type < 0) {
7175 return expected_expression_error();
7178 parser = &expression_parsers[token.type];
7179 if (parser->infix_parser == NULL)
7181 if (parser->infix_precedence < precedence)
7184 left = parser->infix_parser(parser->infix_precedence, left);
7186 assert(left != NULL);
7187 assert(left->kind != EXPR_UNKNOWN);
7188 left->base.source_position = source_position;
7195 * Parse an expression.
7197 static expression_t *parse_expression(void)
7199 return parse_sub_expression(1);
7203 * Register a parser for a prefix-like operator with given precedence.
7205 * @param parser the parser function
7206 * @param token_type the token type of the prefix token
7207 * @param precedence the precedence of the operator
7209 static void register_expression_parser(parse_expression_function parser,
7210 int token_type, unsigned precedence)
7212 expression_parser_function_t *entry = &expression_parsers[token_type];
7214 if (entry->parser != NULL) {
7215 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7216 panic("trying to register multiple expression parsers for a token");
7218 entry->parser = parser;
7219 entry->precedence = precedence;
7223 * Register a parser for an infix operator with given precedence.
7225 * @param parser the parser function
7226 * @param token_type the token type of the infix operator
7227 * @param precedence the precedence of the operator
7229 static void register_infix_parser(parse_expression_infix_function parser,
7230 int token_type, unsigned precedence)
7232 expression_parser_function_t *entry = &expression_parsers[token_type];
7234 if (entry->infix_parser != NULL) {
7235 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7236 panic("trying to register multiple infix expression parsers for a "
7239 entry->infix_parser = parser;
7240 entry->infix_precedence = precedence;
7244 * Initialize the expression parsers.
7246 static void init_expression_parsers(void)
7248 memset(&expression_parsers, 0, sizeof(expression_parsers));
7250 register_infix_parser(parse_array_expression, '[', 30);
7251 register_infix_parser(parse_call_expression, '(', 30);
7252 register_infix_parser(parse_select_expression, '.', 30);
7253 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7254 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7256 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7259 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7260 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7261 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7262 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7263 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7264 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7265 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7266 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7267 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7268 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7269 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7270 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7271 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7272 T_EXCLAMATIONMARKEQUAL, 13);
7273 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7274 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7275 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7276 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7277 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7278 register_infix_parser(parse_conditional_expression, '?', 7);
7279 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7280 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7281 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7282 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7283 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7284 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7285 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7286 T_LESSLESSEQUAL, 2);
7287 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7288 T_GREATERGREATEREQUAL, 2);
7289 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7291 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7293 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7296 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7298 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7299 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7300 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7301 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7302 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7303 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7304 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7306 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7308 register_expression_parser(parse_sizeof, T_sizeof, 25);
7309 register_expression_parser(parse_alignof, T___alignof__, 25);
7310 register_expression_parser(parse_extension, T___extension__, 25);
7311 register_expression_parser(parse_builtin_classify_type,
7312 T___builtin_classify_type, 25);
7316 * Parse a asm statement arguments specification.
7318 static asm_argument_t *parse_asm_arguments(bool is_out)
7320 asm_argument_t *result = NULL;
7321 asm_argument_t *last = NULL;
7323 while (token.type == T_STRING_LITERAL || token.type == '[') {
7324 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7325 memset(argument, 0, sizeof(argument[0]));
7327 if (token.type == '[') {
7329 if (token.type != T_IDENTIFIER) {
7330 parse_error_expected("while parsing asm argument",
7331 T_IDENTIFIER, NULL);
7334 argument->symbol = token.v.symbol;
7339 argument->constraints = parse_string_literals();
7341 expression_t *expression = parse_expression();
7342 argument->expression = expression;
7343 if (is_out && !is_lvalue(expression)) {
7344 errorf(&expression->base.source_position,
7345 "asm output argument is not an lvalue");
7349 set_address_taken(expression, true);
7352 last->next = argument;
7358 if (token.type != ',')
7369 * Parse a asm statement clobber specification.
7371 static asm_clobber_t *parse_asm_clobbers(void)
7373 asm_clobber_t *result = NULL;
7374 asm_clobber_t *last = NULL;
7376 while(token.type == T_STRING_LITERAL) {
7377 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7378 clobber->clobber = parse_string_literals();
7381 last->next = clobber;
7387 if (token.type != ',')
7396 * Parse an asm statement.
7398 static statement_t *parse_asm_statement(void)
7402 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7403 statement->base.source_position = token.source_position;
7405 asm_statement_t *asm_statement = &statement->asms;
7407 if (token.type == T_volatile) {
7409 asm_statement->is_volatile = true;
7413 add_anchor_token(')');
7414 add_anchor_token(':');
7415 asm_statement->asm_text = parse_string_literals();
7417 if (token.type != ':') {
7418 rem_anchor_token(':');
7423 asm_statement->outputs = parse_asm_arguments(true);
7424 if (token.type != ':') {
7425 rem_anchor_token(':');
7430 asm_statement->inputs = parse_asm_arguments(false);
7431 if (token.type != ':') {
7432 rem_anchor_token(':');
7435 rem_anchor_token(':');
7438 asm_statement->clobbers = parse_asm_clobbers();
7441 rem_anchor_token(')');
7446 return create_invalid_statement();
7450 * Parse a case statement.
7452 static statement_t *parse_case_statement(void)
7456 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7458 statement->base.source_position = token.source_position;
7459 statement->case_label.expression = parse_expression();
7461 if (c_mode & _GNUC) {
7462 if (token.type == T_DOTDOTDOT) {
7464 statement->case_label.end_range = parse_expression();
7470 if (! is_constant_expression(statement->case_label.expression)) {
7471 errorf(&statement->base.source_position,
7472 "case label does not reduce to an integer constant");
7474 /* TODO: check if the case label is already known */
7475 if (current_switch != NULL) {
7476 /* link all cases into the switch statement */
7477 if (current_switch->last_case == NULL) {
7478 current_switch->first_case =
7479 current_switch->last_case = &statement->case_label;
7481 current_switch->last_case->next = &statement->case_label;
7484 errorf(&statement->base.source_position,
7485 "case label not within a switch statement");
7488 statement->case_label.statement = parse_statement();
7492 return create_invalid_statement();
7496 * Finds an existing default label of a switch statement.
7498 static case_label_statement_t *
7499 find_default_label(const switch_statement_t *statement)
7501 case_label_statement_t *label = statement->first_case;
7502 for ( ; label != NULL; label = label->next) {
7503 if (label->expression == NULL)
7510 * Parse a default statement.
7512 static statement_t *parse_default_statement(void)
7516 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7518 statement->base.source_position = token.source_position;
7521 if (current_switch != NULL) {
7522 const case_label_statement_t *def_label = find_default_label(current_switch);
7523 if (def_label != NULL) {
7524 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7525 &def_label->base.source_position);
7527 /* link all cases into the switch statement */
7528 if (current_switch->last_case == NULL) {
7529 current_switch->first_case =
7530 current_switch->last_case = &statement->case_label;
7532 current_switch->last_case->next = &statement->case_label;
7536 errorf(&statement->base.source_position,
7537 "'default' label not within a switch statement");
7539 statement->case_label.statement = parse_statement();
7543 return create_invalid_statement();
7547 * Return the declaration for a given label symbol or create a new one.
7549 static declaration_t *get_label(symbol_t *symbol)
7551 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7552 assert(current_function != NULL);
7553 /* if we found a label in the same function, then we already created the
7555 if (candidate != NULL
7556 && candidate->parent_scope == ¤t_function->scope) {
7560 /* otherwise we need to create a new one */
7561 declaration_t *const declaration = allocate_declaration_zero();
7562 declaration->namespc = NAMESPACE_LABEL;
7563 declaration->symbol = symbol;
7565 label_push(declaration);
7571 * Parse a label statement.
7573 static statement_t *parse_label_statement(void)
7575 assert(token.type == T_IDENTIFIER);
7576 symbol_t *symbol = token.v.symbol;
7579 declaration_t *label = get_label(symbol);
7581 /* if source position is already set then the label is defined twice,
7582 * otherwise it was just mentioned in a goto so far */
7583 if (label->source_position.input_name != NULL) {
7584 errorf(HERE, "duplicate label '%Y' (declared %P)",
7585 symbol, &label->source_position);
7587 label->source_position = token.source_position;
7590 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7592 statement->base.source_position = token.source_position;
7593 statement->label.label = label;
7597 if (token.type == '}') {
7598 /* TODO only warn? */
7600 warningf(HERE, "label at end of compound statement");
7601 statement->label.statement = create_empty_statement();
7603 errorf(HERE, "label at end of compound statement");
7604 statement->label.statement = create_invalid_statement();
7608 if (token.type == ';') {
7609 /* eat an empty statement here, to avoid the warning about an empty
7610 * after a label. label:; is commonly used to have a label before
7612 statement->label.statement = create_empty_statement();
7615 statement->label.statement = parse_statement();
7619 /* remember the labels's in a list for later checking */
7620 if (label_last == NULL) {
7621 label_first = &statement->label;
7623 label_last->next = &statement->label;
7625 label_last = &statement->label;
7631 * Parse an if statement.
7633 static statement_t *parse_if(void)
7637 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7638 statement->base.source_position = token.source_position;
7641 add_anchor_token(')');
7642 statement->ifs.condition = parse_expression();
7643 rem_anchor_token(')');
7646 add_anchor_token(T_else);
7647 statement->ifs.true_statement = parse_statement();
7648 rem_anchor_token(T_else);
7650 if (token.type == T_else) {
7652 statement->ifs.false_statement = parse_statement();
7657 return create_invalid_statement();
7661 * Parse a switch statement.
7663 static statement_t *parse_switch(void)
7667 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7668 statement->base.source_position = token.source_position;
7671 expression_t *const expr = parse_expression();
7672 type_t * type = skip_typeref(expr->base.type);
7673 if (is_type_integer(type)) {
7674 type = promote_integer(type);
7675 } else if (is_type_valid(type)) {
7676 errorf(&expr->base.source_position,
7677 "switch quantity is not an integer, but '%T'", type);
7678 type = type_error_type;
7680 statement->switchs.expression = create_implicit_cast(expr, type);
7683 switch_statement_t *rem = current_switch;
7684 current_switch = &statement->switchs;
7685 statement->switchs.body = parse_statement();
7686 current_switch = rem;
7688 if (warning.switch_default &&
7689 find_default_label(&statement->switchs) == NULL) {
7690 warningf(&statement->base.source_position, "switch has no default case");
7695 return create_invalid_statement();
7698 static statement_t *parse_loop_body(statement_t *const loop)
7700 statement_t *const rem = current_loop;
7701 current_loop = loop;
7703 statement_t *const body = parse_statement();
7710 * Parse a while statement.
7712 static statement_t *parse_while(void)
7716 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7717 statement->base.source_position = token.source_position;
7720 add_anchor_token(')');
7721 statement->whiles.condition = parse_expression();
7722 rem_anchor_token(')');
7725 statement->whiles.body = parse_loop_body(statement);
7729 return create_invalid_statement();
7733 * Parse a do statement.
7735 static statement_t *parse_do(void)
7739 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7741 statement->base.source_position = token.source_position;
7743 add_anchor_token(T_while);
7744 statement->do_while.body = parse_loop_body(statement);
7745 rem_anchor_token(T_while);
7749 add_anchor_token(')');
7750 statement->do_while.condition = parse_expression();
7751 rem_anchor_token(')');
7757 return create_invalid_statement();
7761 * Parse a for statement.
7763 static statement_t *parse_for(void)
7767 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7768 statement->base.source_position = token.source_position;
7770 int top = environment_top();
7771 scope_t *last_scope = scope;
7772 set_scope(&statement->fors.scope);
7775 add_anchor_token(')');
7777 if (token.type != ';') {
7778 if (is_declaration_specifier(&token, false)) {
7779 parse_declaration(record_declaration);
7781 add_anchor_token(';');
7782 expression_t *const init = parse_expression();
7783 statement->fors.initialisation = init;
7784 if (warning.unused_value && !expression_has_effect(init)) {
7785 warningf(&init->base.source_position,
7786 "initialisation of 'for'-statement has no effect");
7788 rem_anchor_token(';');
7795 if (token.type != ';') {
7796 add_anchor_token(';');
7797 statement->fors.condition = parse_expression();
7798 rem_anchor_token(';');
7801 if (token.type != ')') {
7802 expression_t *const step = parse_expression();
7803 statement->fors.step = step;
7804 if (warning.unused_value && !expression_has_effect(step)) {
7805 warningf(&step->base.source_position,
7806 "step of 'for'-statement has no effect");
7809 rem_anchor_token(')');
7811 statement->fors.body = parse_loop_body(statement);
7813 assert(scope == &statement->fors.scope);
7814 set_scope(last_scope);
7815 environment_pop_to(top);
7820 rem_anchor_token(')');
7821 assert(scope == &statement->fors.scope);
7822 set_scope(last_scope);
7823 environment_pop_to(top);
7825 return create_invalid_statement();
7829 * Parse a goto statement.
7831 static statement_t *parse_goto(void)
7835 if (token.type != T_IDENTIFIER) {
7836 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7840 symbol_t *symbol = token.v.symbol;
7843 declaration_t *label = get_label(symbol);
7845 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7846 statement->base.source_position = token.source_position;
7848 statement->gotos.label = label;
7850 /* remember the goto's in a list for later checking */
7851 if (goto_last == NULL) {
7852 goto_first = &statement->gotos;
7854 goto_last->next = &statement->gotos;
7856 goto_last = &statement->gotos;
7862 return create_invalid_statement();
7866 * Parse a continue statement.
7868 static statement_t *parse_continue(void)
7870 statement_t *statement;
7871 if (current_loop == NULL) {
7872 errorf(HERE, "continue statement not within loop");
7873 statement = create_invalid_statement();
7875 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7877 statement->base.source_position = token.source_position;
7885 return create_invalid_statement();
7889 * Parse a break statement.
7891 static statement_t *parse_break(void)
7893 statement_t *statement;
7894 if (current_switch == NULL && current_loop == NULL) {
7895 errorf(HERE, "break statement not within loop or switch");
7896 statement = create_invalid_statement();
7898 statement = allocate_statement_zero(STATEMENT_BREAK);
7900 statement->base.source_position = token.source_position;
7908 return create_invalid_statement();
7912 * Parse a __leave statement.
7914 static statement_t *parse_leave(void)
7916 statement_t *statement;
7917 if (current_try == NULL) {
7918 errorf(HERE, "__leave statement not within __try");
7919 statement = create_invalid_statement();
7921 statement = allocate_statement_zero(STATEMENT_LEAVE);
7923 statement->base.source_position = token.source_position;
7931 return create_invalid_statement();
7935 * Check if a given declaration represents a local variable.
7937 static bool is_local_var_declaration(const declaration_t *declaration) {
7938 switch ((storage_class_tag_t) declaration->storage_class) {
7939 case STORAGE_CLASS_AUTO:
7940 case STORAGE_CLASS_REGISTER: {
7941 const type_t *type = skip_typeref(declaration->type);
7942 if (is_type_function(type)) {
7954 * Check if a given declaration represents a variable.
7956 static bool is_var_declaration(const declaration_t *declaration) {
7957 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7960 const type_t *type = skip_typeref(declaration->type);
7961 return !is_type_function(type);
7965 * Check if a given expression represents a local variable.
7967 static bool is_local_variable(const expression_t *expression)
7969 if (expression->base.kind != EXPR_REFERENCE) {
7972 const declaration_t *declaration = expression->reference.declaration;
7973 return is_local_var_declaration(declaration);
7977 * Check if a given expression represents a local variable and
7978 * return its declaration then, else return NULL.
7980 declaration_t *expr_is_variable(const expression_t *expression)
7982 if (expression->base.kind != EXPR_REFERENCE) {
7985 declaration_t *declaration = expression->reference.declaration;
7986 if (is_var_declaration(declaration))
7992 * Parse a return statement.
7994 static statement_t *parse_return(void)
7996 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
7997 statement->base.source_position = token.source_position;
8001 expression_t *return_value = NULL;
8002 if (token.type != ';') {
8003 return_value = parse_expression();
8007 const type_t *const func_type = current_function->type;
8008 assert(is_type_function(func_type));
8009 type_t *const return_type = skip_typeref(func_type->function.return_type);
8011 if (return_value != NULL) {
8012 type_t *return_value_type = skip_typeref(return_value->base.type);
8014 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8015 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8016 warningf(&statement->base.source_position,
8017 "'return' with a value, in function returning void");
8018 return_value = NULL;
8020 assign_error_t error = semantic_assign(return_type, return_value);
8021 report_assign_error(error, return_type, return_value, "'return'",
8022 &statement->base.source_position);
8023 return_value = create_implicit_cast(return_value, return_type);
8025 /* check for returning address of a local var */
8026 if (return_value != NULL &&
8027 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8028 const expression_t *expression = return_value->unary.value;
8029 if (is_local_variable(expression)) {
8030 warningf(&statement->base.source_position,
8031 "function returns address of local variable");
8035 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8036 warningf(&statement->base.source_position,
8037 "'return' without value, in function returning non-void");
8040 statement->returns.value = return_value;
8044 return create_invalid_statement();
8048 * Parse a declaration statement.
8050 static statement_t *parse_declaration_statement(void)
8052 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8054 statement->base.source_position = token.source_position;
8056 declaration_t *before = last_declaration;
8057 parse_declaration(record_declaration);
8059 if (before == NULL) {
8060 statement->declaration.declarations_begin = scope->declarations;
8062 statement->declaration.declarations_begin = before->next;
8064 statement->declaration.declarations_end = last_declaration;
8070 * Parse an expression statement, ie. expr ';'.
8072 static statement_t *parse_expression_statement(void)
8074 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8076 statement->base.source_position = token.source_position;
8077 expression_t *const expr = parse_expression();
8078 statement->expression.expression = expr;
8084 return create_invalid_statement();
8088 * Parse a microsoft __try { } __finally { } or
8089 * __try{ } __except() { }
8091 static statement_t *parse_ms_try_statment(void) {
8092 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8094 statement->base.source_position = token.source_position;
8097 ms_try_statement_t *rem = current_try;
8098 current_try = &statement->ms_try;
8099 statement->ms_try.try_statement = parse_compound_statement(false);
8102 if (token.type == T___except) {
8105 add_anchor_token(')');
8106 expression_t *const expr = parse_expression();
8107 type_t * type = skip_typeref(expr->base.type);
8108 if (is_type_integer(type)) {
8109 type = promote_integer(type);
8110 } else if (is_type_valid(type)) {
8111 errorf(&expr->base.source_position,
8112 "__expect expression is not an integer, but '%T'", type);
8113 type = type_error_type;
8115 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8116 rem_anchor_token(')');
8118 statement->ms_try.final_statement = parse_compound_statement(false);
8119 } else if (token.type == T__finally) {
8121 statement->ms_try.final_statement = parse_compound_statement(false);
8123 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8124 return create_invalid_statement();
8128 return create_invalid_statement();
8132 * Parse a statement.
8133 * There's also parse_statement() which additionally checks for
8134 * "statement has no effect" warnings
8136 static statement_t *intern_parse_statement(void)
8138 statement_t *statement = NULL;
8140 /* declaration or statement */
8141 add_anchor_token(';');
8142 switch(token.type) {
8144 statement = parse_asm_statement();
8148 statement = parse_case_statement();
8152 statement = parse_default_statement();
8156 statement = parse_compound_statement(false);
8160 statement = parse_if ();
8164 statement = parse_switch();
8168 statement = parse_while();
8172 statement = parse_do();
8176 statement = parse_for();
8180 statement = parse_goto();
8184 statement = parse_continue();
8188 statement = parse_break();
8192 statement = parse_leave();
8196 statement = parse_return();
8200 if (warning.empty_statement) {
8201 warningf(HERE, "statement is empty");
8203 statement = create_empty_statement();
8208 if (look_ahead(1)->type == ':') {
8209 statement = parse_label_statement();
8213 if (is_typedef_symbol(token.v.symbol)) {
8214 statement = parse_declaration_statement();
8218 statement = parse_expression_statement();
8221 case T___extension__:
8222 /* this can be a prefix to a declaration or an expression statement */
8223 /* we simply eat it now and parse the rest with tail recursion */
8226 } while(token.type == T___extension__);
8227 statement = parse_statement();
8231 statement = parse_declaration_statement();
8235 statement = parse_ms_try_statment();
8239 statement = parse_expression_statement();
8242 rem_anchor_token(';');
8244 assert(statement != NULL
8245 && statement->base.source_position.input_name != NULL);
8251 * parse a statement and emits "statement has no effect" warning if needed
8252 * (This is really a wrapper around intern_parse_statement with check for 1
8253 * single warning. It is needed, because for statement expressions we have
8254 * to avoid the warning on the last statement)
8256 static statement_t *parse_statement(void)
8258 statement_t *statement = intern_parse_statement();
8260 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8261 expression_t *expression = statement->expression.expression;
8262 if (!expression_has_effect(expression)) {
8263 warningf(&expression->base.source_position,
8264 "statement has no effect");
8272 * Parse a compound statement.
8274 static statement_t *parse_compound_statement(bool inside_expression_statement)
8276 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8278 statement->base.source_position = token.source_position;
8281 add_anchor_token('}');
8283 int top = environment_top();
8284 scope_t *last_scope = scope;
8285 set_scope(&statement->compound.scope);
8287 statement_t *last_statement = NULL;
8289 while(token.type != '}' && token.type != T_EOF) {
8290 statement_t *sub_statement = intern_parse_statement();
8291 if (is_invalid_statement(sub_statement)) {
8292 /* an error occurred. if we are at an anchor, return */
8298 if (last_statement != NULL) {
8299 last_statement->base.next = sub_statement;
8301 statement->compound.statements = sub_statement;
8304 while(sub_statement->base.next != NULL)
8305 sub_statement = sub_statement->base.next;
8307 last_statement = sub_statement;
8310 if (token.type == '}') {
8313 errorf(&statement->base.source_position,
8314 "end of file while looking for closing '}'");
8317 /* look over all statements again to produce no effect warnings */
8318 if (warning.unused_value) {
8319 statement_t *sub_statement = statement->compound.statements;
8320 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8321 if (sub_statement->kind != STATEMENT_EXPRESSION)
8323 /* don't emit a warning for the last expression in an expression
8324 * statement as it has always an effect */
8325 if (inside_expression_statement && sub_statement->base.next == NULL)
8328 expression_t *expression = sub_statement->expression.expression;
8329 if (!expression_has_effect(expression)) {
8330 warningf(&expression->base.source_position,
8331 "statement has no effect");
8337 rem_anchor_token('}');
8338 assert(scope == &statement->compound.scope);
8339 set_scope(last_scope);
8340 environment_pop_to(top);
8346 * Initialize builtin types.
8348 static void initialize_builtin_types(void)
8350 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8351 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8352 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8353 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8354 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8355 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8356 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8357 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8359 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8360 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8361 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8362 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8366 * Check for unused global static functions and variables
8368 static void check_unused_globals(void)
8370 if (!warning.unused_function && !warning.unused_variable)
8373 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8375 decl->modifiers & DM_USED ||
8376 decl->storage_class != STORAGE_CLASS_STATIC)
8379 type_t *const type = decl->type;
8381 if (is_type_function(skip_typeref(type))) {
8382 if (!warning.unused_function || decl->is_inline)
8385 s = (decl->init.statement != NULL ? "defined" : "declared");
8387 if (!warning.unused_variable)
8393 warningf(&decl->source_position, "'%#T' %s but not used",
8394 type, decl->symbol, s);
8398 static void parse_global_asm(void)
8403 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8404 statement->base.source_position = token.source_position;
8405 statement->asms.asm_text = parse_string_literals();
8406 statement->base.next = unit->global_asm;
8407 unit->global_asm = statement;
8416 * Parse a translation unit.
8418 static void parse_translation_unit(void)
8420 while(token.type != T_EOF) {
8421 switch (token.type) {
8423 /* TODO error in strict mode */
8424 warningf(HERE, "stray ';' outside of function");
8433 parse_external_declaration();
8442 * @return the translation unit or NULL if errors occurred.
8444 void start_parsing(void)
8446 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8447 label_stack = NEW_ARR_F(stack_entry_t, 0);
8448 diagnostic_count = 0;
8452 type_set_output(stderr);
8453 ast_set_output(stderr);
8455 assert(unit == NULL);
8456 unit = allocate_ast_zero(sizeof(unit[0]));
8458 assert(global_scope == NULL);
8459 global_scope = &unit->scope;
8461 assert(scope == NULL);
8462 set_scope(&unit->scope);
8464 initialize_builtin_types();
8467 translation_unit_t *finish_parsing(void)
8469 assert(scope == &unit->scope);
8471 last_declaration = NULL;
8473 assert(global_scope == &unit->scope);
8474 check_unused_globals();
8475 global_scope = NULL;
8477 DEL_ARR_F(environment_stack);
8478 DEL_ARR_F(label_stack);
8480 translation_unit_t *result = unit;
8487 lookahead_bufpos = 0;
8488 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8491 parse_translation_unit();
8495 * Initialize the parser.
8497 void init_parser(void)
8500 /* add predefined symbols for extended-decl-modifier */
8501 sym_align = symbol_table_insert("align");
8502 sym_allocate = symbol_table_insert("allocate");
8503 sym_dllimport = symbol_table_insert("dllimport");
8504 sym_dllexport = symbol_table_insert("dllexport");
8505 sym_naked = symbol_table_insert("naked");
8506 sym_noinline = symbol_table_insert("noinline");
8507 sym_noreturn = symbol_table_insert("noreturn");
8508 sym_nothrow = symbol_table_insert("nothrow");
8509 sym_novtable = symbol_table_insert("novtable");
8510 sym_property = symbol_table_insert("property");
8511 sym_get = symbol_table_insert("get");
8512 sym_put = symbol_table_insert("put");
8513 sym_selectany = symbol_table_insert("selectany");
8514 sym_thread = symbol_table_insert("thread");
8515 sym_uuid = symbol_table_insert("uuid");
8516 sym_deprecated = symbol_table_insert("deprecated");
8517 sym_restrict = symbol_table_insert("restrict");
8518 sym_noalias = symbol_table_insert("noalias");
8520 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8522 init_expression_parsers();
8523 obstack_init(&temp_obst);
8525 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8526 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8530 * Terminate the parser.
8532 void exit_parser(void)
8534 obstack_free(&temp_obst, NULL);