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 * @param kind type kind to allocate
396 * @param source_position the source position of the type definition
398 static type_t *allocate_type_zero(type_kind_t kind, const source_position_t *source_position)
400 size_t size = get_type_struct_size(kind);
401 type_t *res = obstack_alloc(type_obst, size);
402 memset(res, 0, size);
404 res->base.kind = kind;
405 res->base.source_position = *source_position;
410 * Returns the size of an initializer node.
412 * @param kind the initializer kind
414 static size_t get_initializer_size(initializer_kind_t kind)
416 static const size_t sizes[] = {
417 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
418 [INITIALIZER_STRING] = sizeof(initializer_string_t),
419 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
420 [INITIALIZER_LIST] = sizeof(initializer_list_t),
421 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
423 assert(kind < sizeof(sizes) / sizeof(*sizes));
424 assert(sizes[kind] != 0);
429 * Allocate an initializer node of given kind and initialize all
432 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
434 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
441 * Free a type from the type obstack.
443 static void free_type(void *type)
445 obstack_free(type_obst, type);
449 * Returns the index of the top element of the environment stack.
451 static size_t environment_top(void)
453 return ARR_LEN(environment_stack);
457 * Returns the index of the top element of the label stack.
459 static size_t label_top(void)
461 return ARR_LEN(label_stack);
465 * Return the next token.
467 static inline void next_token(void)
469 token = lookahead_buffer[lookahead_bufpos];
470 lookahead_buffer[lookahead_bufpos] = lexer_token;
473 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
476 print_token(stderr, &token);
477 fprintf(stderr, "\n");
482 * Return the next token with a given lookahead.
484 static inline const token_t *look_ahead(int num)
486 assert(num > 0 && num <= MAX_LOOKAHEAD);
487 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
488 return &lookahead_buffer[pos];
492 * Adds a token to the token anchor set (a multi-set).
494 static void add_anchor_token(int token_type) {
495 assert(0 <= token_type && token_type < T_LAST_TOKEN);
496 ++token_anchor_set[token_type];
499 static int save_and_reset_anchor_state(int token_type) {
500 assert(0 <= token_type && token_type < T_LAST_TOKEN);
501 int count = token_anchor_set[token_type];
502 token_anchor_set[token_type] = 0;
506 static void restore_anchor_state(int token_type, int count) {
507 assert(0 <= token_type && token_type < T_LAST_TOKEN);
508 token_anchor_set[token_type] = count;
512 * Remove a token from the token anchor set (a multi-set).
514 static void rem_anchor_token(int token_type) {
515 assert(0 <= token_type && token_type < T_LAST_TOKEN);
516 --token_anchor_set[token_type];
519 static bool at_anchor(void) {
522 return token_anchor_set[token.type];
526 * Eat tokens until a matching token is found.
528 static void eat_until_matching_token(int type) {
529 unsigned parenthesis_count = 0;
530 unsigned brace_count = 0;
531 unsigned bracket_count = 0;
535 case '(': end_token = ')'; break;
536 case '{': end_token = '}'; break;
537 case '[': end_token = ']'; break;
538 default: end_token = type; break;
541 while(token.type != end_token ||
542 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
546 case '(': ++parenthesis_count; break;
547 case '{': ++brace_count; break;
548 case '[': ++bracket_count; break;
550 if (parenthesis_count > 0)
558 if (bracket_count > 0)
569 * Eat input tokens until an anchor is found.
571 static void eat_until_anchor(void) {
572 if (token.type == T_EOF)
574 while(token_anchor_set[token.type] == 0) {
575 if (token.type == '(' || token.type == '{' || token.type == '[')
576 eat_until_matching_token(token.type);
577 if (token.type == T_EOF)
583 static void eat_block(void) {
584 eat_until_matching_token('{');
585 if (token.type == '}')
590 * eat all token until a ';' is reached or a stop token is found.
592 static void eat_statement(void) {
593 eat_until_matching_token(';');
594 if (token.type == ';')
598 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
601 * Report a parse error because an expected token was not found.
604 #if defined __GNUC__ && __GNUC__ >= 4
605 __attribute__((sentinel))
607 void parse_error_expected(const char *message, ...)
609 if (message != NULL) {
610 errorf(HERE, "%s", message);
613 va_start(ap, message);
614 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
619 * Report a type error.
621 static void type_error(const char *msg, const source_position_t *source_position,
624 errorf(source_position, "%s, but found type '%T'", msg, type);
628 * Report an incompatible type.
630 static void type_error_incompatible(const char *msg,
631 const source_position_t *source_position, type_t *type1, type_t *type2)
633 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
638 * Expect the the current token is the expected token.
639 * If not, generate an error, eat the current statement,
640 * and goto the end_error label.
642 #define expect(expected) \
644 if (UNLIKELY(token.type != (expected))) { \
645 parse_error_expected(NULL, (expected), NULL); \
646 add_anchor_token(expected); \
647 eat_until_anchor(); \
648 if (token.type == expected) \
650 rem_anchor_token(expected); \
656 static void set_scope(scope_t *new_scope)
659 scope->last_declaration = last_declaration;
663 last_declaration = new_scope->last_declaration;
667 * Search a symbol in a given namespace and returns its declaration or
668 * NULL if this symbol was not found.
670 static declaration_t *get_declaration(const symbol_t *const symbol,
671 const namespace_t namespc)
673 declaration_t *declaration = symbol->declaration;
674 for( ; declaration != NULL; declaration = declaration->symbol_next) {
675 if (declaration->namespc == namespc)
683 * pushs an environment_entry on the environment stack and links the
684 * corresponding symbol to the new entry
686 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
688 symbol_t *symbol = declaration->symbol;
689 namespace_t namespc = (namespace_t) declaration->namespc;
691 /* replace/add declaration into declaration list of the symbol */
692 declaration_t *iter = symbol->declaration;
694 symbol->declaration = declaration;
696 declaration_t *iter_last = NULL;
697 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
698 /* replace an entry? */
699 if (iter->namespc == namespc) {
700 if (iter_last == NULL) {
701 symbol->declaration = declaration;
703 iter_last->symbol_next = declaration;
705 declaration->symbol_next = iter->symbol_next;
710 assert(iter_last->symbol_next == NULL);
711 iter_last->symbol_next = declaration;
715 /* remember old declaration */
717 entry.symbol = symbol;
718 entry.old_declaration = iter;
719 entry.namespc = (unsigned short) namespc;
720 ARR_APP1(stack_entry_t, *stack_ptr, entry);
723 static void environment_push(declaration_t *declaration)
725 assert(declaration->source_position.input_name != NULL);
726 assert(declaration->parent_scope != NULL);
727 stack_push(&environment_stack, declaration);
730 static void label_push(declaration_t *declaration)
732 declaration->parent_scope = ¤t_function->scope;
733 stack_push(&label_stack, declaration);
737 * pops symbols from the environment stack until @p new_top is the top element
739 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
741 stack_entry_t *stack = *stack_ptr;
742 size_t top = ARR_LEN(stack);
745 assert(new_top <= top);
749 for(i = top; i > new_top; --i) {
750 stack_entry_t *entry = &stack[i - 1];
752 declaration_t *old_declaration = entry->old_declaration;
753 symbol_t *symbol = entry->symbol;
754 namespace_t namespc = (namespace_t)entry->namespc;
756 /* replace/remove declaration */
757 declaration_t *declaration = symbol->declaration;
758 assert(declaration != NULL);
759 if (declaration->namespc == namespc) {
760 if (old_declaration == NULL) {
761 symbol->declaration = declaration->symbol_next;
763 symbol->declaration = old_declaration;
766 declaration_t *iter_last = declaration;
767 declaration_t *iter = declaration->symbol_next;
768 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
769 /* replace an entry? */
770 if (iter->namespc == namespc) {
771 assert(iter_last != NULL);
772 iter_last->symbol_next = old_declaration;
773 if (old_declaration != NULL) {
774 old_declaration->symbol_next = iter->symbol_next;
779 assert(iter != NULL);
783 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
786 static void environment_pop_to(size_t new_top)
788 stack_pop_to(&environment_stack, new_top);
791 static void label_pop_to(size_t new_top)
793 stack_pop_to(&label_stack, new_top);
797 static int get_rank(const type_t *type)
799 assert(!is_typeref(type));
800 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
801 * and esp. footnote 108). However we can't fold constants (yet), so we
802 * can't decide whether unsigned int is possible, while int always works.
803 * (unsigned int would be preferable when possible... for stuff like
804 * struct { enum { ... } bla : 4; } ) */
805 if (type->kind == TYPE_ENUM)
806 return ATOMIC_TYPE_INT;
808 assert(type->kind == TYPE_ATOMIC);
809 return type->atomic.akind;
812 static type_t *promote_integer(type_t *type)
814 if (type->kind == TYPE_BITFIELD)
815 type = type->bitfield.base_type;
817 if (get_rank(type) < ATOMIC_TYPE_INT)
824 * Create a cast expression.
826 * @param expression the expression to cast
827 * @param dest_type the destination type
829 static expression_t *create_cast_expression(expression_t *expression,
832 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
834 cast->unary.value = expression;
835 cast->base.type = dest_type;
841 * Check if a given expression represents the 0 pointer constant.
843 static bool is_null_pointer_constant(const expression_t *expression)
845 /* skip void* cast */
846 if (expression->kind == EXPR_UNARY_CAST
847 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
848 expression = expression->unary.value;
851 /* TODO: not correct yet, should be any constant integer expression
852 * which evaluates to 0 */
853 if (expression->kind != EXPR_CONST)
856 type_t *const type = skip_typeref(expression->base.type);
857 if (!is_type_integer(type))
860 return expression->conste.v.int_value == 0;
864 * Create an implicit cast expression.
866 * @param expression the expression to cast
867 * @param dest_type the destination type
869 static expression_t *create_implicit_cast(expression_t *expression,
872 type_t *const source_type = expression->base.type;
874 if (source_type == dest_type)
877 return create_cast_expression(expression, dest_type);
880 typedef enum assign_error_t {
882 ASSIGN_ERROR_INCOMPATIBLE,
883 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
884 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
885 ASSIGN_WARNING_POINTER_FROM_INT,
886 ASSIGN_WARNING_INT_FROM_POINTER
889 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
890 const expression_t *const right,
892 const source_position_t *source_position)
894 type_t *const orig_type_right = right->base.type;
895 type_t *const type_left = skip_typeref(orig_type_left);
896 type_t *const type_right = skip_typeref(orig_type_right);
901 case ASSIGN_ERROR_INCOMPATIBLE:
902 errorf(source_position,
903 "destination type '%T' in %s is incompatible with type '%T'",
904 orig_type_left, context, orig_type_right);
907 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
908 type_t *points_to_left
909 = skip_typeref(type_left->pointer.points_to);
910 type_t *points_to_right
911 = skip_typeref(type_right->pointer.points_to);
913 /* the left type has all qualifiers from the right type */
914 unsigned missing_qualifiers
915 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
916 errorf(source_position,
917 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type",
918 orig_type_left, context, orig_type_right, missing_qualifiers);
922 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
923 warningf(source_position,
924 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
925 orig_type_left, context, right, orig_type_right);
928 case ASSIGN_WARNING_POINTER_FROM_INT:
929 warningf(source_position,
930 "%s makes integer '%T' from pointer '%T' without a cast",
931 context, orig_type_left, orig_type_right);
934 case ASSIGN_WARNING_INT_FROM_POINTER:
935 warningf(source_position,
936 "%s makes integer '%T' from pointer '%T' without a cast",
937 context, orig_type_left, orig_type_right);
941 panic("invalid error value");
945 /** Implements the rules from § 6.5.16.1 */
946 static assign_error_t semantic_assign(type_t *orig_type_left,
947 const expression_t *const right)
949 type_t *const orig_type_right = right->base.type;
950 type_t *const type_left = skip_typeref(orig_type_left);
951 type_t *const type_right = skip_typeref(orig_type_right);
953 if (is_type_pointer(type_left)) {
954 if (is_null_pointer_constant(right)) {
955 return ASSIGN_SUCCESS;
956 } else if (is_type_pointer(type_right)) {
957 type_t *points_to_left
958 = skip_typeref(type_left->pointer.points_to);
959 type_t *points_to_right
960 = skip_typeref(type_right->pointer.points_to);
962 /* the left type has all qualifiers from the right type */
963 unsigned missing_qualifiers
964 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
965 if (missing_qualifiers != 0) {
966 return ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
969 points_to_left = get_unqualified_type(points_to_left);
970 points_to_right = get_unqualified_type(points_to_right);
972 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
973 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
974 return ASSIGN_SUCCESS;
977 if (!types_compatible(points_to_left, points_to_right)) {
978 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
981 return ASSIGN_SUCCESS;
982 } else if (is_type_integer(type_right)) {
983 return ASSIGN_WARNING_POINTER_FROM_INT;
985 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
986 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
987 && is_type_pointer(type_right))) {
988 return ASSIGN_SUCCESS;
989 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
990 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
991 type_t *const unqual_type_left = get_unqualified_type(type_left);
992 type_t *const unqual_type_right = get_unqualified_type(type_right);
993 if (types_compatible(unqual_type_left, unqual_type_right)) {
994 return ASSIGN_SUCCESS;
996 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
997 return ASSIGN_WARNING_INT_FROM_POINTER;
1000 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1001 return ASSIGN_SUCCESS;
1003 return ASSIGN_ERROR_INCOMPATIBLE;
1006 static expression_t *parse_constant_expression(void)
1008 /* start parsing at precedence 7 (conditional expression) */
1009 expression_t *result = parse_sub_expression(7);
1011 if (!is_constant_expression(result)) {
1012 errorf(&result->base.source_position,
1013 "expression '%E' is not constant\n", result);
1019 static expression_t *parse_assignment_expression(void)
1021 /* start parsing at precedence 2 (assignment expression) */
1022 return parse_sub_expression(2);
1025 static type_t *make_global_typedef(const char *name, type_t *type)
1027 symbol_t *const symbol = symbol_table_insert(name);
1029 declaration_t *const declaration = allocate_declaration_zero();
1030 declaration->namespc = NAMESPACE_NORMAL;
1031 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
1032 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
1033 declaration->type = type;
1034 declaration->symbol = symbol;
1035 declaration->source_position = builtin_source_position;
1037 record_declaration(declaration);
1039 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, &builtin_source_position);
1040 typedef_type->typedeft.declaration = declaration;
1042 return typedef_type;
1045 static string_t parse_string_literals(void)
1047 assert(token.type == T_STRING_LITERAL);
1048 string_t result = token.v.string;
1052 while (token.type == T_STRING_LITERAL) {
1053 result = concat_strings(&result, &token.v.string);
1060 static const char *gnu_attribute_names[GNU_AK_LAST] = {
1061 [GNU_AK_CONST] = "const",
1062 [GNU_AK_VOLATILE] = "volatile",
1063 [GNU_AK_CDECL] = "cdecl",
1064 [GNU_AK_STDCALL] = "stdcall",
1065 [GNU_AK_FASTCALL] = "fastcall",
1066 [GNU_AK_DEPRECATED] = "deprecated",
1067 [GNU_AK_NOINLINE] = "noinline",
1068 [GNU_AK_NORETURN] = "noreturn",
1069 [GNU_AK_NAKED] = "naked",
1070 [GNU_AK_PURE] = "pure",
1071 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1072 [GNU_AK_MALLOC] = "malloc",
1073 [GNU_AK_WEAK] = "weak",
1074 [GNU_AK_CONSTRUCTOR] = "constructor",
1075 [GNU_AK_DESTRUCTOR] = "destructor",
1076 [GNU_AK_NOTHROW] = "nothrow",
1077 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1078 [GNU_AK_COMMON] = "common",
1079 [GNU_AK_NOCOMMON] = "nocommon",
1080 [GNU_AK_PACKED] = "packed",
1081 [GNU_AK_SHARED] = "shared",
1082 [GNU_AK_NOTSHARED] = "notshared",
1083 [GNU_AK_USED] = "used",
1084 [GNU_AK_UNUSED] = "unused",
1085 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1086 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1087 [GNU_AK_LONGCALL] = "longcall",
1088 [GNU_AK_SHORTCALL] = "shortcall",
1089 [GNU_AK_LONG_CALL] = "long_call",
1090 [GNU_AK_SHORT_CALL] = "short_call",
1091 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1092 [GNU_AK_INTERRUPT] = "interrupt",
1093 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1094 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1095 [GNU_AK_NESTING] = "nesting",
1096 [GNU_AK_NEAR] = "near",
1097 [GNU_AK_FAR] = "far",
1098 [GNU_AK_SIGNAL] = "signal",
1099 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1100 [GNU_AK_TINY_DATA] = "tiny_data",
1101 [GNU_AK_SAVEALL] = "saveall",
1102 [GNU_AK_FLATTEN] = "flatten",
1103 [GNU_AK_SSEREGPARM] = "sseregparm",
1104 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1105 [GNU_AK_RETURN_TWICE] = "return_twice",
1106 [GNU_AK_MAY_ALIAS] = "may_alias",
1107 [GNU_AK_MS_STRUCT] = "ms_struct",
1108 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1109 [GNU_AK_DLLIMPORT] = "dllimport",
1110 [GNU_AK_DLLEXPORT] = "dllexport",
1111 [GNU_AK_ALIGNED] = "aligned",
1112 [GNU_AK_ALIAS] = "alias",
1113 [GNU_AK_SECTION] = "section",
1114 [GNU_AK_FORMAT] = "format",
1115 [GNU_AK_FORMAT_ARG] = "format_arg",
1116 [GNU_AK_WEAKREF] = "weakref",
1117 [GNU_AK_NONNULL] = "nonnull",
1118 [GNU_AK_TLS_MODEL] = "tls_model",
1119 [GNU_AK_VISIBILITY] = "visibility",
1120 [GNU_AK_REGPARM] = "regparm",
1121 [GNU_AK_MODE] = "mode",
1122 [GNU_AK_MODEL] = "model",
1123 [GNU_AK_TRAP_EXIT] = "trap_exit",
1124 [GNU_AK_SP_SWITCH] = "sp_switch",
1125 [GNU_AK_SENTINEL] = "sentinel"
1129 * compare two string, ignoring double underscores on the second.
1131 static int strcmp_underscore(const char *s1, const char *s2) {
1132 if (s2[0] == '_' && s2[1] == '_') {
1133 size_t len2 = strlen(s2);
1134 size_t len1 = strlen(s1);
1135 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1136 return strncmp(s1, s2+2, len2-4);
1140 return strcmp(s1, s2);
1144 * Allocate a new gnu temporal attribute.
1146 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind) {
1147 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1148 attribute->kind = kind;
1149 attribute->next = NULL;
1150 attribute->invalid = false;
1151 attribute->have_arguments = false;
1157 * parse one constant expression argument.
1159 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute) {
1160 expression_t *expression;
1161 add_anchor_token(')');
1162 expression = parse_constant_expression();
1163 rem_anchor_token(')');
1168 attribute->invalid = true;
1172 * parse a list of constant expressions arguments.
1174 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute) {
1175 expression_t *expression;
1176 add_anchor_token(')');
1177 add_anchor_token(',');
1179 expression = parse_constant_expression();
1180 if (token.type != ',')
1184 rem_anchor_token(',');
1185 rem_anchor_token(')');
1190 attribute->invalid = true;
1194 * parse one string literal argument.
1196 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1199 add_anchor_token('(');
1200 if (token.type != T_STRING_LITERAL) {
1201 parse_error_expected("while parsing attribute directive",
1202 T_STRING_LITERAL, NULL);
1205 *string = parse_string_literals();
1206 rem_anchor_token('(');
1210 attribute->invalid = true;
1214 * parse one tls model.
1216 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute) {
1217 static const char *tls_models[] = {
1223 string_t string = { NULL, 0 };
1224 parse_gnu_attribute_string_arg(attribute, &string);
1225 if (string.begin != NULL) {
1226 for(size_t i = 0; i < 4; ++i) {
1227 if (strcmp(tls_models[i], string.begin) == 0) {
1228 attribute->u.value = i;
1232 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1234 attribute->invalid = true;
1238 * parse one tls model.
1240 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute) {
1241 static const char *visibilities[] = {
1247 string_t string = { NULL, 0 };
1248 parse_gnu_attribute_string_arg(attribute, &string);
1249 if (string.begin != NULL) {
1250 for(size_t i = 0; i < 4; ++i) {
1251 if (strcmp(visibilities[i], string.begin) == 0) {
1252 attribute->u.value = i;
1256 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1258 attribute->invalid = true;
1262 * parse one (code) model.
1264 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute) {
1265 static const char *visibilities[] = {
1270 string_t string = { NULL, 0 };
1271 parse_gnu_attribute_string_arg(attribute, &string);
1272 if (string.begin != NULL) {
1273 for(int i = 0; i < 3; ++i) {
1274 if (strcmp(visibilities[i], string.begin) == 0) {
1275 attribute->u.value = i;
1279 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1281 attribute->invalid = true;
1284 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1286 /* TODO: find out what is allowed here... */
1288 /* at least: byte, word, pointer, list of machine modes
1289 * __XXX___ is interpreted as XXX */
1290 add_anchor_token(')');
1292 if (token.type != T_IDENTIFIER) {
1293 expect(T_IDENTIFIER);
1296 /* This isn't really correct, the backend should provide a list of machine
1297 * specific modes (according to gcc philosophy that is...) */
1298 const char *symbol_str = token.v.symbol->string;
1299 if (strcmp_underscore("QI", symbol_str) == 0 ||
1300 strcmp_underscore("byte", symbol_str) == 0) {
1301 attribute->u.akind = ATOMIC_TYPE_CHAR;
1302 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1303 attribute->u.akind = ATOMIC_TYPE_SHORT;
1304 } else if (strcmp_underscore("SI", symbol_str) == 0
1305 || strcmp_underscore("word", symbol_str) == 0
1306 || strcmp_underscore("pointer", symbol_str) == 0) {
1307 attribute->u.akind = ATOMIC_TYPE_INT;
1308 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1309 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1311 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1312 attribute->invalid = true;
1316 rem_anchor_token(')');
1320 attribute->invalid = true;
1324 * parse one interrupt argument.
1326 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute) {
1327 static const char *interrupts[] = {
1334 string_t string = { NULL, 0 };
1335 parse_gnu_attribute_string_arg(attribute, &string);
1336 if (string.begin != NULL) {
1337 for(size_t i = 0; i < 5; ++i) {
1338 if (strcmp(interrupts[i], string.begin) == 0) {
1339 attribute->u.value = i;
1343 errorf(HERE, "'%s' is not an interrupt", string.begin);
1345 attribute->invalid = true;
1349 * parse ( identifier, const expression, const expression )
1351 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute) {
1352 static const char *format_names[] = {
1360 if (token.type != T_IDENTIFIER) {
1361 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1364 const char *name = token.v.symbol->string;
1365 for(i = 0; i < 4; ++i) {
1366 if (strcmp_underscore(format_names[i], name) == 0)
1370 if (warning.attribute)
1371 warningf(HERE, "'%s' is an unrecognized format function type", name);
1376 add_anchor_token(')');
1377 add_anchor_token(',');
1378 parse_constant_expression();
1379 rem_anchor_token(',');
1380 rem_anchor_token('(');
1383 add_anchor_token(')');
1384 parse_constant_expression();
1385 rem_anchor_token('(');
1389 attribute->u.value = true;
1392 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1394 if (!attribute->have_arguments)
1397 /* should have no arguments */
1398 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1399 eat_until_matching_token('(');
1400 /* we have already consumed '(', so we stop before ')', eat it */
1402 attribute->invalid = true;
1406 * Parse one GNU attribute.
1408 * Note that attribute names can be specified WITH or WITHOUT
1409 * double underscores, ie const or __const__.
1411 * The following attributes are parsed without arguments
1436 * no_instrument_function
1437 * warn_unused_result
1454 * externally_visible
1462 * The following attributes are parsed with arguments
1463 * aligned( const expression )
1464 * alias( string literal )
1465 * section( string literal )
1466 * format( identifier, const expression, const expression )
1467 * format_arg( const expression )
1468 * tls_model( string literal )
1469 * visibility( string literal )
1470 * regparm( const expression )
1471 * model( string leteral )
1472 * trap_exit( const expression )
1473 * sp_switch( string literal )
1475 * The following attributes might have arguments
1476 * weak_ref( string literal )
1477 * non_null( const expression // ',' )
1478 * interrupt( string literal )
1479 * sentinel( constant expression )
1481 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1483 gnu_attribute_t *head = *attributes;
1484 gnu_attribute_t *last = *attributes;
1485 decl_modifiers_t modifiers = 0;
1486 gnu_attribute_t *attribute;
1488 eat(T___attribute__);
1492 if (token.type != ')') {
1493 /* find the end of the list */
1495 while(last->next != NULL)
1499 /* non-empty attribute list */
1502 if (token.type == T_const) {
1504 } else if (token.type == T_volatile) {
1506 } else if (token.type == T_cdecl) {
1507 /* __attribute__((cdecl)), WITH ms mode */
1509 } else if (token.type == T_IDENTIFIER) {
1510 const symbol_t *sym = token.v.symbol;
1513 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1520 for(i = 0; i < GNU_AK_LAST; ++i) {
1521 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1524 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1527 if (kind == GNU_AK_LAST) {
1528 if (warning.attribute)
1529 warningf(HERE, "'%s' attribute directive ignored", name);
1531 /* skip possible arguments */
1532 if (token.type == '(') {
1533 eat_until_matching_token(')');
1536 /* check for arguments */
1537 attribute = allocate_gnu_attribute(kind);
1538 if (token.type == '(') {
1540 if (token.type == ')') {
1541 /* empty args are allowed */
1544 attribute->have_arguments = true;
1549 case GNU_AK_VOLATILE:
1550 case GNU_AK_DEPRECATED:
1555 case GNU_AK_NOCOMMON:
1557 case GNU_AK_NOTSHARED:
1559 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1560 case GNU_AK_WARN_UNUSED_RESULT:
1561 case GNU_AK_LONGCALL:
1562 case GNU_AK_SHORTCALL:
1563 case GNU_AK_LONG_CALL:
1564 case GNU_AK_SHORT_CALL:
1565 case GNU_AK_FUNCTION_VECTOR:
1566 case GNU_AK_INTERRUPT_HANDLER:
1567 case GNU_AK_NMI_HANDLER:
1568 case GNU_AK_NESTING:
1572 case GNU_AK_EIGTHBIT_DATA:
1573 case GNU_AK_TINY_DATA:
1574 case GNU_AK_SAVEALL:
1575 case GNU_AK_FLATTEN:
1576 case GNU_AK_SSEREGPARM:
1577 case GNU_AK_EXTERNALLY_VISIBLE:
1578 case GNU_AK_RETURN_TWICE:
1579 case GNU_AK_MAY_ALIAS:
1580 case GNU_AK_MS_STRUCT:
1581 case GNU_AK_GCC_STRUCT:
1584 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1585 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1586 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1587 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1588 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1589 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1590 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1591 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1592 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1593 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1594 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1595 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1596 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1597 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1598 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1600 case GNU_AK_ALIGNED:
1601 /* __align__ may be used without an argument */
1602 if (attribute->have_arguments) {
1603 parse_gnu_attribute_const_arg(attribute);
1607 case GNU_AK_FORMAT_ARG:
1608 case GNU_AK_REGPARM:
1609 case GNU_AK_TRAP_EXIT:
1610 if (!attribute->have_arguments) {
1611 /* should have arguments */
1612 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1613 attribute->invalid = true;
1615 parse_gnu_attribute_const_arg(attribute);
1618 case GNU_AK_SECTION:
1619 case GNU_AK_SP_SWITCH:
1620 if (!attribute->have_arguments) {
1621 /* should have arguments */
1622 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1623 attribute->invalid = true;
1625 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1628 if (!attribute->have_arguments) {
1629 /* should have arguments */
1630 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1631 attribute->invalid = true;
1633 parse_gnu_attribute_format_args(attribute);
1635 case GNU_AK_WEAKREF:
1636 /* may have one string argument */
1637 if (attribute->have_arguments)
1638 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1640 case GNU_AK_NONNULL:
1641 if (attribute->have_arguments)
1642 parse_gnu_attribute_const_arg_list(attribute);
1644 case GNU_AK_TLS_MODEL:
1645 if (!attribute->have_arguments) {
1646 /* should have arguments */
1647 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1649 parse_gnu_attribute_tls_model_arg(attribute);
1651 case GNU_AK_VISIBILITY:
1652 if (!attribute->have_arguments) {
1653 /* should have arguments */
1654 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1656 parse_gnu_attribute_visibility_arg(attribute);
1659 if (!attribute->have_arguments) {
1660 /* should have arguments */
1661 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1663 parse_gnu_attribute_model_arg(attribute);
1667 if (!attribute->have_arguments) {
1668 /* should have arguments */
1669 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1671 parse_gnu_attribute_mode_arg(attribute);
1674 case GNU_AK_INTERRUPT:
1675 /* may have one string argument */
1676 if (attribute->have_arguments)
1677 parse_gnu_attribute_interrupt_arg(attribute);
1679 case GNU_AK_SENTINEL:
1680 /* may have one string argument */
1681 if (attribute->have_arguments)
1682 parse_gnu_attribute_const_arg(attribute);
1685 /* already handled */
1689 check_no_argument(attribute, name);
1692 if (attribute != NULL) {
1694 last->next = attribute;
1697 head = last = attribute;
1701 if (token.type != ',')
1715 * Parse GNU attributes.
1717 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1719 decl_modifiers_t modifiers = 0;
1722 switch(token.type) {
1723 case T___attribute__:
1724 modifiers |= parse_gnu_attribute(attributes);
1730 if (token.type != T_STRING_LITERAL) {
1731 parse_error_expected("while parsing assembler attribute",
1732 T_STRING_LITERAL, NULL);
1733 eat_until_matching_token('(');
1736 parse_string_literals();
1741 case T_cdecl: modifiers |= DM_CDECL; break;
1742 case T__fastcall: modifiers |= DM_FASTCALL; break;
1743 case T__stdcall: modifiers |= DM_STDCALL; break;
1746 /* TODO record modifier */
1747 warningf(HERE, "Ignoring declaration modifier %K", &token);
1751 default: return modifiers;
1758 static designator_t *parse_designation(void)
1760 designator_t *result = NULL;
1761 designator_t *last = NULL;
1764 designator_t *designator;
1765 switch(token.type) {
1767 designator = allocate_ast_zero(sizeof(designator[0]));
1768 designator->source_position = token.source_position;
1770 add_anchor_token(']');
1771 designator->array_index = parse_constant_expression();
1772 rem_anchor_token(']');
1776 designator = allocate_ast_zero(sizeof(designator[0]));
1777 designator->source_position = token.source_position;
1779 if (token.type != T_IDENTIFIER) {
1780 parse_error_expected("while parsing designator",
1781 T_IDENTIFIER, NULL);
1784 designator->symbol = token.v.symbol;
1792 assert(designator != NULL);
1794 last->next = designator;
1796 result = designator;
1804 static initializer_t *initializer_from_string(array_type_t *type,
1805 const string_t *const string)
1807 /* TODO: check len vs. size of array type */
1810 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1811 initializer->string.string = *string;
1816 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1817 wide_string_t *const string)
1819 /* TODO: check len vs. size of array type */
1822 initializer_t *const initializer =
1823 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1824 initializer->wide_string.string = *string;
1830 * Build an initializer from a given expression.
1832 static initializer_t *initializer_from_expression(type_t *orig_type,
1833 expression_t *expression)
1835 /* TODO check that expression is a constant expression */
1837 /* § 6.7.8.14/15 char array may be initialized by string literals */
1838 type_t *type = skip_typeref(orig_type);
1839 type_t *expr_type_orig = expression->base.type;
1840 type_t *expr_type = skip_typeref(expr_type_orig);
1841 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1842 array_type_t *const array_type = &type->array;
1843 type_t *const element_type = skip_typeref(array_type->element_type);
1845 if (element_type->kind == TYPE_ATOMIC) {
1846 atomic_type_kind_t akind = element_type->atomic.akind;
1847 switch (expression->kind) {
1848 case EXPR_STRING_LITERAL:
1849 if (akind == ATOMIC_TYPE_CHAR
1850 || akind == ATOMIC_TYPE_SCHAR
1851 || akind == ATOMIC_TYPE_UCHAR) {
1852 return initializer_from_string(array_type,
1853 &expression->string.value);
1856 case EXPR_WIDE_STRING_LITERAL: {
1857 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1858 if (get_unqualified_type(element_type) == bare_wchar_type) {
1859 return initializer_from_wide_string(array_type,
1860 &expression->wide_string.value);
1870 assign_error_t error = semantic_assign(type, expression);
1871 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1873 report_assign_error(error, type, expression, "initializer",
1874 &expression->base.source_position);
1876 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1877 result->value.value = create_implicit_cast(expression, type);
1883 * Checks if a given expression can be used as an constant initializer.
1885 static bool is_initializer_constant(const expression_t *expression)
1887 return is_constant_expression(expression)
1888 || is_address_constant(expression);
1892 * Parses an scalar initializer.
1894 * § 6.7.8.11; eat {} without warning
1896 static initializer_t *parse_scalar_initializer(type_t *type,
1897 bool must_be_constant)
1899 /* there might be extra {} hierarchies */
1901 if (token.type == '{') {
1902 warningf(HERE, "extra curly braces around scalar initializer");
1906 } while (token.type == '{');
1909 expression_t *expression = parse_assignment_expression();
1910 if (must_be_constant && !is_initializer_constant(expression)) {
1911 errorf(&expression->base.source_position,
1912 "Initialisation expression '%E' is not constant\n",
1916 initializer_t *initializer = initializer_from_expression(type, expression);
1918 if (initializer == NULL) {
1919 errorf(&expression->base.source_position,
1920 "expression '%E' (type '%T') doesn't match expected type '%T'",
1921 expression, expression->base.type, type);
1926 bool additional_warning_displayed = false;
1928 if (token.type == ',') {
1931 if (token.type != '}') {
1932 if (!additional_warning_displayed) {
1933 warningf(HERE, "additional elements in scalar initializer");
1934 additional_warning_displayed = true;
1945 * An entry in the type path.
1947 typedef struct type_path_entry_t type_path_entry_t;
1948 struct type_path_entry_t {
1949 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1951 size_t index; /**< For array types: the current index. */
1952 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1957 * A type path expression a position inside compound or array types.
1959 typedef struct type_path_t type_path_t;
1960 struct type_path_t {
1961 type_path_entry_t *path; /**< An flexible array containing the current path. */
1962 type_t *top_type; /**< type of the element the path points */
1963 size_t max_index; /**< largest index in outermost array */
1967 * Prints a type path for debugging.
1969 static __attribute__((unused)) void debug_print_type_path(
1970 const type_path_t *path)
1972 size_t len = ARR_LEN(path->path);
1974 for(size_t i = 0; i < len; ++i) {
1975 const type_path_entry_t *entry = & path->path[i];
1977 type_t *type = skip_typeref(entry->type);
1978 if (is_type_compound(type)) {
1979 /* in gcc mode structs can have no members */
1980 if (entry->v.compound_entry == NULL) {
1984 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1985 } else if (is_type_array(type)) {
1986 fprintf(stderr, "[%zd]", entry->v.index);
1988 fprintf(stderr, "-INVALID-");
1991 if (path->top_type != NULL) {
1992 fprintf(stderr, " (");
1993 print_type(path->top_type);
1994 fprintf(stderr, ")");
1999 * Return the top type path entry, ie. in a path
2000 * (type).a.b returns the b.
2002 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2004 size_t len = ARR_LEN(path->path);
2006 return &path->path[len-1];
2010 * Enlarge the type path by an (empty) element.
2012 static type_path_entry_t *append_to_type_path(type_path_t *path)
2014 size_t len = ARR_LEN(path->path);
2015 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2017 type_path_entry_t *result = & path->path[len];
2018 memset(result, 0, sizeof(result[0]));
2023 * Descending into a sub-type. Enter the scope of the current
2026 static void descend_into_subtype(type_path_t *path)
2028 type_t *orig_top_type = path->top_type;
2029 type_t *top_type = skip_typeref(orig_top_type);
2031 assert(is_type_compound(top_type) || is_type_array(top_type));
2033 type_path_entry_t *top = append_to_type_path(path);
2034 top->type = top_type;
2036 if (is_type_compound(top_type)) {
2037 declaration_t *declaration = top_type->compound.declaration;
2038 declaration_t *entry = declaration->scope.declarations;
2039 top->v.compound_entry = entry;
2041 if (entry != NULL) {
2042 path->top_type = entry->type;
2044 path->top_type = NULL;
2047 assert(is_type_array(top_type));
2050 path->top_type = top_type->array.element_type;
2055 * Pop an entry from the given type path, ie. returning from
2056 * (type).a.b to (type).a
2058 static void ascend_from_subtype(type_path_t *path)
2060 type_path_entry_t *top = get_type_path_top(path);
2062 path->top_type = top->type;
2064 size_t len = ARR_LEN(path->path);
2065 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2069 * Pop entries from the given type path until the given
2070 * path level is reached.
2072 static void ascend_to(type_path_t *path, size_t top_path_level)
2074 size_t len = ARR_LEN(path->path);
2076 while(len > top_path_level) {
2077 ascend_from_subtype(path);
2078 len = ARR_LEN(path->path);
2082 static bool walk_designator(type_path_t *path, const designator_t *designator,
2083 bool used_in_offsetof)
2085 for( ; designator != NULL; designator = designator->next) {
2086 type_path_entry_t *top = get_type_path_top(path);
2087 type_t *orig_type = top->type;
2089 type_t *type = skip_typeref(orig_type);
2091 if (designator->symbol != NULL) {
2092 symbol_t *symbol = designator->symbol;
2093 if (!is_type_compound(type)) {
2094 if (is_type_valid(type)) {
2095 errorf(&designator->source_position,
2096 "'.%Y' designator used for non-compound type '%T'",
2102 declaration_t *declaration = type->compound.declaration;
2103 declaration_t *iter = declaration->scope.declarations;
2104 for( ; iter != NULL; iter = iter->next) {
2105 if (iter->symbol == symbol) {
2110 errorf(&designator->source_position,
2111 "'%T' has no member named '%Y'", orig_type, symbol);
2114 if (used_in_offsetof) {
2115 type_t *real_type = skip_typeref(iter->type);
2116 if (real_type->kind == TYPE_BITFIELD) {
2117 errorf(&designator->source_position,
2118 "offsetof designator '%Y' may not specify bitfield",
2124 top->type = orig_type;
2125 top->v.compound_entry = iter;
2126 orig_type = iter->type;
2128 expression_t *array_index = designator->array_index;
2129 assert(designator->array_index != NULL);
2131 if (!is_type_array(type)) {
2132 if (is_type_valid(type)) {
2133 errorf(&designator->source_position,
2134 "[%E] designator used for non-array type '%T'",
2135 array_index, orig_type);
2139 if (!is_type_valid(array_index->base.type)) {
2143 long index = fold_constant(array_index);
2144 if (!used_in_offsetof) {
2146 errorf(&designator->source_position,
2147 "array index [%E] must be positive", array_index);
2150 if (type->array.size_constant == true) {
2151 long array_size = type->array.size;
2152 if (index >= array_size) {
2153 errorf(&designator->source_position,
2154 "designator [%E] (%d) exceeds array size %d",
2155 array_index, index, array_size);
2161 top->type = orig_type;
2162 top->v.index = (size_t) index;
2163 orig_type = type->array.element_type;
2165 path->top_type = orig_type;
2167 if (designator->next != NULL) {
2168 descend_into_subtype(path);
2177 static void advance_current_object(type_path_t *path, size_t top_path_level)
2179 type_path_entry_t *top = get_type_path_top(path);
2181 type_t *type = skip_typeref(top->type);
2182 if (is_type_union(type)) {
2183 /* in unions only the first element is initialized */
2184 top->v.compound_entry = NULL;
2185 } else if (is_type_struct(type)) {
2186 declaration_t *entry = top->v.compound_entry;
2188 entry = entry->next;
2189 top->v.compound_entry = entry;
2190 if (entry != NULL) {
2191 path->top_type = entry->type;
2195 assert(is_type_array(type));
2199 if (!type->array.size_constant || top->v.index < type->array.size) {
2204 /* we're past the last member of the current sub-aggregate, try if we
2205 * can ascend in the type hierarchy and continue with another subobject */
2206 size_t len = ARR_LEN(path->path);
2208 if (len > top_path_level) {
2209 ascend_from_subtype(path);
2210 advance_current_object(path, top_path_level);
2212 path->top_type = NULL;
2217 * skip until token is found.
2219 static void skip_until(int type) {
2220 while(token.type != type) {
2221 if (token.type == T_EOF)
2228 * skip any {...} blocks until a closing bracket is reached.
2230 static void skip_initializers(void)
2232 if (token.type == '{')
2235 while(token.type != '}') {
2236 if (token.type == T_EOF)
2238 if (token.type == '{') {
2246 static initializer_t *create_empty_initializer(void)
2248 static initializer_t empty_initializer
2249 = { .list = { { INITIALIZER_LIST }, 0 } };
2250 return &empty_initializer;
2254 * Parse a part of an initialiser for a struct or union,
2256 static initializer_t *parse_sub_initializer(type_path_t *path,
2257 type_t *outer_type, size_t top_path_level,
2258 parse_initializer_env_t *env)
2260 if (token.type == '}') {
2261 /* empty initializer */
2262 return create_empty_initializer();
2265 type_t *orig_type = path->top_type;
2266 type_t *type = NULL;
2268 if (orig_type == NULL) {
2269 /* We are initializing an empty compound. */
2271 type = skip_typeref(orig_type);
2273 /* we can't do usefull stuff if we didn't even parse the type. Skip the
2274 * initializers in this case. */
2275 if (!is_type_valid(type)) {
2276 skip_initializers();
2277 return create_empty_initializer();
2281 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2284 designator_t *designator = NULL;
2285 if (token.type == '.' || token.type == '[') {
2286 designator = parse_designation();
2288 /* reset path to toplevel, evaluate designator from there */
2289 ascend_to(path, top_path_level);
2290 if (!walk_designator(path, designator, false)) {
2291 /* can't continue after designation error */
2295 initializer_t *designator_initializer
2296 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2297 designator_initializer->designator.designator = designator;
2298 ARR_APP1(initializer_t*, initializers, designator_initializer);
2300 orig_type = path->top_type;
2301 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2306 if (token.type == '{') {
2307 if (type != NULL && is_type_scalar(type)) {
2308 sub = parse_scalar_initializer(type, env->must_be_constant);
2312 if (env->declaration != NULL) {
2313 errorf(HERE, "extra brace group at end of initializer for '%Y'",
2314 env->declaration->symbol);
2316 errorf(HERE, "extra brace group at end of initializer");
2319 descend_into_subtype(path);
2321 add_anchor_token('}');
2322 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2324 rem_anchor_token('}');
2327 ascend_from_subtype(path);
2331 goto error_parse_next;
2335 /* must be an expression */
2336 expression_t *expression = parse_assignment_expression();
2338 if (env->must_be_constant && !is_initializer_constant(expression)) {
2339 errorf(&expression->base.source_position,
2340 "Initialisation expression '%E' is not constant\n",
2345 /* we are already outside, ... */
2349 /* handle { "string" } special case */
2350 if ((expression->kind == EXPR_STRING_LITERAL
2351 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2352 && outer_type != NULL) {
2353 sub = initializer_from_expression(outer_type, expression);
2355 if (token.type == ',') {
2358 if (token.type != '}') {
2359 warningf(HERE, "excessive elements in initializer for type '%T'",
2362 /* TODO: eat , ... */
2367 /* descend into subtypes until expression matches type */
2369 orig_type = path->top_type;
2370 type = skip_typeref(orig_type);
2372 sub = initializer_from_expression(orig_type, expression);
2376 if (!is_type_valid(type)) {
2379 if (is_type_scalar(type)) {
2380 errorf(&expression->base.source_position,
2381 "expression '%E' doesn't match expected type '%T'",
2382 expression, orig_type);
2386 descend_into_subtype(path);
2390 /* update largest index of top array */
2391 const type_path_entry_t *first = &path->path[0];
2392 type_t *first_type = first->type;
2393 first_type = skip_typeref(first_type);
2394 if (is_type_array(first_type)) {
2395 size_t index = first->v.index;
2396 if (index > path->max_index)
2397 path->max_index = index;
2401 /* append to initializers list */
2402 ARR_APP1(initializer_t*, initializers, sub);
2405 if (env->declaration != NULL)
2406 warningf(HERE, "excess elements in struct initializer for '%Y'",
2407 env->declaration->symbol);
2409 warningf(HERE, "excess elements in struct initializer");
2413 if (token.type == '}') {
2417 if (token.type == '}') {
2422 /* advance to the next declaration if we are not at the end */
2423 advance_current_object(path, top_path_level);
2424 orig_type = path->top_type;
2425 if (orig_type != NULL)
2426 type = skip_typeref(orig_type);
2432 size_t len = ARR_LEN(initializers);
2433 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2434 initializer_t *result = allocate_ast_zero(size);
2435 result->kind = INITIALIZER_LIST;
2436 result->list.len = len;
2437 memcpy(&result->list.initializers, initializers,
2438 len * sizeof(initializers[0]));
2440 DEL_ARR_F(initializers);
2441 ascend_to(path, top_path_level+1);
2446 skip_initializers();
2447 DEL_ARR_F(initializers);
2448 ascend_to(path, top_path_level+1);
2453 * Parses an initializer. Parsers either a compound literal
2454 * (env->declaration == NULL) or an initializer of a declaration.
2456 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2458 type_t *type = skip_typeref(env->type);
2459 initializer_t *result = NULL;
2462 if (is_type_scalar(type)) {
2463 result = parse_scalar_initializer(type, env->must_be_constant);
2464 } else if (token.type == '{') {
2468 memset(&path, 0, sizeof(path));
2469 path.top_type = env->type;
2470 path.path = NEW_ARR_F(type_path_entry_t, 0);
2472 descend_into_subtype(&path);
2474 add_anchor_token('}');
2475 result = parse_sub_initializer(&path, env->type, 1, env);
2476 rem_anchor_token('}');
2478 max_index = path.max_index;
2479 DEL_ARR_F(path.path);
2483 /* parse_scalar_initializer() also works in this case: we simply
2484 * have an expression without {} around it */
2485 result = parse_scalar_initializer(type, env->must_be_constant);
2488 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
2489 * the array type size */
2490 if (is_type_array(type) && type->array.size_expression == NULL
2491 && result != NULL) {
2493 switch (result->kind) {
2494 case INITIALIZER_LIST:
2495 size = max_index + 1;
2498 case INITIALIZER_STRING:
2499 size = result->string.string.size;
2502 case INITIALIZER_WIDE_STRING:
2503 size = result->wide_string.string.size;
2506 case INITIALIZER_DESIGNATOR:
2507 case INITIALIZER_VALUE:
2508 /* can happen for parse errors */
2513 internal_errorf(HERE, "invalid initializer type");
2516 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2517 cnst->base.type = type_size_t;
2518 cnst->conste.v.int_value = size;
2520 type_t *new_type = duplicate_type(type);
2522 new_type->array.size_expression = cnst;
2523 new_type->array.size_constant = true;
2524 new_type->array.size = size;
2525 env->type = new_type;
2533 static declaration_t *append_declaration(declaration_t *declaration);
2535 static declaration_t *parse_compound_type_specifier(bool is_struct)
2537 gnu_attribute_t *attributes = NULL;
2538 decl_modifiers_t modifiers = 0;
2545 symbol_t *symbol = NULL;
2546 declaration_t *declaration = NULL;
2548 if (token.type == T___attribute__) {
2549 modifiers |= parse_attributes(&attributes);
2552 if (token.type == T_IDENTIFIER) {
2553 symbol = token.v.symbol;
2556 namespace_t const namespc =
2557 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2558 declaration = get_declaration(symbol, namespc);
2559 if (declaration != NULL) {
2560 if (declaration->parent_scope != scope &&
2561 (token.type == '{' || token.type == ';')) {
2563 } else if (declaration->init.complete &&
2564 token.type == '{') {
2565 assert(symbol != NULL);
2566 errorf(HERE, "multiple definitions of '%s %Y' (previous definition at %P)",
2567 is_struct ? "struct" : "union", symbol,
2568 &declaration->source_position);
2569 declaration->scope.declarations = NULL;
2572 } else if (token.type != '{') {
2574 parse_error_expected("while parsing struct type specifier",
2575 T_IDENTIFIER, '{', NULL);
2577 parse_error_expected("while parsing union type specifier",
2578 T_IDENTIFIER, '{', NULL);
2584 if (declaration == NULL) {
2585 declaration = allocate_declaration_zero();
2586 declaration->namespc =
2587 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2588 declaration->source_position = token.source_position;
2589 declaration->symbol = symbol;
2590 declaration->parent_scope = scope;
2591 if (symbol != NULL) {
2592 environment_push(declaration);
2594 append_declaration(declaration);
2597 if (token.type == '{') {
2598 declaration->init.complete = true;
2600 parse_compound_type_entries(declaration);
2601 modifiers |= parse_attributes(&attributes);
2604 declaration->modifiers |= modifiers;
2608 static void parse_enum_entries(type_t *const enum_type)
2612 if (token.type == '}') {
2614 errorf(HERE, "empty enum not allowed");
2618 add_anchor_token('}');
2620 if (token.type != T_IDENTIFIER) {
2621 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2623 rem_anchor_token('}');
2627 declaration_t *const entry = allocate_declaration_zero();
2628 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
2629 entry->type = enum_type;
2630 entry->symbol = token.v.symbol;
2631 entry->source_position = token.source_position;
2634 if (token.type == '=') {
2636 expression_t *value = parse_constant_expression();
2638 value = create_implicit_cast(value, enum_type);
2639 entry->init.enum_value = value;
2644 record_declaration(entry);
2646 if (token.type != ',')
2649 } while(token.type != '}');
2650 rem_anchor_token('}');
2658 static type_t *parse_enum_specifier(void)
2660 gnu_attribute_t *attributes = NULL;
2661 declaration_t *declaration;
2665 if (token.type == T_IDENTIFIER) {
2666 symbol = token.v.symbol;
2669 declaration = get_declaration(symbol, NAMESPACE_ENUM);
2670 } else if (token.type != '{') {
2671 parse_error_expected("while parsing enum type specifier",
2672 T_IDENTIFIER, '{', NULL);
2679 if (declaration == NULL) {
2680 declaration = allocate_declaration_zero();
2681 declaration->namespc = NAMESPACE_ENUM;
2682 declaration->source_position = token.source_position;
2683 declaration->symbol = symbol;
2684 declaration->parent_scope = scope;
2687 type_t *const type = allocate_type_zero(TYPE_ENUM, &declaration->source_position);
2688 type->enumt.declaration = declaration;
2690 if (token.type == '{') {
2691 if (declaration->init.complete) {
2692 errorf(HERE, "multiple definitions of enum %Y", symbol);
2694 if (symbol != NULL) {
2695 environment_push(declaration);
2697 append_declaration(declaration);
2698 declaration->init.complete = true;
2700 parse_enum_entries(type);
2701 parse_attributes(&attributes);
2708 * if a symbol is a typedef to another type, return true
2710 static bool is_typedef_symbol(symbol_t *symbol)
2712 const declaration_t *const declaration =
2713 get_declaration(symbol, NAMESPACE_NORMAL);
2715 declaration != NULL &&
2716 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
2719 static type_t *parse_typeof(void)
2726 add_anchor_token(')');
2728 expression_t *expression = NULL;
2731 switch(token.type) {
2732 case T___extension__:
2733 /* this can be a prefix to a typename or an expression */
2734 /* we simply eat it now. */
2737 } while(token.type == T___extension__);
2741 if (is_typedef_symbol(token.v.symbol)) {
2742 type = parse_typename();
2744 expression = parse_expression();
2745 type = expression->base.type;
2750 type = parse_typename();
2754 expression = parse_expression();
2755 type = expression->base.type;
2759 rem_anchor_token(')');
2762 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, &expression->base.source_position);
2763 typeof_type->typeoft.expression = expression;
2764 typeof_type->typeoft.typeof_type = type;
2771 typedef enum specifiers_t {
2772 SPECIFIER_SIGNED = 1 << 0,
2773 SPECIFIER_UNSIGNED = 1 << 1,
2774 SPECIFIER_LONG = 1 << 2,
2775 SPECIFIER_INT = 1 << 3,
2776 SPECIFIER_DOUBLE = 1 << 4,
2777 SPECIFIER_CHAR = 1 << 5,
2778 SPECIFIER_SHORT = 1 << 6,
2779 SPECIFIER_LONG_LONG = 1 << 7,
2780 SPECIFIER_FLOAT = 1 << 8,
2781 SPECIFIER_BOOL = 1 << 9,
2782 SPECIFIER_VOID = 1 << 10,
2783 SPECIFIER_INT8 = 1 << 11,
2784 SPECIFIER_INT16 = 1 << 12,
2785 SPECIFIER_INT32 = 1 << 13,
2786 SPECIFIER_INT64 = 1 << 14,
2787 SPECIFIER_INT128 = 1 << 15,
2788 SPECIFIER_COMPLEX = 1 << 16,
2789 SPECIFIER_IMAGINARY = 1 << 17,
2792 static type_t *create_builtin_type(symbol_t *const symbol,
2793 type_t *const real_type)
2795 type_t *type = allocate_type_zero(TYPE_BUILTIN, &builtin_source_position);
2796 type->builtin.symbol = symbol;
2797 type->builtin.real_type = real_type;
2799 type_t *result = typehash_insert(type);
2800 if (type != result) {
2807 static type_t *get_typedef_type(symbol_t *symbol)
2809 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
2810 if (declaration == NULL ||
2811 declaration->storage_class != STORAGE_CLASS_TYPEDEF)
2814 type_t *type = allocate_type_zero(TYPE_TYPEDEF, &declaration->source_position);
2815 type->typedeft.declaration = declaration;
2821 * check for the allowed MS alignment values.
2823 static bool check_elignment_value(long long intvalue) {
2824 if (intvalue < 1 || intvalue > 8192) {
2825 errorf(HERE, "illegal alignment value");
2828 unsigned v = (unsigned)intvalue;
2829 for(unsigned i = 1; i <= 8192; i += i) {
2833 errorf(HERE, "alignment must be power of two");
2837 #define DET_MOD(name, tag) do { \
2838 if (*modifiers & tag) warningf(HERE, #name " used more than once"); \
2839 *modifiers |= tag; \
2842 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2844 decl_modifiers_t *modifiers = &specifiers->modifiers;
2847 if (token.type == T_restrict) {
2849 DET_MOD(restrict, DM_RESTRICT);
2851 } else if (token.type != T_IDENTIFIER)
2853 symbol_t *symbol = token.v.symbol;
2854 if (symbol == sym_align) {
2857 if (token.type != T_INTEGER)
2859 if (check_elignment_value(token.v.intvalue)) {
2860 if (specifiers->alignment != 0)
2861 warningf(HERE, "align used more than once");
2862 specifiers->alignment = (unsigned char)token.v.intvalue;
2866 } else if (symbol == sym_allocate) {
2869 if (token.type != T_IDENTIFIER)
2871 (void)token.v.symbol;
2873 } else if (symbol == sym_dllimport) {
2875 DET_MOD(dllimport, DM_DLLIMPORT);
2876 } else if (symbol == sym_dllexport) {
2878 DET_MOD(dllexport, DM_DLLEXPORT);
2879 } else if (symbol == sym_thread) {
2881 DET_MOD(thread, DM_THREAD);
2882 } else if (symbol == sym_naked) {
2884 DET_MOD(naked, DM_NAKED);
2885 } else if (symbol == sym_noinline) {
2887 DET_MOD(noinline, DM_NOINLINE);
2888 } else if (symbol == sym_noreturn) {
2890 DET_MOD(noreturn, DM_NORETURN);
2891 } else if (symbol == sym_nothrow) {
2893 DET_MOD(nothrow, DM_NOTHROW);
2894 } else if (symbol == sym_novtable) {
2896 DET_MOD(novtable, DM_NOVTABLE);
2897 } else if (symbol == sym_property) {
2901 bool is_get = false;
2902 if (token.type != T_IDENTIFIER)
2904 if (token.v.symbol == sym_get) {
2906 } else if (token.v.symbol == sym_put) {
2908 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2913 if (token.type != T_IDENTIFIER)
2916 if (specifiers->get_property_sym != NULL) {
2917 errorf(HERE, "get property name already specified");
2919 specifiers->get_property_sym = token.v.symbol;
2922 if (specifiers->put_property_sym != NULL) {
2923 errorf(HERE, "put property name already specified");
2925 specifiers->put_property_sym = token.v.symbol;
2929 if (token.type == ',') {
2936 } else if (symbol == sym_selectany) {
2938 DET_MOD(selectany, DM_SELECTANY);
2939 } else if (symbol == sym_uuid) {
2942 if (token.type != T_STRING_LITERAL)
2946 } else if (symbol == sym_deprecated) {
2948 if (specifiers->deprecated != 0)
2949 warningf(HERE, "deprecated used more than once");
2950 specifiers->deprecated = 1;
2951 if (token.type == '(') {
2953 if (token.type == T_STRING_LITERAL) {
2954 specifiers->deprecated_string = token.v.string.begin;
2957 errorf(HERE, "string literal expected");
2961 } else if (symbol == sym_noalias) {
2963 DET_MOD(noalias, DM_NOALIAS);
2965 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2967 if (token.type == '(')
2971 if (token.type == ',')
2978 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2980 type_t *type = NULL;
2981 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2982 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
2983 unsigned type_specifiers = 0;
2986 specifiers->source_position = token.source_position;
2989 specifiers->modifiers
2990 |= parse_attributes(&specifiers->gnu_attributes);
2991 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
2992 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
2994 switch(token.type) {
2997 #define MATCH_STORAGE_CLASS(token, class) \
2999 if (specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
3000 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3002 specifiers->declared_storage_class = class; \
3006 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3007 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3008 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3009 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3010 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3015 add_anchor_token(')');
3016 parse_microsoft_extended_decl_modifier(specifiers);
3017 rem_anchor_token(')');
3022 switch (specifiers->declared_storage_class) {
3023 case STORAGE_CLASS_NONE:
3024 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
3027 case STORAGE_CLASS_EXTERN:
3028 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
3031 case STORAGE_CLASS_STATIC:
3032 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
3036 errorf(HERE, "multiple storage classes in declaration specifiers");
3042 /* type qualifiers */
3043 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3045 qualifiers |= qualifier; \
3049 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3050 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3051 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3052 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3053 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3054 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3055 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3056 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3058 case T___extension__:
3063 /* type specifiers */
3064 #define MATCH_SPECIFIER(token, specifier, name) \
3067 if (type_specifiers & specifier) { \
3068 errorf(HERE, "multiple " name " type specifiers given"); \
3070 type_specifiers |= specifier; \
3074 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
3075 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
3076 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
3077 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
3078 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
3079 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
3080 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
3081 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
3082 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
3083 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8")
3084 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16")
3085 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32")
3086 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64")
3087 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128")
3088 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
3089 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
3091 case T__forceinline:
3092 /* only in microsoft mode */
3093 specifiers->modifiers |= DM_FORCEINLINE;
3097 specifiers->is_inline = true;
3102 if (type_specifiers & SPECIFIER_LONG_LONG) {
3103 errorf(HERE, "multiple type specifiers given");
3104 } else if (type_specifiers & SPECIFIER_LONG) {
3105 type_specifiers |= SPECIFIER_LONG_LONG;
3107 type_specifiers |= SPECIFIER_LONG;
3112 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
3114 type->compound.declaration = parse_compound_type_specifier(true);
3118 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
3119 type->compound.declaration = parse_compound_type_specifier(false);
3120 if (type->compound.declaration->modifiers & DM_TRANSPARENT_UNION)
3121 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3125 type = parse_enum_specifier();
3128 type = parse_typeof();
3130 case T___builtin_va_list:
3131 type = duplicate_type(type_valist);
3135 case T_IDENTIFIER: {
3136 /* only parse identifier if we haven't found a type yet */
3137 if (type != NULL || type_specifiers != 0)
3138 goto finish_specifiers;
3140 type_t *typedef_type = get_typedef_type(token.v.symbol);
3142 if (typedef_type == NULL)
3143 goto finish_specifiers;
3146 type = typedef_type;
3150 /* function specifier */
3152 goto finish_specifiers;
3159 atomic_type_kind_t atomic_type;
3161 /* match valid basic types */
3162 switch(type_specifiers) {
3163 case SPECIFIER_VOID:
3164 atomic_type = ATOMIC_TYPE_VOID;
3166 case SPECIFIER_CHAR:
3167 atomic_type = ATOMIC_TYPE_CHAR;
3169 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3170 atomic_type = ATOMIC_TYPE_SCHAR;
3172 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3173 atomic_type = ATOMIC_TYPE_UCHAR;
3175 case SPECIFIER_SHORT:
3176 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3177 case SPECIFIER_SHORT | SPECIFIER_INT:
3178 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3179 atomic_type = ATOMIC_TYPE_SHORT;
3181 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3182 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3183 atomic_type = ATOMIC_TYPE_USHORT;
3186 case SPECIFIER_SIGNED:
3187 case SPECIFIER_SIGNED | SPECIFIER_INT:
3188 atomic_type = ATOMIC_TYPE_INT;
3190 case SPECIFIER_UNSIGNED:
3191 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3192 atomic_type = ATOMIC_TYPE_UINT;
3194 case SPECIFIER_LONG:
3195 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3196 case SPECIFIER_LONG | SPECIFIER_INT:
3197 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3198 atomic_type = ATOMIC_TYPE_LONG;
3200 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3201 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3202 atomic_type = ATOMIC_TYPE_ULONG;
3204 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3205 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3206 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3207 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3209 atomic_type = ATOMIC_TYPE_LONGLONG;
3211 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3212 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3214 atomic_type = ATOMIC_TYPE_ULONGLONG;
3217 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3218 atomic_type = unsigned_int8_type_kind;
3221 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3222 atomic_type = unsigned_int16_type_kind;
3225 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3226 atomic_type = unsigned_int32_type_kind;
3229 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3230 atomic_type = unsigned_int64_type_kind;
3233 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3234 atomic_type = unsigned_int128_type_kind;
3237 case SPECIFIER_INT8:
3238 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3239 atomic_type = int8_type_kind;
3242 case SPECIFIER_INT16:
3243 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3244 atomic_type = int16_type_kind;
3247 case SPECIFIER_INT32:
3248 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3249 atomic_type = int32_type_kind;
3252 case SPECIFIER_INT64:
3253 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3254 atomic_type = int64_type_kind;
3257 case SPECIFIER_INT128:
3258 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3259 atomic_type = int128_type_kind;
3262 case SPECIFIER_FLOAT:
3263 atomic_type = ATOMIC_TYPE_FLOAT;
3265 case SPECIFIER_DOUBLE:
3266 atomic_type = ATOMIC_TYPE_DOUBLE;
3268 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3269 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3271 case SPECIFIER_BOOL:
3272 atomic_type = ATOMIC_TYPE_BOOL;
3274 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3275 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3276 atomic_type = ATOMIC_TYPE_FLOAT;
3278 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3279 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3280 atomic_type = ATOMIC_TYPE_DOUBLE;
3282 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3283 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3284 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3287 /* invalid specifier combination, give an error message */
3288 if (type_specifiers == 0) {
3289 if (! strict_mode) {
3290 if (warning.implicit_int) {
3291 warningf(HERE, "no type specifiers in declaration, using 'int'");
3293 atomic_type = ATOMIC_TYPE_INT;
3296 errorf(HERE, "no type specifiers given in declaration");
3298 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3299 (type_specifiers & SPECIFIER_UNSIGNED)) {
3300 errorf(HERE, "signed and unsigned specifiers gives");
3301 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3302 errorf(HERE, "only integer types can be signed or unsigned");
3304 errorf(HERE, "multiple datatypes in declaration");
3306 atomic_type = ATOMIC_TYPE_INVALID;
3309 if (type_specifiers & SPECIFIER_COMPLEX &&
3310 atomic_type != ATOMIC_TYPE_INVALID) {
3311 type = allocate_type_zero(TYPE_COMPLEX, &builtin_source_position);
3312 type->complex.akind = atomic_type;
3313 } else if (type_specifiers & SPECIFIER_IMAGINARY &&
3314 atomic_type != ATOMIC_TYPE_INVALID) {
3315 type = allocate_type_zero(TYPE_IMAGINARY, &builtin_source_position);
3316 type->imaginary.akind = atomic_type;
3318 type = allocate_type_zero(TYPE_ATOMIC, &builtin_source_position);
3319 type->atomic.akind = atomic_type;
3323 if (type_specifiers != 0) {
3324 errorf(HERE, "multiple datatypes in declaration");
3328 /* FIXME: check type qualifiers here */
3330 type->base.qualifiers = qualifiers;
3331 type->base.modifiers = modifiers;
3333 type_t *result = typehash_insert(type);
3334 if (newtype && result != type) {
3338 specifiers->type = result;
3343 static type_qualifiers_t parse_type_qualifiers(void)
3345 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3348 switch(token.type) {
3349 /* type qualifiers */
3350 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3351 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3352 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3353 /* microsoft extended type modifiers */
3354 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3355 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3356 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3357 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3358 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3366 static declaration_t *parse_identifier_list(void)
3368 declaration_t *declarations = NULL;
3369 declaration_t *last_declaration = NULL;
3371 declaration_t *const declaration = allocate_declaration_zero();
3372 declaration->type = NULL; /* a K&R parameter list has no types, yet */
3373 declaration->source_position = token.source_position;
3374 declaration->symbol = token.v.symbol;
3377 if (last_declaration != NULL) {
3378 last_declaration->next = declaration;
3380 declarations = declaration;
3382 last_declaration = declaration;
3384 if (token.type != ',') {
3388 } while(token.type == T_IDENTIFIER);
3390 return declarations;
3393 static type_t *automatic_type_conversion(type_t *orig_type);
3395 static void semantic_parameter(declaration_t *declaration)
3397 /* TODO: improve error messages */
3399 if (declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
3400 errorf(HERE, "typedef not allowed in parameter list");
3401 } else if (declaration->declared_storage_class != STORAGE_CLASS_NONE
3402 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
3403 errorf(HERE, "parameter may only have none or register storage class");
3406 type_t *const orig_type = declaration->type;
3407 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3408 * sugar. Turn it into a pointer.
3409 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3410 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
3412 type_t *const type = automatic_type_conversion(orig_type);
3413 declaration->type = type;
3415 if (is_type_incomplete(skip_typeref(type))) {
3416 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
3417 orig_type, declaration->symbol);
3421 static declaration_t *parse_parameter(void)
3423 declaration_specifiers_t specifiers;
3424 memset(&specifiers, 0, sizeof(specifiers));
3426 parse_declaration_specifiers(&specifiers);
3428 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
3433 static declaration_t *parse_parameters(function_type_t *type)
3435 declaration_t *declarations = NULL;
3438 add_anchor_token(')');
3439 int saved_comma_state = save_and_reset_anchor_state(',');
3441 if (token.type == T_IDENTIFIER) {
3442 symbol_t *symbol = token.v.symbol;
3443 if (!is_typedef_symbol(symbol)) {
3444 type->kr_style_parameters = true;
3445 declarations = parse_identifier_list();
3446 goto parameters_finished;
3450 if (token.type == ')') {
3451 type->unspecified_parameters = 1;
3452 goto parameters_finished;
3455 declaration_t *declaration;
3456 declaration_t *last_declaration = NULL;
3457 function_parameter_t *parameter;
3458 function_parameter_t *last_parameter = NULL;
3461 switch(token.type) {
3465 goto parameters_finished;
3468 case T___extension__:
3470 declaration = parse_parameter();
3472 /* func(void) is not a parameter */
3473 if (last_parameter == NULL
3474 && token.type == ')'
3475 && declaration->symbol == NULL
3476 && skip_typeref(declaration->type) == type_void) {
3477 goto parameters_finished;
3479 semantic_parameter(declaration);
3481 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
3482 memset(parameter, 0, sizeof(parameter[0]));
3483 parameter->type = declaration->type;
3485 if (last_parameter != NULL) {
3486 last_declaration->next = declaration;
3487 last_parameter->next = parameter;
3489 type->parameters = parameter;
3490 declarations = declaration;
3492 last_parameter = parameter;
3493 last_declaration = declaration;
3497 goto parameters_finished;
3499 if (token.type != ',') {
3500 goto parameters_finished;
3506 parameters_finished:
3507 rem_anchor_token(')');
3510 restore_anchor_state(',', saved_comma_state);
3511 return declarations;
3514 restore_anchor_state(',', saved_comma_state);
3518 typedef enum construct_type_kind_t {
3523 } construct_type_kind_t;
3525 typedef struct construct_type_t construct_type_t;
3526 struct construct_type_t {
3527 construct_type_kind_t kind;
3528 construct_type_t *next;
3531 typedef struct parsed_pointer_t parsed_pointer_t;
3532 struct parsed_pointer_t {
3533 construct_type_t construct_type;
3534 type_qualifiers_t type_qualifiers;
3537 typedef struct construct_function_type_t construct_function_type_t;
3538 struct construct_function_type_t {
3539 construct_type_t construct_type;
3540 type_t *function_type;
3543 typedef struct parsed_array_t parsed_array_t;
3544 struct parsed_array_t {
3545 construct_type_t construct_type;
3546 type_qualifiers_t type_qualifiers;
3552 typedef struct construct_base_type_t construct_base_type_t;
3553 struct construct_base_type_t {
3554 construct_type_t construct_type;
3558 static construct_type_t *parse_pointer_declarator(void)
3562 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3563 memset(pointer, 0, sizeof(pointer[0]));
3564 pointer->construct_type.kind = CONSTRUCT_POINTER;
3565 pointer->type_qualifiers = parse_type_qualifiers();
3567 return (construct_type_t*) pointer;
3570 static construct_type_t *parse_array_declarator(void)
3573 add_anchor_token(']');
3575 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
3576 memset(array, 0, sizeof(array[0]));
3577 array->construct_type.kind = CONSTRUCT_ARRAY;
3579 if (token.type == T_static) {
3580 array->is_static = true;
3584 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3585 if (type_qualifiers != 0) {
3586 if (token.type == T_static) {
3587 array->is_static = true;
3591 array->type_qualifiers = type_qualifiers;
3593 if (token.type == '*' && look_ahead(1)->type == ']') {
3594 array->is_variable = true;
3596 } else if (token.type != ']') {
3597 array->size = parse_assignment_expression();
3600 rem_anchor_token(']');
3603 return (construct_type_t*) array;
3608 static construct_type_t *parse_function_declarator(declaration_t *declaration)
3611 if (declaration != NULL) {
3612 type = allocate_type_zero(TYPE_FUNCTION, &declaration->source_position);
3614 unsigned mask = declaration->modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
3616 if (mask & (mask-1)) {
3617 const char *first = NULL, *second = NULL;
3619 /* more than one calling convention set */
3620 if (declaration->modifiers & DM_CDECL) {
3621 if (first == NULL) first = "cdecl";
3622 else if (second == NULL) second = "cdecl";
3624 if (declaration->modifiers & DM_STDCALL) {
3625 if (first == NULL) first = "stdcall";
3626 else if (second == NULL) second = "stdcall";
3628 if (declaration->modifiers & DM_FASTCALL) {
3629 if (first == NULL) first = "faslcall";
3630 else if (second == NULL) second = "fastcall";
3632 if (declaration->modifiers & DM_THISCALL) {
3633 if (first == NULL) first = "thiscall";
3634 else if (second == NULL) second = "thiscall";
3636 errorf(&declaration->source_position, "%s and %s attributes are not compatible", first, second);
3639 if (declaration->modifiers & DM_CDECL)
3640 type->function.calling_convention = CC_CDECL;
3641 else if (declaration->modifiers & DM_STDCALL)
3642 type->function.calling_convention = CC_STDCALL;
3643 else if (declaration->modifiers & DM_FASTCALL)
3644 type->function.calling_convention = CC_FASTCALL;
3645 else if (declaration->modifiers & DM_THISCALL)
3646 type->function.calling_convention = CC_THISCALL;
3648 type = allocate_type_zero(TYPE_FUNCTION, HERE);
3651 declaration_t *parameters = parse_parameters(&type->function);
3652 if (declaration != NULL) {
3653 declaration->scope.declarations = parameters;
3656 construct_function_type_t *construct_function_type =
3657 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
3658 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
3659 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
3660 construct_function_type->function_type = type;
3662 return &construct_function_type->construct_type;
3665 static void fix_declaration_type(declaration_t *declaration)
3667 decl_modifiers_t declaration_modifiers = declaration->modifiers;
3668 type_modifiers_t type_modifiers = declaration->type->base.modifiers;
3670 if (declaration_modifiers & DM_TRANSPARENT_UNION)
3671 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3673 if (declaration->type->base.modifiers == type_modifiers)
3676 type_t *copy = duplicate_type(declaration->type);
3677 copy->base.modifiers = type_modifiers;
3679 type_t *result = typehash_insert(copy);
3680 if (result != copy) {
3681 obstack_free(type_obst, copy);
3684 declaration->type = result;
3687 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
3688 bool may_be_abstract)
3690 /* construct a single linked list of construct_type_t's which describe
3691 * how to construct the final declarator type */
3692 construct_type_t *first = NULL;
3693 construct_type_t *last = NULL;
3694 gnu_attribute_t *attributes = NULL;
3696 decl_modifiers_t modifiers = parse_attributes(&attributes);
3699 while(token.type == '*') {
3700 construct_type_t *type = parse_pointer_declarator();
3710 /* TODO: find out if this is correct */
3711 modifiers |= parse_attributes(&attributes);
3714 construct_type_t *inner_types = NULL;
3716 switch(token.type) {
3718 if (declaration == NULL) {
3719 errorf(HERE, "no identifier expected in typename");
3721 declaration->symbol = token.v.symbol;
3722 declaration->source_position = token.source_position;
3728 add_anchor_token(')');
3729 inner_types = parse_inner_declarator(declaration, may_be_abstract);
3730 rem_anchor_token(')');
3734 if (may_be_abstract)
3736 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3737 /* avoid a loop in the outermost scope, because eat_statement doesn't
3739 if (token.type == '}' && current_function == NULL) {
3747 construct_type_t *p = last;
3750 construct_type_t *type;
3751 switch(token.type) {
3753 type = parse_function_declarator(declaration);
3756 type = parse_array_declarator();
3759 goto declarator_finished;
3762 /* insert in the middle of the list (behind p) */
3764 type->next = p->next;
3775 declarator_finished:
3776 /* append inner_types at the end of the list, we don't to set last anymore
3777 * as it's not needed anymore */
3779 assert(first == NULL);
3780 first = inner_types;
3782 last->next = inner_types;
3790 static void parse_declaration_attributes(declaration_t *declaration)
3792 gnu_attribute_t *attributes = NULL;
3793 decl_modifiers_t modifiers = parse_attributes(&attributes);
3795 if (declaration == NULL)
3798 declaration->modifiers |= modifiers;
3799 /* check if we have these stupid mode attributes... */
3800 type_t *old_type = declaration->type;
3801 if (old_type == NULL)
3804 gnu_attribute_t *attribute = attributes;
3805 for ( ; attribute != NULL; attribute = attribute->next) {
3806 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
3809 atomic_type_kind_t akind = attribute->u.akind;
3810 if (!is_type_signed(old_type)) {
3812 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
3813 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
3814 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
3815 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
3817 panic("invalid akind in mode attribute");
3821 = make_atomic_type(akind, old_type->base.qualifiers);
3825 static type_t *construct_declarator_type(construct_type_t *construct_list,
3828 construct_type_t *iter = construct_list;
3829 for( ; iter != NULL; iter = iter->next) {
3830 switch(iter->kind) {
3831 case CONSTRUCT_INVALID:
3832 internal_errorf(HERE, "invalid type construction found");
3833 case CONSTRUCT_FUNCTION: {
3834 construct_function_type_t *construct_function_type
3835 = (construct_function_type_t*) iter;
3837 type_t *function_type = construct_function_type->function_type;
3839 function_type->function.return_type = type;
3841 type_t *skipped_return_type = skip_typeref(type);
3842 if (is_type_function(skipped_return_type)) {
3843 errorf(HERE, "function returning function is not allowed");
3844 type = type_error_type;
3845 } else if (is_type_array(skipped_return_type)) {
3846 errorf(HERE, "function returning array is not allowed");
3847 type = type_error_type;
3849 type = function_type;
3854 case CONSTRUCT_POINTER: {
3855 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
3856 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, &null_position);
3857 pointer_type->pointer.points_to = type;
3858 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
3860 type = pointer_type;
3864 case CONSTRUCT_ARRAY: {
3865 parsed_array_t *parsed_array = (parsed_array_t*) iter;
3866 type_t *array_type = allocate_type_zero(TYPE_ARRAY, &null_position);
3868 expression_t *size_expression = parsed_array->size;
3869 if (size_expression != NULL) {
3871 = create_implicit_cast(size_expression, type_size_t);
3874 array_type->base.qualifiers = parsed_array->type_qualifiers;
3875 array_type->array.element_type = type;
3876 array_type->array.is_static = parsed_array->is_static;
3877 array_type->array.is_variable = parsed_array->is_variable;
3878 array_type->array.size_expression = size_expression;
3880 if (size_expression != NULL) {
3881 if (is_constant_expression(size_expression)) {
3882 array_type->array.size_constant = true;
3883 array_type->array.size
3884 = fold_constant(size_expression);
3886 array_type->array.is_vla = true;
3890 type_t *skipped_type = skip_typeref(type);
3891 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
3892 errorf(HERE, "array of void is not allowed");
3893 type = type_error_type;
3901 type_t *hashed_type = typehash_insert(type);
3902 if (hashed_type != type) {
3903 /* the function type was constructed earlier freeing it here will
3904 * destroy other types... */
3905 if (iter->kind != CONSTRUCT_FUNCTION) {
3915 static declaration_t *parse_declarator(
3916 const declaration_specifiers_t *specifiers, bool may_be_abstract)
3918 declaration_t *const declaration = allocate_declaration_zero();
3919 declaration->declared_storage_class = specifiers->declared_storage_class;
3920 declaration->modifiers = specifiers->modifiers;
3921 declaration->deprecated = specifiers->deprecated;
3922 declaration->deprecated_string = specifiers->deprecated_string;
3923 declaration->get_property_sym = specifiers->get_property_sym;
3924 declaration->put_property_sym = specifiers->put_property_sym;
3925 declaration->is_inline = specifiers->is_inline;
3927 declaration->storage_class = specifiers->declared_storage_class;
3928 if (declaration->storage_class == STORAGE_CLASS_NONE
3929 && scope != global_scope) {
3930 declaration->storage_class = STORAGE_CLASS_AUTO;
3933 if (specifiers->alignment != 0) {
3934 /* TODO: add checks here */
3935 declaration->alignment = specifiers->alignment;
3938 construct_type_t *construct_type
3939 = parse_inner_declarator(declaration, may_be_abstract);
3940 type_t *const type = specifiers->type;
3941 declaration->type = construct_declarator_type(construct_type, type);
3943 parse_declaration_attributes(declaration);
3945 fix_declaration_type(declaration);
3947 if (construct_type != NULL) {
3948 obstack_free(&temp_obst, construct_type);
3954 static type_t *parse_abstract_declarator(type_t *base_type)
3956 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
3958 type_t *result = construct_declarator_type(construct_type, base_type);
3959 if (construct_type != NULL) {
3960 obstack_free(&temp_obst, construct_type);
3966 static declaration_t *append_declaration(declaration_t* const declaration)
3968 if (last_declaration != NULL) {
3969 last_declaration->next = declaration;
3971 scope->declarations = declaration;
3973 last_declaration = declaration;
3978 * Check if the declaration of main is suspicious. main should be a
3979 * function with external linkage, returning int, taking either zero
3980 * arguments, two, or three arguments of appropriate types, ie.
3982 * int main([ int argc, char **argv [, char **env ] ]).
3984 * @param decl the declaration to check
3985 * @param type the function type of the declaration
3987 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
3989 if (decl->storage_class == STORAGE_CLASS_STATIC) {
3990 warningf(&decl->source_position,
3991 "'main' is normally a non-static function");
3993 if (skip_typeref(func_type->return_type) != type_int) {
3994 warningf(&decl->source_position,
3995 "return type of 'main' should be 'int', but is '%T'",
3996 func_type->return_type);
3998 const function_parameter_t *parm = func_type->parameters;
4000 type_t *const first_type = parm->type;
4001 if (!types_compatible(skip_typeref(first_type), type_int)) {
4002 warningf(&decl->source_position,
4003 "first argument of 'main' should be 'int', but is '%T'", first_type);
4007 type_t *const second_type = parm->type;
4008 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4009 warningf(&decl->source_position,
4010 "second argument of 'main' should be 'char**', but is '%T'", second_type);
4014 type_t *const third_type = parm->type;
4015 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4016 warningf(&decl->source_position,
4017 "third argument of 'main' should be 'char**', but is '%T'", third_type);
4021 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4025 warningf(&decl->source_position, "'main' takes only zero, two or three arguments");
4031 * Check if a symbol is the equal to "main".
4033 static bool is_sym_main(const symbol_t *const sym)
4035 return strcmp(sym->string, "main") == 0;
4038 static declaration_t *internal_record_declaration(
4039 declaration_t *const declaration,
4040 const bool is_function_definition)
4042 const symbol_t *const symbol = declaration->symbol;
4043 const namespace_t namespc = (namespace_t)declaration->namespc;
4045 assert(declaration->symbol != NULL);
4046 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4048 type_t *const orig_type = declaration->type;
4049 type_t *const type = skip_typeref(orig_type);
4050 if (is_type_function(type) &&
4051 type->function.unspecified_parameters &&
4052 warning.strict_prototypes &&
4053 previous_declaration == NULL) {
4054 warningf(&declaration->source_position,
4055 "function declaration '%#T' is not a prototype",
4056 orig_type, declaration->symbol);
4059 if (is_function_definition && warning.main && is_sym_main(symbol)) {
4060 check_type_of_main(declaration, &type->function);
4063 assert(declaration != previous_declaration);
4064 if (previous_declaration != NULL
4065 && previous_declaration->parent_scope == scope) {
4066 /* can happen for K&R style declarations */
4067 if (previous_declaration->type == NULL) {
4068 previous_declaration->type = declaration->type;
4071 const type_t *prev_type = skip_typeref(previous_declaration->type);
4072 if (!types_compatible(type, prev_type)) {
4073 errorf(&declaration->source_position,
4074 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4075 orig_type, symbol, previous_declaration->type, symbol,
4076 &previous_declaration->source_position);
4078 unsigned old_storage_class = previous_declaration->storage_class;
4079 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
4080 errorf(&declaration->source_position,
4081 "redeclaration of enum entry '%Y' (declared %P)",
4082 symbol, &previous_declaration->source_position);
4083 return previous_declaration;
4086 unsigned new_storage_class = declaration->storage_class;
4088 if (is_type_incomplete(prev_type)) {
4089 previous_declaration->type = type;
4093 /* pretend no storage class means extern for function
4094 * declarations (except if the previous declaration is neither
4095 * none nor extern) */
4096 if (is_type_function(type)) {
4097 if (prev_type->function.unspecified_parameters) {
4098 previous_declaration->type = type;
4102 switch (old_storage_class) {
4103 case STORAGE_CLASS_NONE:
4104 old_storage_class = STORAGE_CLASS_EXTERN;
4107 case STORAGE_CLASS_EXTERN:
4108 if (is_function_definition) {
4109 if (warning.missing_prototypes &&
4110 prev_type->function.unspecified_parameters &&
4111 !is_sym_main(symbol)) {
4112 warningf(&declaration->source_position,
4113 "no previous prototype for '%#T'",
4116 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4117 new_storage_class = STORAGE_CLASS_EXTERN;
4126 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4127 new_storage_class == STORAGE_CLASS_EXTERN) {
4128 warn_redundant_declaration:
4129 if (warning.redundant_decls && strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4130 warningf(&declaration->source_position,
4131 "redundant declaration for '%Y' (declared %P)",
4132 symbol, &previous_declaration->source_position);
4134 } else if (current_function == NULL) {
4135 if (old_storage_class != STORAGE_CLASS_STATIC &&
4136 new_storage_class == STORAGE_CLASS_STATIC) {
4137 errorf(&declaration->source_position,
4138 "static declaration of '%Y' follows non-static declaration (declared %P)",
4139 symbol, &previous_declaration->source_position);
4140 } else if (old_storage_class != STORAGE_CLASS_EXTERN
4141 && !is_function_definition) {
4142 goto warn_redundant_declaration;
4143 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4144 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4145 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4147 } else if (old_storage_class == new_storage_class) {
4148 errorf(&declaration->source_position,
4149 "redeclaration of '%Y' (declared %P)",
4150 symbol, &previous_declaration->source_position);
4152 errorf(&declaration->source_position,
4153 "redeclaration of '%Y' with different linkage (declared %P)",
4154 symbol, &previous_declaration->source_position);
4158 if (declaration->is_inline)
4159 previous_declaration->is_inline = true;
4160 return previous_declaration;
4161 } else if (is_function_definition) {
4162 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4163 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4164 warningf(&declaration->source_position,
4165 "no previous prototype for '%#T'", orig_type, symbol);
4166 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4167 warningf(&declaration->source_position,
4168 "no previous declaration for '%#T'", orig_type,
4172 } else if (warning.missing_declarations &&
4173 scope == global_scope &&
4174 !is_type_function(type) && (
4175 declaration->storage_class == STORAGE_CLASS_NONE ||
4176 declaration->storage_class == STORAGE_CLASS_THREAD
4178 warningf(&declaration->source_position,
4179 "no previous declaration for '%#T'", orig_type, symbol);
4182 assert(declaration->parent_scope == NULL);
4183 assert(scope != NULL);
4185 declaration->parent_scope = scope;
4187 environment_push(declaration);
4188 return append_declaration(declaration);
4191 static declaration_t *record_declaration(declaration_t *declaration)
4193 return internal_record_declaration(declaration, false);
4196 static declaration_t *record_function_definition(declaration_t *declaration)
4198 return internal_record_declaration(declaration, true);
4201 static void parser_error_multiple_definition(declaration_t *declaration,
4202 const source_position_t *source_position)
4204 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4205 declaration->symbol, &declaration->source_position);
4208 static bool is_declaration_specifier(const token_t *token,
4209 bool only_specifiers_qualifiers)
4211 switch(token->type) {
4216 return is_typedef_symbol(token->v.symbol);
4218 case T___extension__:
4220 return !only_specifiers_qualifiers;
4227 static void parse_init_declarator_rest(declaration_t *declaration)
4231 type_t *orig_type = declaration->type;
4232 type_t *type = skip_typeref(orig_type);
4234 if (declaration->init.initializer != NULL) {
4235 parser_error_multiple_definition(declaration, HERE);
4238 bool must_be_constant = false;
4239 if (declaration->storage_class == STORAGE_CLASS_STATIC
4240 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4241 || declaration->parent_scope == global_scope) {
4242 must_be_constant = true;
4245 parse_initializer_env_t env;
4246 env.type = orig_type;
4247 env.must_be_constant = must_be_constant;
4248 env.declaration = declaration;
4250 initializer_t *initializer = parse_initializer(&env);
4252 if (env.type != orig_type) {
4253 orig_type = env.type;
4254 type = skip_typeref(orig_type);
4255 declaration->type = env.type;
4258 if (is_type_function(type)) {
4259 errorf(&declaration->source_position,
4260 "initializers not allowed for function types at declator '%Y' (type '%T')",
4261 declaration->symbol, orig_type);
4263 declaration->init.initializer = initializer;
4267 /* parse rest of a declaration without any declarator */
4268 static void parse_anonymous_declaration_rest(
4269 const declaration_specifiers_t *specifiers,
4270 parsed_declaration_func finished_declaration)
4274 declaration_t *const declaration = allocate_declaration_zero();
4275 declaration->type = specifiers->type;
4276 declaration->declared_storage_class = specifiers->declared_storage_class;
4277 declaration->source_position = specifiers->source_position;
4278 declaration->modifiers = specifiers->modifiers;
4280 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4281 warningf(&declaration->source_position,
4282 "useless storage class in empty declaration");
4284 declaration->storage_class = STORAGE_CLASS_NONE;
4286 type_t *type = declaration->type;
4287 switch (type->kind) {
4288 case TYPE_COMPOUND_STRUCT:
4289 case TYPE_COMPOUND_UNION: {
4290 if (type->compound.declaration->symbol == NULL) {
4291 warningf(&declaration->source_position,
4292 "unnamed struct/union that defines no instances");
4301 warningf(&declaration->source_position, "empty declaration");
4305 finished_declaration(declaration);
4308 static void parse_declaration_rest(declaration_t *ndeclaration,
4309 const declaration_specifiers_t *specifiers,
4310 parsed_declaration_func finished_declaration)
4312 add_anchor_token(';');
4313 add_anchor_token('=');
4314 add_anchor_token(',');
4316 declaration_t *declaration = finished_declaration(ndeclaration);
4318 type_t *orig_type = declaration->type;
4319 type_t *type = skip_typeref(orig_type);
4321 if (type->kind != TYPE_FUNCTION &&
4322 declaration->is_inline &&
4323 is_type_valid(type)) {
4324 warningf(&declaration->source_position,
4325 "variable '%Y' declared 'inline'\n", declaration->symbol);
4328 if (token.type == '=') {
4329 parse_init_declarator_rest(declaration);
4332 if (token.type != ',')
4336 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4341 rem_anchor_token(';');
4342 rem_anchor_token('=');
4343 rem_anchor_token(',');
4346 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4348 symbol_t *symbol = declaration->symbol;
4349 if (symbol == NULL) {
4350 errorf(HERE, "anonymous declaration not valid as function parameter");
4353 namespace_t namespc = (namespace_t) declaration->namespc;
4354 if (namespc != NAMESPACE_NORMAL) {
4355 return record_declaration(declaration);
4358 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4359 if (previous_declaration == NULL ||
4360 previous_declaration->parent_scope != scope) {
4361 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4366 if (previous_declaration->type == NULL) {
4367 previous_declaration->type = declaration->type;
4368 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4369 previous_declaration->storage_class = declaration->storage_class;
4370 previous_declaration->parent_scope = scope;
4371 return previous_declaration;
4373 return record_declaration(declaration);
4377 static void parse_declaration(parsed_declaration_func finished_declaration)
4379 declaration_specifiers_t specifiers;
4380 memset(&specifiers, 0, sizeof(specifiers));
4381 parse_declaration_specifiers(&specifiers);
4383 if (token.type == ';') {
4384 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4386 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4387 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4391 static type_t *get_default_promoted_type(type_t *orig_type)
4393 type_t *result = orig_type;
4395 type_t *type = skip_typeref(orig_type);
4396 if (is_type_integer(type)) {
4397 result = promote_integer(type);
4398 } else if (type == type_float) {
4399 result = type_double;
4405 static void parse_kr_declaration_list(declaration_t *declaration)
4407 type_t *type = skip_typeref(declaration->type);
4408 if (!is_type_function(type))
4411 if (!type->function.kr_style_parameters)
4414 /* push function parameters */
4415 int top = environment_top();
4416 scope_t *last_scope = scope;
4417 set_scope(&declaration->scope);
4419 declaration_t *parameter = declaration->scope.declarations;
4420 for ( ; parameter != NULL; parameter = parameter->next) {
4421 assert(parameter->parent_scope == NULL);
4422 parameter->parent_scope = scope;
4423 environment_push(parameter);
4426 /* parse declaration list */
4427 while (is_declaration_specifier(&token, false)) {
4428 parse_declaration(finished_kr_declaration);
4431 /* pop function parameters */
4432 assert(scope == &declaration->scope);
4433 set_scope(last_scope);
4434 environment_pop_to(top);
4436 /* update function type */
4437 type_t *new_type = duplicate_type(type);
4439 function_parameter_t *parameters = NULL;
4440 function_parameter_t *last_parameter = NULL;
4442 declaration_t *parameter_declaration = declaration->scope.declarations;
4443 for( ; parameter_declaration != NULL;
4444 parameter_declaration = parameter_declaration->next) {
4445 type_t *parameter_type = parameter_declaration->type;
4446 if (parameter_type == NULL) {
4448 errorf(HERE, "no type specified for function parameter '%Y'",
4449 parameter_declaration->symbol);
4451 if (warning.implicit_int) {
4452 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4453 parameter_declaration->symbol);
4455 parameter_type = type_int;
4456 parameter_declaration->type = parameter_type;
4460 semantic_parameter(parameter_declaration);
4461 parameter_type = parameter_declaration->type;
4464 * we need the default promoted types for the function type
4466 parameter_type = get_default_promoted_type(parameter_type);
4468 function_parameter_t *function_parameter
4469 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4470 memset(function_parameter, 0, sizeof(function_parameter[0]));
4472 function_parameter->type = parameter_type;
4473 if (last_parameter != NULL) {
4474 last_parameter->next = function_parameter;
4476 parameters = function_parameter;
4478 last_parameter = function_parameter;
4481 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4483 new_type->function.parameters = parameters;
4484 new_type->function.unspecified_parameters = true;
4486 type = typehash_insert(new_type);
4487 if (type != new_type) {
4488 obstack_free(type_obst, new_type);
4491 declaration->type = type;
4494 static bool first_err = true;
4497 * When called with first_err set, prints the name of the current function,
4500 static void print_in_function(void) {
4503 diagnosticf("%s: In function '%Y':\n",
4504 current_function->source_position.input_name,
4505 current_function->symbol);
4510 * Check if all labels are defined in the current function.
4511 * Check if all labels are used in the current function.
4513 static void check_labels(void)
4515 for (const goto_statement_t *goto_statement = goto_first;
4516 goto_statement != NULL;
4517 goto_statement = goto_statement->next) {
4518 declaration_t *label = goto_statement->label;
4521 if (label->source_position.input_name == NULL) {
4522 print_in_function();
4523 errorf(&goto_statement->base.source_position,
4524 "label '%Y' used but not defined", label->symbol);
4527 goto_first = goto_last = NULL;
4529 if (warning.unused_label) {
4530 for (const label_statement_t *label_statement = label_first;
4531 label_statement != NULL;
4532 label_statement = label_statement->next) {
4533 const declaration_t *label = label_statement->label;
4535 if (! label->used) {
4536 print_in_function();
4537 warningf(&label_statement->base.source_position,
4538 "label '%Y' defined but not used", label->symbol);
4542 label_first = label_last = NULL;
4546 * Check declarations of current_function for unused entities.
4548 static void check_declarations(void)
4550 if (warning.unused_parameter) {
4551 const scope_t *scope = ¤t_function->scope;
4553 const declaration_t *parameter = scope->declarations;
4554 for (; parameter != NULL; parameter = parameter->next) {
4555 if (! parameter->used) {
4556 print_in_function();
4557 warningf(¶meter->source_position,
4558 "unused parameter '%Y'", parameter->symbol);
4562 if (warning.unused_variable) {
4566 static void parse_external_declaration(void)
4568 /* function-definitions and declarations both start with declaration
4570 declaration_specifiers_t specifiers;
4571 memset(&specifiers, 0, sizeof(specifiers));
4573 add_anchor_token(';');
4574 parse_declaration_specifiers(&specifiers);
4575 rem_anchor_token(';');
4577 /* must be a declaration */
4578 if (token.type == ';') {
4579 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4583 add_anchor_token(',');
4584 add_anchor_token('=');
4585 rem_anchor_token(';');
4587 /* declarator is common to both function-definitions and declarations */
4588 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4590 rem_anchor_token(',');
4591 rem_anchor_token('=');
4592 rem_anchor_token(';');
4594 /* must be a declaration */
4595 if (token.type == ',' || token.type == '=' || token.type == ';') {
4596 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4600 /* must be a function definition */
4601 parse_kr_declaration_list(ndeclaration);
4603 if (token.type != '{') {
4604 parse_error_expected("while parsing function definition", '{', NULL);
4605 eat_until_matching_token(';');
4609 type_t *type = ndeclaration->type;
4611 /* note that we don't skip typerefs: the standard doesn't allow them here
4612 * (so we can't use is_type_function here) */
4613 if (type->kind != TYPE_FUNCTION) {
4614 if (is_type_valid(type)) {
4615 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4616 type, ndeclaration->symbol);
4622 /* § 6.7.5.3 (14) a function definition with () means no
4623 * parameters (and not unspecified parameters) */
4624 if (type->function.unspecified_parameters
4625 && type->function.parameters == NULL
4626 && !type->function.kr_style_parameters) {
4627 type_t *duplicate = duplicate_type(type);
4628 duplicate->function.unspecified_parameters = false;
4630 type = typehash_insert(duplicate);
4631 if (type != duplicate) {
4632 obstack_free(type_obst, duplicate);
4634 ndeclaration->type = type;
4637 declaration_t *const declaration = record_function_definition(ndeclaration);
4638 if (ndeclaration != declaration) {
4639 declaration->scope = ndeclaration->scope;
4641 type = skip_typeref(declaration->type);
4643 /* push function parameters and switch scope */
4644 int top = environment_top();
4645 scope_t *last_scope = scope;
4646 set_scope(&declaration->scope);
4648 declaration_t *parameter = declaration->scope.declarations;
4649 for( ; parameter != NULL; parameter = parameter->next) {
4650 if (parameter->parent_scope == &ndeclaration->scope) {
4651 parameter->parent_scope = scope;
4653 assert(parameter->parent_scope == NULL
4654 || parameter->parent_scope == scope);
4655 parameter->parent_scope = scope;
4656 if (parameter->symbol == NULL) {
4657 errorf(&ndeclaration->source_position, "parameter name omitted");
4660 environment_push(parameter);
4663 if (declaration->init.statement != NULL) {
4664 parser_error_multiple_definition(declaration, HERE);
4666 goto end_of_parse_external_declaration;
4668 /* parse function body */
4669 int label_stack_top = label_top();
4670 declaration_t *old_current_function = current_function;
4671 current_function = declaration;
4673 declaration->init.statement = parse_compound_statement(false);
4676 check_declarations();
4678 assert(current_function == declaration);
4679 current_function = old_current_function;
4680 label_pop_to(label_stack_top);
4683 end_of_parse_external_declaration:
4684 assert(scope == &declaration->scope);
4685 set_scope(last_scope);
4686 environment_pop_to(top);
4689 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4690 source_position_t *source_position)
4692 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4694 type->bitfield.base_type = base_type;
4695 type->bitfield.size = size;
4700 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4703 declaration_t *iter = compound_declaration->scope.declarations;
4704 for( ; iter != NULL; iter = iter->next) {
4705 if (iter->namespc != NAMESPACE_NORMAL)
4708 if (iter->symbol == NULL) {
4709 type_t *type = skip_typeref(iter->type);
4710 if (is_type_compound(type)) {
4711 declaration_t *result
4712 = find_compound_entry(type->compound.declaration, symbol);
4719 if (iter->symbol == symbol) {
4727 static void parse_compound_declarators(declaration_t *struct_declaration,
4728 const declaration_specifiers_t *specifiers)
4730 declaration_t *last_declaration = struct_declaration->scope.declarations;
4731 if (last_declaration != NULL) {
4732 while(last_declaration->next != NULL) {
4733 last_declaration = last_declaration->next;
4738 declaration_t *declaration;
4740 if (token.type == ':') {
4741 source_position_t source_position = *HERE;
4744 type_t *base_type = specifiers->type;
4745 expression_t *size = parse_constant_expression();
4747 if (!is_type_integer(skip_typeref(base_type))) {
4748 errorf(HERE, "bitfield base type '%T' is not an integer type",
4752 type_t *type = make_bitfield_type(base_type, size, &source_position);
4754 declaration = allocate_declaration_zero();
4755 declaration->namespc = NAMESPACE_NORMAL;
4756 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4757 declaration->storage_class = STORAGE_CLASS_NONE;
4758 declaration->source_position = source_position;
4759 declaration->modifiers = specifiers->modifiers;
4760 declaration->type = type;
4762 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4764 type_t *orig_type = declaration->type;
4765 type_t *type = skip_typeref(orig_type);
4767 if (token.type == ':') {
4768 source_position_t source_position = *HERE;
4770 expression_t *size = parse_constant_expression();
4772 if (!is_type_integer(type)) {
4773 errorf(HERE, "bitfield base type '%T' is not an "
4774 "integer type", orig_type);
4777 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4778 declaration->type = bitfield_type;
4780 /* TODO we ignore arrays for now... what is missing is a check
4781 * that they're at the end of the struct */
4782 if (is_type_incomplete(type) && !is_type_array(type)) {
4784 "compound member '%Y' has incomplete type '%T'",
4785 declaration->symbol, orig_type);
4786 } else if (is_type_function(type)) {
4787 errorf(HERE, "compound member '%Y' must not have function "
4788 "type '%T'", declaration->symbol, orig_type);
4793 /* make sure we don't define a symbol multiple times */
4794 symbol_t *symbol = declaration->symbol;
4795 if (symbol != NULL) {
4796 declaration_t *prev_decl
4797 = find_compound_entry(struct_declaration, symbol);
4799 if (prev_decl != NULL) {
4800 assert(prev_decl->symbol == symbol);
4801 errorf(&declaration->source_position,
4802 "multiple declarations of symbol '%Y' (declared %P)",
4803 symbol, &prev_decl->source_position);
4807 /* append declaration */
4808 if (last_declaration != NULL) {
4809 last_declaration->next = declaration;
4811 struct_declaration->scope.declarations = declaration;
4813 last_declaration = declaration;
4815 if (token.type != ',')
4825 static void parse_compound_type_entries(declaration_t *compound_declaration)
4828 add_anchor_token('}');
4830 while(token.type != '}' && token.type != T_EOF) {
4831 declaration_specifiers_t specifiers;
4832 memset(&specifiers, 0, sizeof(specifiers));
4833 parse_declaration_specifiers(&specifiers);
4835 parse_compound_declarators(compound_declaration, &specifiers);
4837 rem_anchor_token('}');
4839 if (token.type == T_EOF) {
4840 errorf(HERE, "EOF while parsing struct");
4845 static type_t *parse_typename(void)
4847 declaration_specifiers_t specifiers;
4848 memset(&specifiers, 0, sizeof(specifiers));
4849 parse_declaration_specifiers(&specifiers);
4850 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4851 /* TODO: improve error message, user does probably not know what a
4852 * storage class is...
4854 errorf(HERE, "typename may not have a storage class");
4857 type_t *result = parse_abstract_declarator(specifiers.type);
4865 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4866 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4867 expression_t *left);
4869 typedef struct expression_parser_function_t expression_parser_function_t;
4870 struct expression_parser_function_t {
4871 unsigned precedence;
4872 parse_expression_function parser;
4873 unsigned infix_precedence;
4874 parse_expression_infix_function infix_parser;
4877 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4880 * Prints an error message if an expression was expected but not read
4882 static expression_t *expected_expression_error(void)
4884 /* skip the error message if the error token was read */
4885 if (token.type != T_ERROR) {
4886 errorf(HERE, "expected expression, got token '%K'", &token);
4890 return create_invalid_expression();
4894 * Parse a string constant.
4896 static expression_t *parse_string_const(void)
4899 if (token.type == T_STRING_LITERAL) {
4900 string_t res = token.v.string;
4902 while (token.type == T_STRING_LITERAL) {
4903 res = concat_strings(&res, &token.v.string);
4906 if (token.type != T_WIDE_STRING_LITERAL) {
4907 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4908 /* note: that we use type_char_ptr here, which is already the
4909 * automatic converted type. revert_automatic_type_conversion
4910 * will construct the array type */
4911 cnst->base.type = type_char_ptr;
4912 cnst->string.value = res;
4916 wres = concat_string_wide_string(&res, &token.v.wide_string);
4918 wres = token.v.wide_string;
4923 switch (token.type) {
4924 case T_WIDE_STRING_LITERAL:
4925 wres = concat_wide_strings(&wres, &token.v.wide_string);
4928 case T_STRING_LITERAL:
4929 wres = concat_wide_string_string(&wres, &token.v.string);
4933 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4934 cnst->base.type = type_wchar_t_ptr;
4935 cnst->wide_string.value = wres;
4944 * Parse an integer constant.
4946 static expression_t *parse_int_const(void)
4948 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4949 cnst->base.source_position = *HERE;
4950 cnst->base.type = token.datatype;
4951 cnst->conste.v.int_value = token.v.intvalue;
4959 * Parse a character constant.
4961 static expression_t *parse_character_constant(void)
4963 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4965 cnst->base.source_position = *HERE;
4966 cnst->base.type = token.datatype;
4967 cnst->conste.v.character = token.v.string;
4969 if (cnst->conste.v.character.size != 1) {
4970 if (warning.multichar && (c_mode & _GNUC)) {
4972 warningf(HERE, "multi-character character constant");
4974 errorf(HERE, "more than 1 characters in character constant");
4983 * Parse a wide character constant.
4985 static expression_t *parse_wide_character_constant(void)
4987 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4989 cnst->base.source_position = *HERE;
4990 cnst->base.type = token.datatype;
4991 cnst->conste.v.wide_character = token.v.wide_string;
4993 if (cnst->conste.v.wide_character.size != 1) {
4994 if (warning.multichar && (c_mode & _GNUC)) {
4996 warningf(HERE, "multi-character character constant");
4998 errorf(HERE, "more than 1 characters in character constant");
5007 * Parse a float constant.
5009 static expression_t *parse_float_const(void)
5011 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5012 cnst->base.type = token.datatype;
5013 cnst->conste.v.float_value = token.v.floatvalue;
5020 static declaration_t *create_implicit_function(symbol_t *symbol,
5021 const source_position_t *source_position)
5023 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5024 ntype->function.return_type = type_int;
5025 ntype->function.unspecified_parameters = true;
5027 type_t *type = typehash_insert(ntype);
5028 if (type != ntype) {
5032 declaration_t *const declaration = allocate_declaration_zero();
5033 declaration->storage_class = STORAGE_CLASS_EXTERN;
5034 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5035 declaration->type = type;
5036 declaration->symbol = symbol;
5037 declaration->source_position = *source_position;
5039 bool strict_prototypes_old = warning.strict_prototypes;
5040 warning.strict_prototypes = false;
5041 record_declaration(declaration);
5042 warning.strict_prototypes = strict_prototypes_old;
5048 * Creates a return_type (func)(argument_type) function type if not
5051 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5052 type_t *argument_type2)
5054 function_parameter_t *parameter2
5055 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5056 memset(parameter2, 0, sizeof(parameter2[0]));
5057 parameter2->type = argument_type2;
5059 function_parameter_t *parameter1
5060 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5061 memset(parameter1, 0, sizeof(parameter1[0]));
5062 parameter1->type = argument_type1;
5063 parameter1->next = parameter2;
5065 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5066 type->function.return_type = return_type;
5067 type->function.parameters = parameter1;
5069 type_t *result = typehash_insert(type);
5070 if (result != type) {
5078 * Creates a return_type (func)(argument_type) function type if not
5081 * @param return_type the return type
5082 * @param argument_type the argument type
5084 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5086 function_parameter_t *parameter
5087 = obstack_alloc(type_obst, sizeof(parameter[0]));
5088 memset(parameter, 0, sizeof(parameter[0]));
5089 parameter->type = argument_type;
5091 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5092 type->function.return_type = return_type;
5093 type->function.parameters = parameter;
5095 type_t *result = typehash_insert(type);
5096 if (result != type) {
5103 static type_t *make_function_0_type(type_t *return_type)
5105 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5106 type->function.return_type = return_type;
5107 type->function.parameters = NULL;
5109 type_t *result = typehash_insert(type);
5110 if (result != type) {
5118 * Creates a function type for some function like builtins.
5120 * @param symbol the symbol describing the builtin
5122 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5124 switch(symbol->ID) {
5125 case T___builtin_alloca:
5126 return make_function_1_type(type_void_ptr, type_size_t);
5127 case T___builtin_huge_val:
5128 return make_function_0_type(type_double);
5129 case T___builtin_nan:
5130 return make_function_1_type(type_double, type_char_ptr);
5131 case T___builtin_nanf:
5132 return make_function_1_type(type_float, type_char_ptr);
5133 case T___builtin_nand:
5134 return make_function_1_type(type_long_double, type_char_ptr);
5135 case T___builtin_va_end:
5136 return make_function_1_type(type_void, type_valist);
5137 case T___builtin_expect:
5138 return make_function_2_type(type_long, type_long, type_long);
5140 internal_errorf(HERE, "not implemented builtin symbol found");
5145 * Performs automatic type cast as described in § 6.3.2.1.
5147 * @param orig_type the original type
5149 static type_t *automatic_type_conversion(type_t *orig_type)
5151 type_t *type = skip_typeref(orig_type);
5152 if (is_type_array(type)) {
5153 array_type_t *array_type = &type->array;
5154 type_t *element_type = array_type->element_type;
5155 unsigned qualifiers = array_type->base.qualifiers;
5157 return make_pointer_type(element_type, qualifiers);
5160 if (is_type_function(type)) {
5161 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5168 * reverts the automatic casts of array to pointer types and function
5169 * to function-pointer types as defined § 6.3.2.1
5171 type_t *revert_automatic_type_conversion(const expression_t *expression)
5173 switch (expression->kind) {
5174 case EXPR_REFERENCE: return expression->reference.declaration->type;
5175 case EXPR_SELECT: return expression->select.compound_entry->type;
5177 case EXPR_UNARY_DEREFERENCE: {
5178 const expression_t *const value = expression->unary.value;
5179 type_t *const type = skip_typeref(value->base.type);
5180 assert(is_type_pointer(type));
5181 return type->pointer.points_to;
5184 case EXPR_BUILTIN_SYMBOL:
5185 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5187 case EXPR_ARRAY_ACCESS: {
5188 const expression_t *array_ref = expression->array_access.array_ref;
5189 type_t *type_left = skip_typeref(array_ref->base.type);
5190 if (!is_type_valid(type_left))
5192 assert(is_type_pointer(type_left));
5193 return type_left->pointer.points_to;
5196 case EXPR_STRING_LITERAL: {
5197 size_t size = expression->string.value.size;
5198 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5201 case EXPR_WIDE_STRING_LITERAL: {
5202 size_t size = expression->wide_string.value.size;
5203 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5206 case EXPR_COMPOUND_LITERAL:
5207 return expression->compound_literal.type;
5212 return expression->base.type;
5215 static expression_t *parse_reference(void)
5217 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5219 reference_expression_t *ref = &expression->reference;
5220 symbol_t *const symbol = token.v.symbol;
5222 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5224 source_position_t source_position = token.source_position;
5227 if (declaration == NULL) {
5228 if (! strict_mode && token.type == '(') {
5229 /* an implicitly defined function */
5230 if (warning.implicit_function_declaration) {
5231 warningf(HERE, "implicit declaration of function '%Y'",
5235 declaration = create_implicit_function(symbol,
5238 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5239 return create_invalid_expression();
5243 type_t *type = declaration->type;
5245 /* we always do the auto-type conversions; the & and sizeof parser contains
5246 * code to revert this! */
5247 type = automatic_type_conversion(type);
5249 ref->declaration = declaration;
5250 ref->base.type = type;
5252 /* this declaration is used */
5253 declaration->used = true;
5255 /* check for deprecated functions */
5256 if (declaration->deprecated != 0) {
5257 const char *prefix = "";
5258 if (is_type_function(declaration->type))
5259 prefix = "function ";
5261 if (declaration->deprecated_string != NULL) {
5262 warningf(&source_position,
5263 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5264 declaration->deprecated_string);
5266 warningf(&source_position,
5267 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5274 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5278 /* TODO check if explicit cast is allowed and issue warnings/errors */
5281 static expression_t *parse_compound_literal(type_t *type)
5283 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5285 parse_initializer_env_t env;
5287 env.declaration = NULL;
5288 env.must_be_constant = false;
5289 initializer_t *initializer = parse_initializer(&env);
5292 expression->compound_literal.initializer = initializer;
5293 expression->compound_literal.type = type;
5294 expression->base.type = automatic_type_conversion(type);
5300 * Parse a cast expression.
5302 static expression_t *parse_cast(void)
5304 source_position_t source_position = token.source_position;
5306 type_t *type = parse_typename();
5308 /* matching add_anchor_token() is at call site */
5309 rem_anchor_token(')');
5312 if (token.type == '{') {
5313 return parse_compound_literal(type);
5316 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5317 cast->base.source_position = source_position;
5319 expression_t *value = parse_sub_expression(20);
5321 check_cast_allowed(value, type);
5323 cast->base.type = type;
5324 cast->unary.value = value;
5328 return create_invalid_expression();
5332 * Parse a statement expression.
5334 static expression_t *parse_statement_expression(void)
5336 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5338 statement_t *statement = parse_compound_statement(true);
5339 expression->statement.statement = statement;
5340 expression->base.source_position = statement->base.source_position;
5342 /* find last statement and use its type */
5343 type_t *type = type_void;
5344 const statement_t *stmt = statement->compound.statements;
5346 while (stmt->base.next != NULL)
5347 stmt = stmt->base.next;
5349 if (stmt->kind == STATEMENT_EXPRESSION) {
5350 type = stmt->expression.expression->base.type;
5353 warningf(&expression->base.source_position, "empty statement expression ({})");
5355 expression->base.type = type;
5361 return create_invalid_expression();
5365 * Parse a braced expression.
5367 static expression_t *parse_brace_expression(void)
5370 add_anchor_token(')');
5372 switch(token.type) {
5374 /* gcc extension: a statement expression */
5375 return parse_statement_expression();
5379 return parse_cast();
5381 if (is_typedef_symbol(token.v.symbol)) {
5382 return parse_cast();
5386 expression_t *result = parse_expression();
5387 rem_anchor_token(')');
5392 return create_invalid_expression();
5395 static expression_t *parse_function_keyword(void)
5400 if (current_function == NULL) {
5401 errorf(HERE, "'__func__' used outside of a function");
5404 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5405 expression->base.type = type_char_ptr;
5406 expression->funcname.kind = FUNCNAME_FUNCTION;
5411 static expression_t *parse_pretty_function_keyword(void)
5413 eat(T___PRETTY_FUNCTION__);
5415 if (current_function == NULL) {
5416 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5419 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5420 expression->base.type = type_char_ptr;
5421 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5426 static expression_t *parse_funcsig_keyword(void)
5430 if (current_function == NULL) {
5431 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5434 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5435 expression->base.type = type_char_ptr;
5436 expression->funcname.kind = FUNCNAME_FUNCSIG;
5441 static expression_t *parse_funcdname_keyword(void)
5443 eat(T___FUNCDNAME__);
5445 if (current_function == NULL) {
5446 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5449 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5450 expression->base.type = type_char_ptr;
5451 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5456 static designator_t *parse_designator(void)
5458 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5459 result->source_position = *HERE;
5461 if (token.type != T_IDENTIFIER) {
5462 parse_error_expected("while parsing member designator",
5463 T_IDENTIFIER, NULL);
5466 result->symbol = token.v.symbol;
5469 designator_t *last_designator = result;
5471 if (token.type == '.') {
5473 if (token.type != T_IDENTIFIER) {
5474 parse_error_expected("while parsing member designator",
5475 T_IDENTIFIER, NULL);
5478 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5479 designator->source_position = *HERE;
5480 designator->symbol = token.v.symbol;
5483 last_designator->next = designator;
5484 last_designator = designator;
5487 if (token.type == '[') {
5489 add_anchor_token(']');
5490 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5491 designator->source_position = *HERE;
5492 designator->array_index = parse_expression();
5493 rem_anchor_token(']');
5495 if (designator->array_index == NULL) {
5499 last_designator->next = designator;
5500 last_designator = designator;
5512 * Parse the __builtin_offsetof() expression.
5514 static expression_t *parse_offsetof(void)
5516 eat(T___builtin_offsetof);
5518 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5519 expression->base.type = type_size_t;
5522 add_anchor_token(',');
5523 type_t *type = parse_typename();
5524 rem_anchor_token(',');
5526 add_anchor_token(')');
5527 designator_t *designator = parse_designator();
5528 rem_anchor_token(')');
5531 expression->offsetofe.type = type;
5532 expression->offsetofe.designator = designator;
5535 memset(&path, 0, sizeof(path));
5536 path.top_type = type;
5537 path.path = NEW_ARR_F(type_path_entry_t, 0);
5539 descend_into_subtype(&path);
5541 if (!walk_designator(&path, designator, true)) {
5542 return create_invalid_expression();
5545 DEL_ARR_F(path.path);
5549 return create_invalid_expression();
5553 * Parses a _builtin_va_start() expression.
5555 static expression_t *parse_va_start(void)
5557 eat(T___builtin_va_start);
5559 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5562 add_anchor_token(',');
5563 expression->va_starte.ap = parse_assignment_expression();
5564 rem_anchor_token(',');
5566 expression_t *const expr = parse_assignment_expression();
5567 if (expr->kind == EXPR_REFERENCE) {
5568 declaration_t *const decl = expr->reference.declaration;
5570 return create_invalid_expression();
5571 if (decl->parent_scope == ¤t_function->scope &&
5572 decl->next == NULL) {
5573 expression->va_starte.parameter = decl;
5578 errorf(&expr->base.source_position,
5579 "second argument of 'va_start' must be last parameter of the current function");
5581 return create_invalid_expression();
5585 * Parses a _builtin_va_arg() expression.
5587 static expression_t *parse_va_arg(void)
5589 eat(T___builtin_va_arg);
5591 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5594 expression->va_arge.ap = parse_assignment_expression();
5596 expression->base.type = parse_typename();
5601 return create_invalid_expression();
5604 static expression_t *parse_builtin_symbol(void)
5606 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5608 symbol_t *symbol = token.v.symbol;
5610 expression->builtin_symbol.symbol = symbol;
5613 type_t *type = get_builtin_symbol_type(symbol);
5614 type = automatic_type_conversion(type);
5616 expression->base.type = type;
5621 * Parses a __builtin_constant() expression.
5623 static expression_t *parse_builtin_constant(void)
5625 eat(T___builtin_constant_p);
5627 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5630 add_anchor_token(')');
5631 expression->builtin_constant.value = parse_assignment_expression();
5632 rem_anchor_token(')');
5634 expression->base.type = type_int;
5638 return create_invalid_expression();
5642 * Parses a __builtin_prefetch() expression.
5644 static expression_t *parse_builtin_prefetch(void)
5646 eat(T___builtin_prefetch);
5648 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5651 add_anchor_token(')');
5652 expression->builtin_prefetch.adr = parse_assignment_expression();
5653 if (token.type == ',') {
5655 expression->builtin_prefetch.rw = parse_assignment_expression();
5657 if (token.type == ',') {
5659 expression->builtin_prefetch.locality = parse_assignment_expression();
5661 rem_anchor_token(')');
5663 expression->base.type = type_void;
5667 return create_invalid_expression();
5671 * Parses a __builtin_is_*() compare expression.
5673 static expression_t *parse_compare_builtin(void)
5675 expression_t *expression;
5677 switch(token.type) {
5678 case T___builtin_isgreater:
5679 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5681 case T___builtin_isgreaterequal:
5682 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5684 case T___builtin_isless:
5685 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5687 case T___builtin_islessequal:
5688 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5690 case T___builtin_islessgreater:
5691 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5693 case T___builtin_isunordered:
5694 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5697 internal_errorf(HERE, "invalid compare builtin found");
5700 expression->base.source_position = *HERE;
5704 expression->binary.left = parse_assignment_expression();
5706 expression->binary.right = parse_assignment_expression();
5709 type_t *const orig_type_left = expression->binary.left->base.type;
5710 type_t *const orig_type_right = expression->binary.right->base.type;
5712 type_t *const type_left = skip_typeref(orig_type_left);
5713 type_t *const type_right = skip_typeref(orig_type_right);
5714 if (!is_type_float(type_left) && !is_type_float(type_right)) {
5715 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5716 type_error_incompatible("invalid operands in comparison",
5717 &expression->base.source_position, orig_type_left, orig_type_right);
5720 semantic_comparison(&expression->binary);
5725 return create_invalid_expression();
5730 * Parses a __builtin_expect() expression.
5732 static expression_t *parse_builtin_expect(void)
5734 eat(T___builtin_expect);
5736 expression_t *expression
5737 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5740 expression->binary.left = parse_assignment_expression();
5742 expression->binary.right = parse_constant_expression();
5745 expression->base.type = expression->binary.left->base.type;
5749 return create_invalid_expression();
5754 * Parses a MS assume() expression.
5756 static expression_t *parse_assume(void) {
5759 expression_t *expression
5760 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5763 add_anchor_token(')');
5764 expression->unary.value = parse_assignment_expression();
5765 rem_anchor_token(')');
5768 expression->base.type = type_void;
5771 return create_invalid_expression();
5775 * Parse a microsoft __noop expression.
5777 static expression_t *parse_noop_expression(void) {
5778 source_position_t source_position = *HERE;
5781 if (token.type == '(') {
5782 /* parse arguments */
5784 add_anchor_token(')');
5785 add_anchor_token(',');
5787 if (token.type != ')') {
5789 (void)parse_assignment_expression();
5790 if (token.type != ',')
5796 rem_anchor_token(',');
5797 rem_anchor_token(')');
5800 /* the result is a (int)0 */
5801 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5802 cnst->base.source_position = source_position;
5803 cnst->base.type = type_int;
5804 cnst->conste.v.int_value = 0;
5805 cnst->conste.is_ms_noop = true;
5810 return create_invalid_expression();
5814 * Parses a primary expression.
5816 static expression_t *parse_primary_expression(void)
5818 switch (token.type) {
5819 case T_INTEGER: return parse_int_const();
5820 case T_CHARACTER_CONSTANT: return parse_character_constant();
5821 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5822 case T_FLOATINGPOINT: return parse_float_const();
5823 case T_STRING_LITERAL:
5824 case T_WIDE_STRING_LITERAL: return parse_string_const();
5825 case T_IDENTIFIER: return parse_reference();
5826 case T___FUNCTION__:
5827 case T___func__: return parse_function_keyword();
5828 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5829 case T___FUNCSIG__: return parse_funcsig_keyword();
5830 case T___FUNCDNAME__: return parse_funcdname_keyword();
5831 case T___builtin_offsetof: return parse_offsetof();
5832 case T___builtin_va_start: return parse_va_start();
5833 case T___builtin_va_arg: return parse_va_arg();
5834 case T___builtin_expect:
5835 case T___builtin_alloca:
5836 case T___builtin_nan:
5837 case T___builtin_nand:
5838 case T___builtin_nanf:
5839 case T___builtin_huge_val:
5840 case T___builtin_va_end: return parse_builtin_symbol();
5841 case T___builtin_isgreater:
5842 case T___builtin_isgreaterequal:
5843 case T___builtin_isless:
5844 case T___builtin_islessequal:
5845 case T___builtin_islessgreater:
5846 case T___builtin_isunordered: return parse_compare_builtin();
5847 case T___builtin_constant_p: return parse_builtin_constant();
5848 case T___builtin_prefetch: return parse_builtin_prefetch();
5849 case T__assume: return parse_assume();
5851 case '(': return parse_brace_expression();
5852 case T___noop: return parse_noop_expression();
5855 errorf(HERE, "unexpected token %K, expected an expression", &token);
5856 return create_invalid_expression();
5860 * Check if the expression has the character type and issue a warning then.
5862 static void check_for_char_index_type(const expression_t *expression) {
5863 type_t *const type = expression->base.type;
5864 const type_t *const base_type = skip_typeref(type);
5866 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5867 warning.char_subscripts) {
5868 warningf(&expression->base.source_position,
5869 "array subscript has type '%T'", type);
5873 static expression_t *parse_array_expression(unsigned precedence,
5879 add_anchor_token(']');
5881 expression_t *inside = parse_expression();
5883 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5885 array_access_expression_t *array_access = &expression->array_access;
5887 type_t *const orig_type_left = left->base.type;
5888 type_t *const orig_type_inside = inside->base.type;
5890 type_t *const type_left = skip_typeref(orig_type_left);
5891 type_t *const type_inside = skip_typeref(orig_type_inside);
5893 type_t *return_type;
5894 if (is_type_pointer(type_left)) {
5895 return_type = type_left->pointer.points_to;
5896 array_access->array_ref = left;
5897 array_access->index = inside;
5898 check_for_char_index_type(inside);
5899 } else if (is_type_pointer(type_inside)) {
5900 return_type = type_inside->pointer.points_to;
5901 array_access->array_ref = inside;
5902 array_access->index = left;
5903 array_access->flipped = true;
5904 check_for_char_index_type(left);
5906 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5908 "array access on object with non-pointer types '%T', '%T'",
5909 orig_type_left, orig_type_inside);
5911 return_type = type_error_type;
5912 array_access->array_ref = create_invalid_expression();
5915 rem_anchor_token(']');
5916 if (token.type != ']') {
5917 parse_error_expected("Problem while parsing array access", ']', NULL);
5922 return_type = automatic_type_conversion(return_type);
5923 expression->base.type = return_type;
5928 static expression_t *parse_typeprop(expression_kind_t const kind,
5929 source_position_t const pos,
5930 unsigned const precedence)
5932 expression_t *tp_expression = allocate_expression_zero(kind);
5933 tp_expression->base.type = type_size_t;
5934 tp_expression->base.source_position = pos;
5936 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5938 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5940 add_anchor_token(')');
5941 type_t* const orig_type = parse_typename();
5942 tp_expression->typeprop.type = orig_type;
5944 type_t const* const type = skip_typeref(orig_type);
5945 char const* const wrong_type =
5946 is_type_incomplete(type) ? "incomplete" :
5947 type->kind == TYPE_FUNCTION ? "function designator" :
5948 type->kind == TYPE_BITFIELD ? "bitfield" :
5950 if (wrong_type != NULL) {
5951 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5952 what, wrong_type, type);
5955 rem_anchor_token(')');
5958 expression_t *expression = parse_sub_expression(precedence);
5960 type_t* const orig_type = revert_automatic_type_conversion(expression);
5961 expression->base.type = orig_type;
5963 type_t const* const type = skip_typeref(orig_type);
5964 char const* const wrong_type =
5965 is_type_incomplete(type) ? "incomplete" :
5966 type->kind == TYPE_FUNCTION ? "function designator" :
5967 type->kind == TYPE_BITFIELD ? "bitfield" :
5969 if (wrong_type != NULL) {
5970 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5973 tp_expression->typeprop.type = expression->base.type;
5974 tp_expression->typeprop.tp_expression = expression;
5977 return tp_expression;
5979 return create_invalid_expression();
5982 static expression_t *parse_sizeof(unsigned precedence)
5984 source_position_t pos = *HERE;
5986 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5989 static expression_t *parse_alignof(unsigned precedence)
5991 source_position_t pos = *HERE;
5993 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5996 static expression_t *parse_select_expression(unsigned precedence,
5997 expression_t *compound)
6000 assert(token.type == '.' || token.type == T_MINUSGREATER);
6002 bool is_pointer = (token.type == T_MINUSGREATER);
6005 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6006 select->select.compound = compound;
6008 if (token.type != T_IDENTIFIER) {
6009 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6012 symbol_t *symbol = token.v.symbol;
6013 select->select.symbol = symbol;
6016 type_t *const orig_type = compound->base.type;
6017 type_t *const type = skip_typeref(orig_type);
6019 type_t *type_left = type;
6021 if (!is_type_pointer(type)) {
6022 if (is_type_valid(type)) {
6023 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6025 return create_invalid_expression();
6027 type_left = type->pointer.points_to;
6029 type_left = skip_typeref(type_left);
6031 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6032 type_left->kind != TYPE_COMPOUND_UNION) {
6033 if (is_type_valid(type_left)) {
6034 errorf(HERE, "request for member '%Y' in something not a struct or "
6035 "union, but '%T'", symbol, type_left);
6037 return create_invalid_expression();
6040 declaration_t *const declaration = type_left->compound.declaration;
6042 if (!declaration->init.complete) {
6043 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6045 return create_invalid_expression();
6048 declaration_t *iter = find_compound_entry(declaration, symbol);
6050 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6051 return create_invalid_expression();
6054 /* we always do the auto-type conversions; the & and sizeof parser contains
6055 * code to revert this! */
6056 type_t *expression_type = automatic_type_conversion(iter->type);
6058 select->select.compound_entry = iter;
6059 select->base.type = expression_type;
6061 type_t *skipped = skip_typeref(iter->type);
6062 if (skipped->kind == TYPE_BITFIELD) {
6063 select->base.type = skipped->bitfield.base_type;
6069 static void check_call_argument(const function_parameter_t *parameter,
6070 call_argument_t *argument)
6072 type_t *expected_type = parameter->type;
6073 type_t *expected_type_skip = skip_typeref(expected_type);
6074 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6075 expression_t *arg_expr = argument->expression;
6077 /* handle transparent union gnu extension */
6078 if (is_type_union(expected_type_skip)
6079 && (expected_type_skip->base.modifiers
6080 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6081 declaration_t *union_decl = expected_type_skip->compound.declaration;
6083 declaration_t *declaration = union_decl->scope.declarations;
6084 type_t *best_type = NULL;
6085 for ( ; declaration != NULL; declaration = declaration->next) {
6086 type_t *decl_type = declaration->type;
6087 error = semantic_assign(decl_type, arg_expr);
6088 if (error == ASSIGN_ERROR_INCOMPATIBLE
6089 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6092 if (error == ASSIGN_SUCCESS) {
6093 best_type = decl_type;
6094 } else if (best_type == NULL) {
6095 best_type = decl_type;
6099 if (best_type != NULL) {
6100 expected_type = best_type;
6104 error = semantic_assign(expected_type, arg_expr);
6105 argument->expression = create_implicit_cast(argument->expression,
6108 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6109 report_assign_error(error, expected_type, arg_expr, "function call",
6110 &arg_expr->base.source_position);
6114 * Parse a call expression, ie. expression '( ... )'.
6116 * @param expression the function address
6118 static expression_t *parse_call_expression(unsigned precedence,
6119 expression_t *expression)
6122 expression_t *result = allocate_expression_zero(EXPR_CALL);
6123 result->base.source_position = expression->base.source_position;
6125 call_expression_t *call = &result->call;
6126 call->function = expression;
6128 type_t *const orig_type = expression->base.type;
6129 type_t *const type = skip_typeref(orig_type);
6131 function_type_t *function_type = NULL;
6132 if (is_type_pointer(type)) {
6133 type_t *const to_type = skip_typeref(type->pointer.points_to);
6135 if (is_type_function(to_type)) {
6136 function_type = &to_type->function;
6137 call->base.type = function_type->return_type;
6141 if (function_type == NULL && is_type_valid(type)) {
6142 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6145 /* parse arguments */
6147 add_anchor_token(')');
6148 add_anchor_token(',');
6150 if (token.type != ')') {
6151 call_argument_t *last_argument = NULL;
6154 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6156 argument->expression = parse_assignment_expression();
6157 if (last_argument == NULL) {
6158 call->arguments = argument;
6160 last_argument->next = argument;
6162 last_argument = argument;
6164 if (token.type != ',')
6169 rem_anchor_token(',');
6170 rem_anchor_token(')');
6173 if (function_type == NULL)
6176 function_parameter_t *parameter = function_type->parameters;
6177 call_argument_t *argument = call->arguments;
6178 if (!function_type->unspecified_parameters) {
6179 for( ; parameter != NULL && argument != NULL;
6180 parameter = parameter->next, argument = argument->next) {
6181 check_call_argument(parameter, argument);
6184 if (parameter != NULL) {
6185 errorf(HERE, "too few arguments to function '%E'", expression);
6186 } else if (argument != NULL && !function_type->variadic) {
6187 errorf(HERE, "too many arguments to function '%E'", expression);
6191 /* do default promotion */
6192 for( ; argument != NULL; argument = argument->next) {
6193 type_t *type = argument->expression->base.type;
6195 type = get_default_promoted_type(type);
6197 argument->expression
6198 = create_implicit_cast(argument->expression, type);
6201 check_format(&result->call);
6205 return create_invalid_expression();
6208 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6210 static bool same_compound_type(const type_t *type1, const type_t *type2)
6213 is_type_compound(type1) &&
6214 type1->kind == type2->kind &&
6215 type1->compound.declaration == type2->compound.declaration;
6219 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6221 * @param expression the conditional expression
6223 static expression_t *parse_conditional_expression(unsigned precedence,
6224 expression_t *expression)
6227 add_anchor_token(':');
6229 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6231 conditional_expression_t *conditional = &result->conditional;
6232 conditional->condition = expression;
6235 type_t *const condition_type_orig = expression->base.type;
6236 type_t *const condition_type = skip_typeref(condition_type_orig);
6237 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6238 type_error("expected a scalar type in conditional condition",
6239 &expression->base.source_position, condition_type_orig);
6242 expression_t *true_expression = parse_expression();
6243 rem_anchor_token(':');
6245 expression_t *false_expression = parse_sub_expression(precedence);
6247 type_t *const orig_true_type = true_expression->base.type;
6248 type_t *const orig_false_type = false_expression->base.type;
6249 type_t *const true_type = skip_typeref(orig_true_type);
6250 type_t *const false_type = skip_typeref(orig_false_type);
6253 type_t *result_type;
6254 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6255 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6256 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6257 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6258 warningf(&expression->base.source_position,
6259 "ISO C forbids conditional expression with only one void side");
6261 result_type = type_void;
6262 } else if (is_type_arithmetic(true_type)
6263 && is_type_arithmetic(false_type)) {
6264 result_type = semantic_arithmetic(true_type, false_type);
6266 true_expression = create_implicit_cast(true_expression, result_type);
6267 false_expression = create_implicit_cast(false_expression, result_type);
6269 conditional->true_expression = true_expression;
6270 conditional->false_expression = false_expression;
6271 conditional->base.type = result_type;
6272 } else if (same_compound_type(true_type, false_type)) {
6273 /* just take 1 of the 2 types */
6274 result_type = true_type;
6275 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6276 type_t *pointer_type;
6278 expression_t *other_expression;
6279 if (is_type_pointer(true_type) &&
6280 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6281 pointer_type = true_type;
6282 other_type = false_type;
6283 other_expression = false_expression;
6285 pointer_type = false_type;
6286 other_type = true_type;
6287 other_expression = true_expression;
6290 if (is_null_pointer_constant(other_expression)) {
6291 result_type = pointer_type;
6292 } else if (is_type_pointer(other_type)) {
6293 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6294 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6297 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6298 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6300 } else if (types_compatible(get_unqualified_type(to1),
6301 get_unqualified_type(to2))) {
6304 warningf(&expression->base.source_position,
6305 "pointer types '%T' and '%T' in conditional expression are incompatible",
6306 true_type, false_type);
6310 type_t *const copy = duplicate_type(to);
6311 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6313 type_t *const type = typehash_insert(copy);
6317 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6318 } else if (is_type_integer(other_type)) {
6319 warningf(&expression->base.source_position,
6320 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6321 result_type = pointer_type;
6323 type_error_incompatible("while parsing conditional",
6324 &expression->base.source_position, true_type, false_type);
6325 result_type = type_error_type;
6328 /* TODO: one pointer to void*, other some pointer */
6330 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6331 type_error_incompatible("while parsing conditional",
6332 &expression->base.source_position, true_type,
6335 result_type = type_error_type;
6338 conditional->true_expression
6339 = create_implicit_cast(true_expression, result_type);
6340 conditional->false_expression
6341 = create_implicit_cast(false_expression, result_type);
6342 conditional->base.type = result_type;
6345 return create_invalid_expression();
6349 * Parse an extension expression.
6351 static expression_t *parse_extension(unsigned precedence)
6353 eat(T___extension__);
6355 /* TODO enable extensions */
6356 expression_t *expression = parse_sub_expression(precedence);
6357 /* TODO disable extensions */
6362 * Parse a __builtin_classify_type() expression.
6364 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6366 eat(T___builtin_classify_type);
6368 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6369 result->base.type = type_int;
6372 add_anchor_token(')');
6373 expression_t *expression = parse_sub_expression(precedence);
6374 rem_anchor_token(')');
6376 result->classify_type.type_expression = expression;
6380 return create_invalid_expression();
6383 static void check_pointer_arithmetic(const source_position_t *source_position,
6384 type_t *pointer_type,
6385 type_t *orig_pointer_type)
6387 type_t *points_to = pointer_type->pointer.points_to;
6388 points_to = skip_typeref(points_to);
6390 if (is_type_incomplete(points_to) &&
6392 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6393 errorf(source_position,
6394 "arithmetic with pointer to incomplete type '%T' not allowed",
6396 } else if (is_type_function(points_to)) {
6397 errorf(source_position,
6398 "arithmetic with pointer to function type '%T' not allowed",
6403 static void semantic_incdec(unary_expression_t *expression)
6405 type_t *const orig_type = expression->value->base.type;
6406 type_t *const type = skip_typeref(orig_type);
6407 if (is_type_pointer(type)) {
6408 check_pointer_arithmetic(&expression->base.source_position,
6410 } else if (!is_type_real(type) && is_type_valid(type)) {
6411 /* TODO: improve error message */
6412 errorf(HERE, "operation needs an arithmetic or pointer type");
6414 expression->base.type = orig_type;
6417 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6419 type_t *const orig_type = expression->value->base.type;
6420 type_t *const type = skip_typeref(orig_type);
6421 if (!is_type_arithmetic(type)) {
6422 if (is_type_valid(type)) {
6423 /* TODO: improve error message */
6424 errorf(HERE, "operation needs an arithmetic type");
6429 expression->base.type = orig_type;
6432 static void semantic_unexpr_scalar(unary_expression_t *expression)
6434 type_t *const orig_type = expression->value->base.type;
6435 type_t *const type = skip_typeref(orig_type);
6436 if (!is_type_scalar(type)) {
6437 if (is_type_valid(type)) {
6438 errorf(HERE, "operand of ! must be of scalar type");
6443 expression->base.type = orig_type;
6446 static void semantic_unexpr_integer(unary_expression_t *expression)
6448 type_t *const orig_type = expression->value->base.type;
6449 type_t *const type = skip_typeref(orig_type);
6450 if (!is_type_integer(type)) {
6451 if (is_type_valid(type)) {
6452 errorf(HERE, "operand of ~ must be of integer type");
6457 expression->base.type = orig_type;
6460 static void semantic_dereference(unary_expression_t *expression)
6462 type_t *const orig_type = expression->value->base.type;
6463 type_t *const type = skip_typeref(orig_type);
6464 if (!is_type_pointer(type)) {
6465 if (is_type_valid(type)) {
6466 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6471 type_t *result_type = type->pointer.points_to;
6472 result_type = automatic_type_conversion(result_type);
6473 expression->base.type = result_type;
6476 static void set_address_taken(expression_t *expression, bool may_be_register)
6478 if (expression->kind != EXPR_REFERENCE)
6481 declaration_t *const declaration = expression->reference.declaration;
6482 /* happens for parse errors */
6483 if (declaration == NULL)
6486 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6487 errorf(&expression->base.source_position,
6488 "address of register variable '%Y' requested",
6489 declaration->symbol);
6491 declaration->address_taken = 1;
6496 * Check the semantic of the address taken expression.
6498 static void semantic_take_addr(unary_expression_t *expression)
6500 expression_t *value = expression->value;
6501 value->base.type = revert_automatic_type_conversion(value);
6503 type_t *orig_type = value->base.type;
6504 if (!is_type_valid(orig_type))
6507 set_address_taken(value, false);
6509 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6512 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6513 static expression_t *parse_##unexpression_type(unsigned precedence) \
6517 expression_t *unary_expression \
6518 = allocate_expression_zero(unexpression_type); \
6519 unary_expression->base.source_position = *HERE; \
6520 unary_expression->unary.value = parse_sub_expression(precedence); \
6522 sfunc(&unary_expression->unary); \
6524 return unary_expression; \
6527 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6528 semantic_unexpr_arithmetic)
6529 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6530 semantic_unexpr_arithmetic)
6531 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6532 semantic_unexpr_scalar)
6533 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6534 semantic_dereference)
6535 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6537 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6538 semantic_unexpr_integer)
6539 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6541 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6544 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6546 static expression_t *parse_##unexpression_type(unsigned precedence, \
6547 expression_t *left) \
6549 (void) precedence; \
6552 expression_t *unary_expression \
6553 = allocate_expression_zero(unexpression_type); \
6554 unary_expression->unary.value = left; \
6556 sfunc(&unary_expression->unary); \
6558 return unary_expression; \
6561 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6562 EXPR_UNARY_POSTFIX_INCREMENT,
6564 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6565 EXPR_UNARY_POSTFIX_DECREMENT,
6568 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6570 /* TODO: handle complex + imaginary types */
6572 /* § 6.3.1.8 Usual arithmetic conversions */
6573 if (type_left == type_long_double || type_right == type_long_double) {
6574 return type_long_double;
6575 } else if (type_left == type_double || type_right == type_double) {
6577 } else if (type_left == type_float || type_right == type_float) {
6581 type_right = promote_integer(type_right);
6582 type_left = promote_integer(type_left);
6584 if (type_left == type_right)
6587 bool signed_left = is_type_signed(type_left);
6588 bool signed_right = is_type_signed(type_right);
6589 int rank_left = get_rank(type_left);
6590 int rank_right = get_rank(type_right);
6591 if (rank_left < rank_right) {
6592 if (signed_left == signed_right || !signed_right) {
6598 if (signed_left == signed_right || !signed_left) {
6607 * Check the semantic restrictions for a binary expression.
6609 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6611 expression_t *const left = expression->left;
6612 expression_t *const right = expression->right;
6613 type_t *const orig_type_left = left->base.type;
6614 type_t *const orig_type_right = right->base.type;
6615 type_t *const type_left = skip_typeref(orig_type_left);
6616 type_t *const type_right = skip_typeref(orig_type_right);
6618 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6619 /* TODO: improve error message */
6620 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6621 errorf(HERE, "operation needs arithmetic types");
6626 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6627 expression->left = create_implicit_cast(left, arithmetic_type);
6628 expression->right = create_implicit_cast(right, arithmetic_type);
6629 expression->base.type = arithmetic_type;
6632 static void semantic_shift_op(binary_expression_t *expression)
6634 expression_t *const left = expression->left;
6635 expression_t *const right = expression->right;
6636 type_t *const orig_type_left = left->base.type;
6637 type_t *const orig_type_right = right->base.type;
6638 type_t * type_left = skip_typeref(orig_type_left);
6639 type_t * type_right = skip_typeref(orig_type_right);
6641 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6642 /* TODO: improve error message */
6643 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6644 errorf(HERE, "operation needs integer types");
6649 type_left = promote_integer(type_left);
6650 type_right = promote_integer(type_right);
6652 expression->left = create_implicit_cast(left, type_left);
6653 expression->right = create_implicit_cast(right, type_right);
6654 expression->base.type = type_left;
6657 static void semantic_add(binary_expression_t *expression)
6659 expression_t *const left = expression->left;
6660 expression_t *const right = expression->right;
6661 type_t *const orig_type_left = left->base.type;
6662 type_t *const orig_type_right = right->base.type;
6663 type_t *const type_left = skip_typeref(orig_type_left);
6664 type_t *const type_right = skip_typeref(orig_type_right);
6667 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6668 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6669 expression->left = create_implicit_cast(left, arithmetic_type);
6670 expression->right = create_implicit_cast(right, arithmetic_type);
6671 expression->base.type = arithmetic_type;
6673 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6674 check_pointer_arithmetic(&expression->base.source_position,
6675 type_left, orig_type_left);
6676 expression->base.type = type_left;
6677 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6678 check_pointer_arithmetic(&expression->base.source_position,
6679 type_right, orig_type_right);
6680 expression->base.type = type_right;
6681 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6682 errorf(&expression->base.source_position,
6683 "invalid operands to binary + ('%T', '%T')",
6684 orig_type_left, orig_type_right);
6688 static void semantic_sub(binary_expression_t *expression)
6690 expression_t *const left = expression->left;
6691 expression_t *const right = expression->right;
6692 type_t *const orig_type_left = left->base.type;
6693 type_t *const orig_type_right = right->base.type;
6694 type_t *const type_left = skip_typeref(orig_type_left);
6695 type_t *const type_right = skip_typeref(orig_type_right);
6698 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6699 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6700 expression->left = create_implicit_cast(left, arithmetic_type);
6701 expression->right = create_implicit_cast(right, arithmetic_type);
6702 expression->base.type = arithmetic_type;
6704 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6705 check_pointer_arithmetic(&expression->base.source_position,
6706 type_left, orig_type_left);
6707 expression->base.type = type_left;
6708 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6709 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6710 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6711 if (!types_compatible(unqual_left, unqual_right)) {
6712 errorf(&expression->base.source_position,
6713 "subtracting pointers to incompatible types '%T' and '%T'",
6714 orig_type_left, orig_type_right);
6715 } else if (!is_type_object(unqual_left)) {
6716 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6717 warningf(&expression->base.source_position,
6718 "subtracting pointers to void");
6720 errorf(&expression->base.source_position,
6721 "subtracting pointers to non-object types '%T'",
6725 expression->base.type = type_ptrdiff_t;
6726 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6727 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6728 orig_type_left, orig_type_right);
6733 * Check the semantics of comparison expressions.
6735 * @param expression The expression to check.
6737 static void semantic_comparison(binary_expression_t *expression)
6739 expression_t *left = expression->left;
6740 expression_t *right = expression->right;
6741 type_t *orig_type_left = left->base.type;
6742 type_t *orig_type_right = right->base.type;
6744 type_t *type_left = skip_typeref(orig_type_left);
6745 type_t *type_right = skip_typeref(orig_type_right);
6747 /* TODO non-arithmetic types */
6748 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6749 /* test for signed vs unsigned compares */
6750 if (warning.sign_compare &&
6751 (expression->base.kind != EXPR_BINARY_EQUAL &&
6752 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6753 (is_type_signed(type_left) != is_type_signed(type_right))) {
6755 /* check if 1 of the operands is a constant, in this case we just
6756 * check wether we can safely represent the resulting constant in
6757 * the type of the other operand. */
6758 expression_t *const_expr = NULL;
6759 expression_t *other_expr = NULL;
6761 if (is_constant_expression(left)) {
6764 } else if (is_constant_expression(right)) {
6769 if (const_expr != NULL) {
6770 type_t *other_type = skip_typeref(other_expr->base.type);
6771 long val = fold_constant(const_expr);
6772 /* TODO: check if val can be represented by other_type */
6776 warningf(&expression->base.source_position,
6777 "comparison between signed and unsigned");
6779 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6780 expression->left = create_implicit_cast(left, arithmetic_type);
6781 expression->right = create_implicit_cast(right, arithmetic_type);
6782 expression->base.type = arithmetic_type;
6783 if (warning.float_equal &&
6784 (expression->base.kind == EXPR_BINARY_EQUAL ||
6785 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6786 is_type_float(arithmetic_type)) {
6787 warningf(&expression->base.source_position,
6788 "comparing floating point with == or != is unsafe");
6790 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6791 /* TODO check compatibility */
6792 } else if (is_type_pointer(type_left)) {
6793 expression->right = create_implicit_cast(right, type_left);
6794 } else if (is_type_pointer(type_right)) {
6795 expression->left = create_implicit_cast(left, type_right);
6796 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6797 type_error_incompatible("invalid operands in comparison",
6798 &expression->base.source_position,
6799 type_left, type_right);
6801 expression->base.type = type_int;
6805 * Checks if a compound type has constant fields.
6807 static bool has_const_fields(const compound_type_t *type)
6809 const scope_t *scope = &type->declaration->scope;
6810 const declaration_t *declaration = scope->declarations;
6812 for (; declaration != NULL; declaration = declaration->next) {
6813 if (declaration->namespc != NAMESPACE_NORMAL)
6816 const type_t *decl_type = skip_typeref(declaration->type);
6817 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6824 static bool is_lvalue(const expression_t *expression)
6826 switch (expression->kind) {
6827 case EXPR_REFERENCE:
6828 case EXPR_ARRAY_ACCESS:
6830 case EXPR_UNARY_DEREFERENCE:
6838 static bool is_valid_assignment_lhs(expression_t const* const left)
6840 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6841 type_t *const type_left = skip_typeref(orig_type_left);
6843 if (!is_lvalue(left)) {
6844 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6849 if (is_type_array(type_left)) {
6850 errorf(HERE, "cannot assign to arrays ('%E')", left);
6853 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6854 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6858 if (is_type_incomplete(type_left)) {
6859 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6860 left, orig_type_left);
6863 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6864 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6865 left, orig_type_left);
6872 static void semantic_arithmetic_assign(binary_expression_t *expression)
6874 expression_t *left = expression->left;
6875 expression_t *right = expression->right;
6876 type_t *orig_type_left = left->base.type;
6877 type_t *orig_type_right = right->base.type;
6879 if (!is_valid_assignment_lhs(left))
6882 type_t *type_left = skip_typeref(orig_type_left);
6883 type_t *type_right = skip_typeref(orig_type_right);
6885 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6886 /* TODO: improve error message */
6887 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6888 errorf(HERE, "operation needs arithmetic types");
6893 /* combined instructions are tricky. We can't create an implicit cast on
6894 * the left side, because we need the uncasted form for the store.
6895 * The ast2firm pass has to know that left_type must be right_type
6896 * for the arithmetic operation and create a cast by itself */
6897 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6898 expression->right = create_implicit_cast(right, arithmetic_type);
6899 expression->base.type = type_left;
6902 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6904 expression_t *const left = expression->left;
6905 expression_t *const right = expression->right;
6906 type_t *const orig_type_left = left->base.type;
6907 type_t *const orig_type_right = right->base.type;
6908 type_t *const type_left = skip_typeref(orig_type_left);
6909 type_t *const type_right = skip_typeref(orig_type_right);
6911 if (!is_valid_assignment_lhs(left))
6914 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6915 /* combined instructions are tricky. We can't create an implicit cast on
6916 * the left side, because we need the uncasted form for the store.
6917 * The ast2firm pass has to know that left_type must be right_type
6918 * for the arithmetic operation and create a cast by itself */
6919 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6920 expression->right = create_implicit_cast(right, arithmetic_type);
6921 expression->base.type = type_left;
6922 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6923 check_pointer_arithmetic(&expression->base.source_position,
6924 type_left, orig_type_left);
6925 expression->base.type = type_left;
6926 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6927 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6932 * Check the semantic restrictions of a logical expression.
6934 static void semantic_logical_op(binary_expression_t *expression)
6936 expression_t *const left = expression->left;
6937 expression_t *const right = expression->right;
6938 type_t *const orig_type_left = left->base.type;
6939 type_t *const orig_type_right = right->base.type;
6940 type_t *const type_left = skip_typeref(orig_type_left);
6941 type_t *const type_right = skip_typeref(orig_type_right);
6943 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6944 /* TODO: improve error message */
6945 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6946 errorf(HERE, "operation needs scalar types");
6951 expression->base.type = type_int;
6955 * Check the semantic restrictions of a binary assign expression.
6957 static void semantic_binexpr_assign(binary_expression_t *expression)
6959 expression_t *left = expression->left;
6960 type_t *orig_type_left = left->base.type;
6962 type_t *type_left = revert_automatic_type_conversion(left);
6963 type_left = skip_typeref(orig_type_left);
6965 if (!is_valid_assignment_lhs(left))
6968 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6969 report_assign_error(error, orig_type_left, expression->right,
6970 "assignment", &left->base.source_position);
6971 expression->right = create_implicit_cast(expression->right, orig_type_left);
6972 expression->base.type = orig_type_left;
6976 * Determine if the outermost operation (or parts thereof) of the given
6977 * expression has no effect in order to generate a warning about this fact.
6978 * Therefore in some cases this only examines some of the operands of the
6979 * expression (see comments in the function and examples below).
6981 * f() + 23; // warning, because + has no effect
6982 * x || f(); // no warning, because x controls execution of f()
6983 * x ? y : f(); // warning, because y has no effect
6984 * (void)x; // no warning to be able to suppress the warning
6985 * This function can NOT be used for an "expression has definitely no effect"-
6987 static bool expression_has_effect(const expression_t *const expr)
6989 switch (expr->kind) {
6990 case EXPR_UNKNOWN: break;
6991 case EXPR_INVALID: return true; /* do NOT warn */
6992 case EXPR_REFERENCE: return false;
6993 /* suppress the warning for microsoft __noop operations */
6994 case EXPR_CONST: return expr->conste.is_ms_noop;
6995 case EXPR_CHARACTER_CONSTANT: return false;
6996 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6997 case EXPR_STRING_LITERAL: return false;
6998 case EXPR_WIDE_STRING_LITERAL: return false;
7001 const call_expression_t *const call = &expr->call;
7002 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7005 switch (call->function->builtin_symbol.symbol->ID) {
7006 case T___builtin_va_end: return true;
7007 default: return false;
7011 /* Generate the warning if either the left or right hand side of a
7012 * conditional expression has no effect */
7013 case EXPR_CONDITIONAL: {
7014 const conditional_expression_t *const cond = &expr->conditional;
7016 expression_has_effect(cond->true_expression) &&
7017 expression_has_effect(cond->false_expression);
7020 case EXPR_SELECT: return false;
7021 case EXPR_ARRAY_ACCESS: return false;
7022 case EXPR_SIZEOF: return false;
7023 case EXPR_CLASSIFY_TYPE: return false;
7024 case EXPR_ALIGNOF: return false;
7026 case EXPR_FUNCNAME: return false;
7027 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7028 case EXPR_BUILTIN_CONSTANT_P: return false;
7029 case EXPR_BUILTIN_PREFETCH: return true;
7030 case EXPR_OFFSETOF: return false;
7031 case EXPR_VA_START: return true;
7032 case EXPR_VA_ARG: return true;
7033 case EXPR_STATEMENT: return true; // TODO
7034 case EXPR_COMPOUND_LITERAL: return false;
7036 case EXPR_UNARY_NEGATE: return false;
7037 case EXPR_UNARY_PLUS: return false;
7038 case EXPR_UNARY_BITWISE_NEGATE: return false;
7039 case EXPR_UNARY_NOT: return false;
7040 case EXPR_UNARY_DEREFERENCE: return false;
7041 case EXPR_UNARY_TAKE_ADDRESS: return false;
7042 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7043 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7044 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7045 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7047 /* Treat void casts as if they have an effect in order to being able to
7048 * suppress the warning */
7049 case EXPR_UNARY_CAST: {
7050 type_t *const type = skip_typeref(expr->base.type);
7051 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7054 case EXPR_UNARY_CAST_IMPLICIT: return true;
7055 case EXPR_UNARY_ASSUME: return true;
7057 case EXPR_BINARY_ADD: return false;
7058 case EXPR_BINARY_SUB: return false;
7059 case EXPR_BINARY_MUL: return false;
7060 case EXPR_BINARY_DIV: return false;
7061 case EXPR_BINARY_MOD: return false;
7062 case EXPR_BINARY_EQUAL: return false;
7063 case EXPR_BINARY_NOTEQUAL: return false;
7064 case EXPR_BINARY_LESS: return false;
7065 case EXPR_BINARY_LESSEQUAL: return false;
7066 case EXPR_BINARY_GREATER: return false;
7067 case EXPR_BINARY_GREATEREQUAL: return false;
7068 case EXPR_BINARY_BITWISE_AND: return false;
7069 case EXPR_BINARY_BITWISE_OR: return false;
7070 case EXPR_BINARY_BITWISE_XOR: return false;
7071 case EXPR_BINARY_SHIFTLEFT: return false;
7072 case EXPR_BINARY_SHIFTRIGHT: return false;
7073 case EXPR_BINARY_ASSIGN: return true;
7074 case EXPR_BINARY_MUL_ASSIGN: return true;
7075 case EXPR_BINARY_DIV_ASSIGN: return true;
7076 case EXPR_BINARY_MOD_ASSIGN: return true;
7077 case EXPR_BINARY_ADD_ASSIGN: return true;
7078 case EXPR_BINARY_SUB_ASSIGN: return true;
7079 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7080 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7081 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7082 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7083 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7085 /* Only examine the right hand side of && and ||, because the left hand
7086 * side already has the effect of controlling the execution of the right
7088 case EXPR_BINARY_LOGICAL_AND:
7089 case EXPR_BINARY_LOGICAL_OR:
7090 /* Only examine the right hand side of a comma expression, because the left
7091 * hand side has a separate warning */
7092 case EXPR_BINARY_COMMA:
7093 return expression_has_effect(expr->binary.right);
7095 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7096 case EXPR_BINARY_ISGREATER: return false;
7097 case EXPR_BINARY_ISGREATEREQUAL: return false;
7098 case EXPR_BINARY_ISLESS: return false;
7099 case EXPR_BINARY_ISLESSEQUAL: return false;
7100 case EXPR_BINARY_ISLESSGREATER: return false;
7101 case EXPR_BINARY_ISUNORDERED: return false;
7104 internal_errorf(HERE, "unexpected expression");
7107 static void semantic_comma(binary_expression_t *expression)
7109 if (warning.unused_value) {
7110 const expression_t *const left = expression->left;
7111 if (!expression_has_effect(left)) {
7112 warningf(&left->base.source_position,
7113 "left-hand operand of comma expression has no effect");
7116 expression->base.type = expression->right->base.type;
7119 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7120 static expression_t *parse_##binexpression_type(unsigned precedence, \
7121 expression_t *left) \
7124 source_position_t pos = *HERE; \
7126 expression_t *right = parse_sub_expression(precedence + lr); \
7128 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7129 binexpr->base.source_position = pos; \
7130 binexpr->binary.left = left; \
7131 binexpr->binary.right = right; \
7132 sfunc(&binexpr->binary); \
7137 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7138 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7139 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7140 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7141 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7142 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7143 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7144 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7145 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7147 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7148 semantic_comparison, 1)
7149 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7150 semantic_comparison, 1)
7151 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7152 semantic_comparison, 1)
7153 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7154 semantic_comparison, 1)
7156 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7157 semantic_binexpr_arithmetic, 1)
7158 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7159 semantic_binexpr_arithmetic, 1)
7160 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7161 semantic_binexpr_arithmetic, 1)
7162 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7163 semantic_logical_op, 1)
7164 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7165 semantic_logical_op, 1)
7166 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7167 semantic_shift_op, 1)
7168 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7169 semantic_shift_op, 1)
7170 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7171 semantic_arithmetic_addsubb_assign, 0)
7172 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7173 semantic_arithmetic_addsubb_assign, 0)
7174 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7175 semantic_arithmetic_assign, 0)
7176 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7177 semantic_arithmetic_assign, 0)
7178 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7179 semantic_arithmetic_assign, 0)
7180 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7181 semantic_arithmetic_assign, 0)
7182 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7183 semantic_arithmetic_assign, 0)
7184 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7185 semantic_arithmetic_assign, 0)
7186 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7187 semantic_arithmetic_assign, 0)
7188 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7189 semantic_arithmetic_assign, 0)
7191 static expression_t *parse_sub_expression(unsigned precedence)
7193 if (token.type < 0) {
7194 return expected_expression_error();
7197 expression_parser_function_t *parser
7198 = &expression_parsers[token.type];
7199 source_position_t source_position = token.source_position;
7202 if (parser->parser != NULL) {
7203 left = parser->parser(parser->precedence);
7205 left = parse_primary_expression();
7207 assert(left != NULL);
7208 left->base.source_position = source_position;
7211 if (token.type < 0) {
7212 return expected_expression_error();
7215 parser = &expression_parsers[token.type];
7216 if (parser->infix_parser == NULL)
7218 if (parser->infix_precedence < precedence)
7221 left = parser->infix_parser(parser->infix_precedence, left);
7223 assert(left != NULL);
7224 assert(left->kind != EXPR_UNKNOWN);
7225 left->base.source_position = source_position;
7232 * Parse an expression.
7234 static expression_t *parse_expression(void)
7236 return parse_sub_expression(1);
7240 * Register a parser for a prefix-like operator with given precedence.
7242 * @param parser the parser function
7243 * @param token_type the token type of the prefix token
7244 * @param precedence the precedence of the operator
7246 static void register_expression_parser(parse_expression_function parser,
7247 int token_type, unsigned precedence)
7249 expression_parser_function_t *entry = &expression_parsers[token_type];
7251 if (entry->parser != NULL) {
7252 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7253 panic("trying to register multiple expression parsers for a token");
7255 entry->parser = parser;
7256 entry->precedence = precedence;
7260 * Register a parser for an infix operator with given precedence.
7262 * @param parser the parser function
7263 * @param token_type the token type of the infix operator
7264 * @param precedence the precedence of the operator
7266 static void register_infix_parser(parse_expression_infix_function parser,
7267 int token_type, unsigned precedence)
7269 expression_parser_function_t *entry = &expression_parsers[token_type];
7271 if (entry->infix_parser != NULL) {
7272 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7273 panic("trying to register multiple infix expression parsers for a "
7276 entry->infix_parser = parser;
7277 entry->infix_precedence = precedence;
7281 * Initialize the expression parsers.
7283 static void init_expression_parsers(void)
7285 memset(&expression_parsers, 0, sizeof(expression_parsers));
7287 register_infix_parser(parse_array_expression, '[', 30);
7288 register_infix_parser(parse_call_expression, '(', 30);
7289 register_infix_parser(parse_select_expression, '.', 30);
7290 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7291 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7293 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7296 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7297 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7298 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7299 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7300 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7301 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7302 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7303 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7304 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7305 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7306 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7307 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7308 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7309 T_EXCLAMATIONMARKEQUAL, 13);
7310 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7311 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7312 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7313 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7314 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7315 register_infix_parser(parse_conditional_expression, '?', 7);
7316 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7317 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7318 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7319 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7320 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7321 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7322 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7323 T_LESSLESSEQUAL, 2);
7324 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7325 T_GREATERGREATEREQUAL, 2);
7326 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7328 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7330 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7333 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7335 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7336 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7337 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7338 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7339 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7340 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7341 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7343 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7345 register_expression_parser(parse_sizeof, T_sizeof, 25);
7346 register_expression_parser(parse_alignof, T___alignof__, 25);
7347 register_expression_parser(parse_extension, T___extension__, 25);
7348 register_expression_parser(parse_builtin_classify_type,
7349 T___builtin_classify_type, 25);
7353 * Parse a asm statement arguments specification.
7355 static asm_argument_t *parse_asm_arguments(bool is_out)
7357 asm_argument_t *result = NULL;
7358 asm_argument_t *last = NULL;
7360 while (token.type == T_STRING_LITERAL || token.type == '[') {
7361 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7362 memset(argument, 0, sizeof(argument[0]));
7364 if (token.type == '[') {
7366 if (token.type != T_IDENTIFIER) {
7367 parse_error_expected("while parsing asm argument",
7368 T_IDENTIFIER, NULL);
7371 argument->symbol = token.v.symbol;
7376 argument->constraints = parse_string_literals();
7378 expression_t *expression = parse_expression();
7379 argument->expression = expression;
7380 if (is_out && !is_lvalue(expression)) {
7381 errorf(&expression->base.source_position,
7382 "asm output argument is not an lvalue");
7386 set_address_taken(expression, true);
7389 last->next = argument;
7395 if (token.type != ',')
7406 * Parse a asm statement clobber specification.
7408 static asm_clobber_t *parse_asm_clobbers(void)
7410 asm_clobber_t *result = NULL;
7411 asm_clobber_t *last = NULL;
7413 while(token.type == T_STRING_LITERAL) {
7414 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7415 clobber->clobber = parse_string_literals();
7418 last->next = clobber;
7424 if (token.type != ',')
7433 * Parse an asm statement.
7435 static statement_t *parse_asm_statement(void)
7439 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7440 statement->base.source_position = token.source_position;
7442 asm_statement_t *asm_statement = &statement->asms;
7444 if (token.type == T_volatile) {
7446 asm_statement->is_volatile = true;
7450 add_anchor_token(')');
7451 add_anchor_token(':');
7452 asm_statement->asm_text = parse_string_literals();
7454 if (token.type != ':') {
7455 rem_anchor_token(':');
7460 asm_statement->outputs = parse_asm_arguments(true);
7461 if (token.type != ':') {
7462 rem_anchor_token(':');
7467 asm_statement->inputs = parse_asm_arguments(false);
7468 if (token.type != ':') {
7469 rem_anchor_token(':');
7472 rem_anchor_token(':');
7475 asm_statement->clobbers = parse_asm_clobbers();
7478 rem_anchor_token(')');
7483 return create_invalid_statement();
7487 * Parse a case statement.
7489 static statement_t *parse_case_statement(void)
7493 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7495 statement->base.source_position = token.source_position;
7496 statement->case_label.expression = parse_expression();
7498 if (c_mode & _GNUC) {
7499 if (token.type == T_DOTDOTDOT) {
7501 statement->case_label.end_range = parse_expression();
7507 if (! is_constant_expression(statement->case_label.expression)) {
7508 errorf(&statement->base.source_position,
7509 "case label does not reduce to an integer constant");
7511 /* TODO: check if the case label is already known */
7512 if (current_switch != NULL) {
7513 /* link all cases into the switch statement */
7514 if (current_switch->last_case == NULL) {
7515 current_switch->first_case =
7516 current_switch->last_case = &statement->case_label;
7518 current_switch->last_case->next = &statement->case_label;
7521 errorf(&statement->base.source_position,
7522 "case label not within a switch statement");
7525 statement->case_label.statement = parse_statement();
7529 return create_invalid_statement();
7533 * Finds an existing default label of a switch statement.
7535 static case_label_statement_t *
7536 find_default_label(const switch_statement_t *statement)
7538 case_label_statement_t *label = statement->first_case;
7539 for ( ; label != NULL; label = label->next) {
7540 if (label->expression == NULL)
7547 * Parse a default statement.
7549 static statement_t *parse_default_statement(void)
7553 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7555 statement->base.source_position = token.source_position;
7558 if (current_switch != NULL) {
7559 const case_label_statement_t *def_label = find_default_label(current_switch);
7560 if (def_label != NULL) {
7561 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7562 &def_label->base.source_position);
7564 /* link all cases into the switch statement */
7565 if (current_switch->last_case == NULL) {
7566 current_switch->first_case =
7567 current_switch->last_case = &statement->case_label;
7569 current_switch->last_case->next = &statement->case_label;
7573 errorf(&statement->base.source_position,
7574 "'default' label not within a switch statement");
7576 statement->case_label.statement = parse_statement();
7580 return create_invalid_statement();
7584 * Return the declaration for a given label symbol or create a new one.
7586 static declaration_t *get_label(symbol_t *symbol)
7588 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7589 assert(current_function != NULL);
7590 /* if we found a label in the same function, then we already created the
7592 if (candidate != NULL
7593 && candidate->parent_scope == ¤t_function->scope) {
7597 /* otherwise we need to create a new one */
7598 declaration_t *const declaration = allocate_declaration_zero();
7599 declaration->namespc = NAMESPACE_LABEL;
7600 declaration->symbol = symbol;
7602 label_push(declaration);
7608 * Parse a label statement.
7610 static statement_t *parse_label_statement(void)
7612 assert(token.type == T_IDENTIFIER);
7613 symbol_t *symbol = token.v.symbol;
7616 declaration_t *label = get_label(symbol);
7618 /* if source position is already set then the label is defined twice,
7619 * otherwise it was just mentioned in a goto so far */
7620 if (label->source_position.input_name != NULL) {
7621 errorf(HERE, "duplicate label '%Y' (declared %P)",
7622 symbol, &label->source_position);
7624 label->source_position = token.source_position;
7627 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7629 statement->base.source_position = token.source_position;
7630 statement->label.label = label;
7634 if (token.type == '}') {
7635 /* TODO only warn? */
7637 warningf(HERE, "label at end of compound statement");
7638 statement->label.statement = create_empty_statement();
7640 errorf(HERE, "label at end of compound statement");
7641 statement->label.statement = create_invalid_statement();
7645 if (token.type == ';') {
7646 /* eat an empty statement here, to avoid the warning about an empty
7647 * after a label. label:; is commonly used to have a label before
7649 statement->label.statement = create_empty_statement();
7652 statement->label.statement = parse_statement();
7656 /* remember the labels's in a list for later checking */
7657 if (label_last == NULL) {
7658 label_first = &statement->label;
7660 label_last->next = &statement->label;
7662 label_last = &statement->label;
7668 * Parse an if statement.
7670 static statement_t *parse_if(void)
7674 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7675 statement->base.source_position = token.source_position;
7678 add_anchor_token(')');
7679 statement->ifs.condition = parse_expression();
7680 rem_anchor_token(')');
7683 add_anchor_token(T_else);
7684 statement->ifs.true_statement = parse_statement();
7685 rem_anchor_token(T_else);
7687 if (token.type == T_else) {
7689 statement->ifs.false_statement = parse_statement();
7694 return create_invalid_statement();
7698 * Parse a switch statement.
7700 static statement_t *parse_switch(void)
7704 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7705 statement->base.source_position = token.source_position;
7708 expression_t *const expr = parse_expression();
7709 type_t * type = skip_typeref(expr->base.type);
7710 if (is_type_integer(type)) {
7711 type = promote_integer(type);
7712 } else if (is_type_valid(type)) {
7713 errorf(&expr->base.source_position,
7714 "switch quantity is not an integer, but '%T'", type);
7715 type = type_error_type;
7717 statement->switchs.expression = create_implicit_cast(expr, type);
7720 switch_statement_t *rem = current_switch;
7721 current_switch = &statement->switchs;
7722 statement->switchs.body = parse_statement();
7723 current_switch = rem;
7725 if (warning.switch_default &&
7726 find_default_label(&statement->switchs) == NULL) {
7727 warningf(&statement->base.source_position, "switch has no default case");
7732 return create_invalid_statement();
7735 static statement_t *parse_loop_body(statement_t *const loop)
7737 statement_t *const rem = current_loop;
7738 current_loop = loop;
7740 statement_t *const body = parse_statement();
7747 * Parse a while statement.
7749 static statement_t *parse_while(void)
7753 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7754 statement->base.source_position = token.source_position;
7757 add_anchor_token(')');
7758 statement->whiles.condition = parse_expression();
7759 rem_anchor_token(')');
7762 statement->whiles.body = parse_loop_body(statement);
7766 return create_invalid_statement();
7770 * Parse a do statement.
7772 static statement_t *parse_do(void)
7776 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7778 statement->base.source_position = token.source_position;
7780 add_anchor_token(T_while);
7781 statement->do_while.body = parse_loop_body(statement);
7782 rem_anchor_token(T_while);
7786 add_anchor_token(')');
7787 statement->do_while.condition = parse_expression();
7788 rem_anchor_token(')');
7794 return create_invalid_statement();
7798 * Parse a for statement.
7800 static statement_t *parse_for(void)
7804 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7805 statement->base.source_position = token.source_position;
7807 int top = environment_top();
7808 scope_t *last_scope = scope;
7809 set_scope(&statement->fors.scope);
7812 add_anchor_token(')');
7814 if (token.type != ';') {
7815 if (is_declaration_specifier(&token, false)) {
7816 parse_declaration(record_declaration);
7818 add_anchor_token(';');
7819 expression_t *const init = parse_expression();
7820 statement->fors.initialisation = init;
7821 if (warning.unused_value && !expression_has_effect(init)) {
7822 warningf(&init->base.source_position,
7823 "initialisation of 'for'-statement has no effect");
7825 rem_anchor_token(';');
7832 if (token.type != ';') {
7833 add_anchor_token(';');
7834 statement->fors.condition = parse_expression();
7835 rem_anchor_token(';');
7838 if (token.type != ')') {
7839 expression_t *const step = parse_expression();
7840 statement->fors.step = step;
7841 if (warning.unused_value && !expression_has_effect(step)) {
7842 warningf(&step->base.source_position,
7843 "step of 'for'-statement has no effect");
7846 rem_anchor_token(')');
7848 statement->fors.body = parse_loop_body(statement);
7850 assert(scope == &statement->fors.scope);
7851 set_scope(last_scope);
7852 environment_pop_to(top);
7857 rem_anchor_token(')');
7858 assert(scope == &statement->fors.scope);
7859 set_scope(last_scope);
7860 environment_pop_to(top);
7862 return create_invalid_statement();
7866 * Parse a goto statement.
7868 static statement_t *parse_goto(void)
7872 if (token.type != T_IDENTIFIER) {
7873 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7877 symbol_t *symbol = token.v.symbol;
7880 declaration_t *label = get_label(symbol);
7882 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7883 statement->base.source_position = token.source_position;
7885 statement->gotos.label = label;
7887 /* remember the goto's in a list for later checking */
7888 if (goto_last == NULL) {
7889 goto_first = &statement->gotos;
7891 goto_last->next = &statement->gotos;
7893 goto_last = &statement->gotos;
7899 return create_invalid_statement();
7903 * Parse a continue statement.
7905 static statement_t *parse_continue(void)
7907 statement_t *statement;
7908 if (current_loop == NULL) {
7909 errorf(HERE, "continue statement not within loop");
7910 statement = create_invalid_statement();
7912 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7914 statement->base.source_position = token.source_position;
7922 return create_invalid_statement();
7926 * Parse a break statement.
7928 static statement_t *parse_break(void)
7930 statement_t *statement;
7931 if (current_switch == NULL && current_loop == NULL) {
7932 errorf(HERE, "break statement not within loop or switch");
7933 statement = create_invalid_statement();
7935 statement = allocate_statement_zero(STATEMENT_BREAK);
7937 statement->base.source_position = token.source_position;
7945 return create_invalid_statement();
7949 * Parse a __leave statement.
7951 static statement_t *parse_leave(void)
7953 statement_t *statement;
7954 if (current_try == NULL) {
7955 errorf(HERE, "__leave statement not within __try");
7956 statement = create_invalid_statement();
7958 statement = allocate_statement_zero(STATEMENT_LEAVE);
7960 statement->base.source_position = token.source_position;
7968 return create_invalid_statement();
7972 * Check if a given declaration represents a local variable.
7974 static bool is_local_var_declaration(const declaration_t *declaration) {
7975 switch ((storage_class_tag_t) declaration->storage_class) {
7976 case STORAGE_CLASS_AUTO:
7977 case STORAGE_CLASS_REGISTER: {
7978 const type_t *type = skip_typeref(declaration->type);
7979 if (is_type_function(type)) {
7991 * Check if a given declaration represents a variable.
7993 static bool is_var_declaration(const declaration_t *declaration) {
7994 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7997 const type_t *type = skip_typeref(declaration->type);
7998 return !is_type_function(type);
8002 * Check if a given expression represents a local variable.
8004 static bool is_local_variable(const expression_t *expression)
8006 if (expression->base.kind != EXPR_REFERENCE) {
8009 const declaration_t *declaration = expression->reference.declaration;
8010 return is_local_var_declaration(declaration);
8014 * Check if a given expression represents a local variable and
8015 * return its declaration then, else return NULL.
8017 declaration_t *expr_is_variable(const expression_t *expression)
8019 if (expression->base.kind != EXPR_REFERENCE) {
8022 declaration_t *declaration = expression->reference.declaration;
8023 if (is_var_declaration(declaration))
8029 * Parse a return statement.
8031 static statement_t *parse_return(void)
8033 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
8034 statement->base.source_position = token.source_position;
8038 expression_t *return_value = NULL;
8039 if (token.type != ';') {
8040 return_value = parse_expression();
8044 const type_t *const func_type = current_function->type;
8045 assert(is_type_function(func_type));
8046 type_t *const return_type = skip_typeref(func_type->function.return_type);
8048 if (return_value != NULL) {
8049 type_t *return_value_type = skip_typeref(return_value->base.type);
8051 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8052 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8053 warningf(&statement->base.source_position,
8054 "'return' with a value, in function returning void");
8055 return_value = NULL;
8057 assign_error_t error = semantic_assign(return_type, return_value);
8058 report_assign_error(error, return_type, return_value, "'return'",
8059 &statement->base.source_position);
8060 return_value = create_implicit_cast(return_value, return_type);
8062 /* check for returning address of a local var */
8063 if (return_value != NULL &&
8064 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8065 const expression_t *expression = return_value->unary.value;
8066 if (is_local_variable(expression)) {
8067 warningf(&statement->base.source_position,
8068 "function returns address of local variable");
8072 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8073 warningf(&statement->base.source_position,
8074 "'return' without value, in function returning non-void");
8077 statement->returns.value = return_value;
8081 return create_invalid_statement();
8085 * Parse a declaration statement.
8087 static statement_t *parse_declaration_statement(void)
8089 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8091 statement->base.source_position = token.source_position;
8093 declaration_t *before = last_declaration;
8094 parse_declaration(record_declaration);
8096 if (before == NULL) {
8097 statement->declaration.declarations_begin = scope->declarations;
8099 statement->declaration.declarations_begin = before->next;
8101 statement->declaration.declarations_end = last_declaration;
8107 * Parse an expression statement, ie. expr ';'.
8109 static statement_t *parse_expression_statement(void)
8111 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8113 statement->base.source_position = token.source_position;
8114 expression_t *const expr = parse_expression();
8115 statement->expression.expression = expr;
8121 return create_invalid_statement();
8125 * Parse a microsoft __try { } __finally { } or
8126 * __try{ } __except() { }
8128 static statement_t *parse_ms_try_statment(void) {
8129 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8131 statement->base.source_position = token.source_position;
8134 ms_try_statement_t *rem = current_try;
8135 current_try = &statement->ms_try;
8136 statement->ms_try.try_statement = parse_compound_statement(false);
8139 if (token.type == T___except) {
8142 add_anchor_token(')');
8143 expression_t *const expr = parse_expression();
8144 type_t * type = skip_typeref(expr->base.type);
8145 if (is_type_integer(type)) {
8146 type = promote_integer(type);
8147 } else if (is_type_valid(type)) {
8148 errorf(&expr->base.source_position,
8149 "__expect expression is not an integer, but '%T'", type);
8150 type = type_error_type;
8152 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8153 rem_anchor_token(')');
8155 statement->ms_try.final_statement = parse_compound_statement(false);
8156 } else if (token.type == T__finally) {
8158 statement->ms_try.final_statement = parse_compound_statement(false);
8160 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8161 return create_invalid_statement();
8165 return create_invalid_statement();
8169 * Parse a statement.
8170 * There's also parse_statement() which additionally checks for
8171 * "statement has no effect" warnings
8173 static statement_t *intern_parse_statement(void)
8175 statement_t *statement = NULL;
8177 /* declaration or statement */
8178 add_anchor_token(';');
8179 switch(token.type) {
8181 statement = parse_asm_statement();
8185 statement = parse_case_statement();
8189 statement = parse_default_statement();
8193 statement = parse_compound_statement(false);
8197 statement = parse_if ();
8201 statement = parse_switch();
8205 statement = parse_while();
8209 statement = parse_do();
8213 statement = parse_for();
8217 statement = parse_goto();
8221 statement = parse_continue();
8225 statement = parse_break();
8229 statement = parse_leave();
8233 statement = parse_return();
8237 if (warning.empty_statement) {
8238 warningf(HERE, "statement is empty");
8240 statement = create_empty_statement();
8245 if (look_ahead(1)->type == ':') {
8246 statement = parse_label_statement();
8250 if (is_typedef_symbol(token.v.symbol)) {
8251 statement = parse_declaration_statement();
8255 statement = parse_expression_statement();
8258 case T___extension__:
8259 /* this can be a prefix to a declaration or an expression statement */
8260 /* we simply eat it now and parse the rest with tail recursion */
8263 } while(token.type == T___extension__);
8264 statement = parse_statement();
8268 statement = parse_declaration_statement();
8272 statement = parse_ms_try_statment();
8276 statement = parse_expression_statement();
8279 rem_anchor_token(';');
8281 assert(statement != NULL
8282 && statement->base.source_position.input_name != NULL);
8288 * parse a statement and emits "statement has no effect" warning if needed
8289 * (This is really a wrapper around intern_parse_statement with check for 1
8290 * single warning. It is needed, because for statement expressions we have
8291 * to avoid the warning on the last statement)
8293 static statement_t *parse_statement(void)
8295 statement_t *statement = intern_parse_statement();
8297 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8298 expression_t *expression = statement->expression.expression;
8299 if (!expression_has_effect(expression)) {
8300 warningf(&expression->base.source_position,
8301 "statement has no effect");
8309 * Parse a compound statement.
8311 static statement_t *parse_compound_statement(bool inside_expression_statement)
8313 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8315 statement->base.source_position = token.source_position;
8318 add_anchor_token('}');
8320 int top = environment_top();
8321 scope_t *last_scope = scope;
8322 set_scope(&statement->compound.scope);
8324 statement_t *last_statement = NULL;
8326 while(token.type != '}' && token.type != T_EOF) {
8327 statement_t *sub_statement = intern_parse_statement();
8328 if (is_invalid_statement(sub_statement)) {
8329 /* an error occurred. if we are at an anchor, return */
8335 if (last_statement != NULL) {
8336 last_statement->base.next = sub_statement;
8338 statement->compound.statements = sub_statement;
8341 while(sub_statement->base.next != NULL)
8342 sub_statement = sub_statement->base.next;
8344 last_statement = sub_statement;
8347 if (token.type == '}') {
8350 errorf(&statement->base.source_position,
8351 "end of file while looking for closing '}'");
8354 /* look over all statements again to produce no effect warnings */
8355 if (warning.unused_value) {
8356 statement_t *sub_statement = statement->compound.statements;
8357 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8358 if (sub_statement->kind != STATEMENT_EXPRESSION)
8360 /* don't emit a warning for the last expression in an expression
8361 * statement as it has always an effect */
8362 if (inside_expression_statement && sub_statement->base.next == NULL)
8365 expression_t *expression = sub_statement->expression.expression;
8366 if (!expression_has_effect(expression)) {
8367 warningf(&expression->base.source_position,
8368 "statement has no effect");
8374 rem_anchor_token('}');
8375 assert(scope == &statement->compound.scope);
8376 set_scope(last_scope);
8377 environment_pop_to(top);
8383 * Initialize builtin types.
8385 static void initialize_builtin_types(void)
8387 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8388 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8389 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8390 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8391 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8392 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8393 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8394 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8396 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8397 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8398 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8399 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8403 * Check for unused global static functions and variables
8405 static void check_unused_globals(void)
8407 if (!warning.unused_function && !warning.unused_variable)
8410 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8412 decl->modifiers & DM_USED ||
8413 decl->storage_class != STORAGE_CLASS_STATIC)
8416 type_t *const type = decl->type;
8418 if (is_type_function(skip_typeref(type))) {
8419 if (!warning.unused_function || decl->is_inline)
8422 s = (decl->init.statement != NULL ? "defined" : "declared");
8424 if (!warning.unused_variable)
8430 warningf(&decl->source_position, "'%#T' %s but not used",
8431 type, decl->symbol, s);
8435 static void parse_global_asm(void)
8440 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8441 statement->base.source_position = token.source_position;
8442 statement->asms.asm_text = parse_string_literals();
8443 statement->base.next = unit->global_asm;
8444 unit->global_asm = statement;
8453 * Parse a translation unit.
8455 static void parse_translation_unit(void)
8457 while(token.type != T_EOF) {
8458 switch (token.type) {
8460 /* TODO error in strict mode */
8461 warningf(HERE, "stray ';' outside of function");
8470 parse_external_declaration();
8479 * @return the translation unit or NULL if errors occurred.
8481 void start_parsing(void)
8483 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8484 label_stack = NEW_ARR_F(stack_entry_t, 0);
8485 diagnostic_count = 0;
8489 type_set_output(stderr);
8490 ast_set_output(stderr);
8492 assert(unit == NULL);
8493 unit = allocate_ast_zero(sizeof(unit[0]));
8495 assert(global_scope == NULL);
8496 global_scope = &unit->scope;
8498 assert(scope == NULL);
8499 set_scope(&unit->scope);
8501 initialize_builtin_types();
8504 translation_unit_t *finish_parsing(void)
8506 assert(scope == &unit->scope);
8508 last_declaration = NULL;
8510 assert(global_scope == &unit->scope);
8511 check_unused_globals();
8512 global_scope = NULL;
8514 DEL_ARR_F(environment_stack);
8515 DEL_ARR_F(label_stack);
8517 translation_unit_t *result = unit;
8524 lookahead_bufpos = 0;
8525 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8528 parse_translation_unit();
8532 * Initialize the parser.
8534 void init_parser(void)
8537 /* add predefined symbols for extended-decl-modifier */
8538 sym_align = symbol_table_insert("align");
8539 sym_allocate = symbol_table_insert("allocate");
8540 sym_dllimport = symbol_table_insert("dllimport");
8541 sym_dllexport = symbol_table_insert("dllexport");
8542 sym_naked = symbol_table_insert("naked");
8543 sym_noinline = symbol_table_insert("noinline");
8544 sym_noreturn = symbol_table_insert("noreturn");
8545 sym_nothrow = symbol_table_insert("nothrow");
8546 sym_novtable = symbol_table_insert("novtable");
8547 sym_property = symbol_table_insert("property");
8548 sym_get = symbol_table_insert("get");
8549 sym_put = symbol_table_insert("put");
8550 sym_selectany = symbol_table_insert("selectany");
8551 sym_thread = symbol_table_insert("thread");
8552 sym_uuid = symbol_table_insert("uuid");
8553 sym_deprecated = symbol_table_insert("deprecated");
8554 sym_restrict = symbol_table_insert("restrict");
8555 sym_noalias = symbol_table_insert("noalias");
8557 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8559 init_expression_parsers();
8560 obstack_init(&temp_obst);
8562 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8563 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8567 * Terminate the parser.
8569 void exit_parser(void)
8571 obstack_free(&temp_obst, NULL);