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 (!is_function_definition &&
4130 warning.redundant_decls &&
4131 strcmp(previous_declaration->source_position.input_name, "<builtin>") != 0) {
4132 warningf(&declaration->source_position,
4133 "redundant declaration for '%Y' (declared %P)",
4134 symbol, &previous_declaration->source_position);
4136 } else if (current_function == NULL) {
4137 if (old_storage_class != STORAGE_CLASS_STATIC &&
4138 new_storage_class == STORAGE_CLASS_STATIC) {
4139 errorf(&declaration->source_position,
4140 "static declaration of '%Y' follows non-static declaration (declared %P)",
4141 symbol, &previous_declaration->source_position);
4142 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4143 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4144 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4146 goto warn_redundant_declaration;
4148 } else if (old_storage_class == new_storage_class) {
4149 errorf(&declaration->source_position,
4150 "redeclaration of '%Y' (declared %P)",
4151 symbol, &previous_declaration->source_position);
4153 errorf(&declaration->source_position,
4154 "redeclaration of '%Y' with different linkage (declared %P)",
4155 symbol, &previous_declaration->source_position);
4159 if (declaration->is_inline)
4160 previous_declaration->is_inline = true;
4161 return previous_declaration;
4162 } else if (is_function_definition) {
4163 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
4164 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4165 warningf(&declaration->source_position,
4166 "no previous prototype for '%#T'", orig_type, symbol);
4167 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4168 warningf(&declaration->source_position,
4169 "no previous declaration for '%#T'", orig_type,
4173 } else if (warning.missing_declarations &&
4174 scope == global_scope &&
4175 !is_type_function(type) && (
4176 declaration->storage_class == STORAGE_CLASS_NONE ||
4177 declaration->storage_class == STORAGE_CLASS_THREAD
4179 warningf(&declaration->source_position,
4180 "no previous declaration for '%#T'", orig_type, symbol);
4183 assert(declaration->parent_scope == NULL);
4184 assert(scope != NULL);
4186 declaration->parent_scope = scope;
4188 environment_push(declaration);
4189 return append_declaration(declaration);
4192 static declaration_t *record_declaration(declaration_t *declaration)
4194 return internal_record_declaration(declaration, false);
4197 static declaration_t *record_function_definition(declaration_t *declaration)
4199 return internal_record_declaration(declaration, true);
4202 static void parser_error_multiple_definition(declaration_t *declaration,
4203 const source_position_t *source_position)
4205 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4206 declaration->symbol, &declaration->source_position);
4209 static bool is_declaration_specifier(const token_t *token,
4210 bool only_specifiers_qualifiers)
4212 switch(token->type) {
4217 return is_typedef_symbol(token->v.symbol);
4219 case T___extension__:
4221 return !only_specifiers_qualifiers;
4228 static void parse_init_declarator_rest(declaration_t *declaration)
4232 type_t *orig_type = declaration->type;
4233 type_t *type = skip_typeref(orig_type);
4235 if (declaration->init.initializer != NULL) {
4236 parser_error_multiple_definition(declaration, HERE);
4239 bool must_be_constant = false;
4240 if (declaration->storage_class == STORAGE_CLASS_STATIC
4241 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
4242 || declaration->parent_scope == global_scope) {
4243 must_be_constant = true;
4246 parse_initializer_env_t env;
4247 env.type = orig_type;
4248 env.must_be_constant = must_be_constant;
4249 env.declaration = declaration;
4251 initializer_t *initializer = parse_initializer(&env);
4253 if (env.type != orig_type) {
4254 orig_type = env.type;
4255 type = skip_typeref(orig_type);
4256 declaration->type = env.type;
4259 if (is_type_function(type)) {
4260 errorf(&declaration->source_position,
4261 "initializers not allowed for function types at declator '%Y' (type '%T')",
4262 declaration->symbol, orig_type);
4264 declaration->init.initializer = initializer;
4268 /* parse rest of a declaration without any declarator */
4269 static void parse_anonymous_declaration_rest(
4270 const declaration_specifiers_t *specifiers,
4271 parsed_declaration_func finished_declaration)
4275 declaration_t *const declaration = allocate_declaration_zero();
4276 declaration->type = specifiers->type;
4277 declaration->declared_storage_class = specifiers->declared_storage_class;
4278 declaration->source_position = specifiers->source_position;
4279 declaration->modifiers = specifiers->modifiers;
4281 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
4282 warningf(&declaration->source_position,
4283 "useless storage class in empty declaration");
4285 declaration->storage_class = STORAGE_CLASS_NONE;
4287 type_t *type = declaration->type;
4288 switch (type->kind) {
4289 case TYPE_COMPOUND_STRUCT:
4290 case TYPE_COMPOUND_UNION: {
4291 if (type->compound.declaration->symbol == NULL) {
4292 warningf(&declaration->source_position,
4293 "unnamed struct/union that defines no instances");
4302 warningf(&declaration->source_position, "empty declaration");
4306 finished_declaration(declaration);
4309 static void parse_declaration_rest(declaration_t *ndeclaration,
4310 const declaration_specifiers_t *specifiers,
4311 parsed_declaration_func finished_declaration)
4313 add_anchor_token(';');
4314 add_anchor_token('=');
4315 add_anchor_token(',');
4317 declaration_t *declaration = finished_declaration(ndeclaration);
4319 type_t *orig_type = declaration->type;
4320 type_t *type = skip_typeref(orig_type);
4322 if (type->kind != TYPE_FUNCTION &&
4323 declaration->is_inline &&
4324 is_type_valid(type)) {
4325 warningf(&declaration->source_position,
4326 "variable '%Y' declared 'inline'\n", declaration->symbol);
4329 if (token.type == '=') {
4330 parse_init_declarator_rest(declaration);
4333 if (token.type != ',')
4337 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
4342 rem_anchor_token(';');
4343 rem_anchor_token('=');
4344 rem_anchor_token(',');
4347 static declaration_t *finished_kr_declaration(declaration_t *declaration)
4349 symbol_t *symbol = declaration->symbol;
4350 if (symbol == NULL) {
4351 errorf(HERE, "anonymous declaration not valid as function parameter");
4354 namespace_t namespc = (namespace_t) declaration->namespc;
4355 if (namespc != NAMESPACE_NORMAL) {
4356 return record_declaration(declaration);
4359 declaration_t *previous_declaration = get_declaration(symbol, namespc);
4360 if (previous_declaration == NULL ||
4361 previous_declaration->parent_scope != scope) {
4362 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4367 if (previous_declaration->type == NULL) {
4368 previous_declaration->type = declaration->type;
4369 previous_declaration->declared_storage_class = declaration->declared_storage_class;
4370 previous_declaration->storage_class = declaration->storage_class;
4371 previous_declaration->parent_scope = scope;
4372 return previous_declaration;
4374 return record_declaration(declaration);
4378 static void parse_declaration(parsed_declaration_func finished_declaration)
4380 declaration_specifiers_t specifiers;
4381 memset(&specifiers, 0, sizeof(specifiers));
4382 parse_declaration_specifiers(&specifiers);
4384 if (token.type == ';') {
4385 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4387 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4388 parse_declaration_rest(declaration, &specifiers, finished_declaration);
4392 static type_t *get_default_promoted_type(type_t *orig_type)
4394 type_t *result = orig_type;
4396 type_t *type = skip_typeref(orig_type);
4397 if (is_type_integer(type)) {
4398 result = promote_integer(type);
4399 } else if (type == type_float) {
4400 result = type_double;
4406 static void parse_kr_declaration_list(declaration_t *declaration)
4408 type_t *type = skip_typeref(declaration->type);
4409 if (!is_type_function(type))
4412 if (!type->function.kr_style_parameters)
4415 /* push function parameters */
4416 int top = environment_top();
4417 scope_t *last_scope = scope;
4418 set_scope(&declaration->scope);
4420 declaration_t *parameter = declaration->scope.declarations;
4421 for ( ; parameter != NULL; parameter = parameter->next) {
4422 assert(parameter->parent_scope == NULL);
4423 parameter->parent_scope = scope;
4424 environment_push(parameter);
4427 /* parse declaration list */
4428 while (is_declaration_specifier(&token, false)) {
4429 parse_declaration(finished_kr_declaration);
4432 /* pop function parameters */
4433 assert(scope == &declaration->scope);
4434 set_scope(last_scope);
4435 environment_pop_to(top);
4437 /* update function type */
4438 type_t *new_type = duplicate_type(type);
4440 function_parameter_t *parameters = NULL;
4441 function_parameter_t *last_parameter = NULL;
4443 declaration_t *parameter_declaration = declaration->scope.declarations;
4444 for( ; parameter_declaration != NULL;
4445 parameter_declaration = parameter_declaration->next) {
4446 type_t *parameter_type = parameter_declaration->type;
4447 if (parameter_type == NULL) {
4449 errorf(HERE, "no type specified for function parameter '%Y'",
4450 parameter_declaration->symbol);
4452 if (warning.implicit_int) {
4453 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4454 parameter_declaration->symbol);
4456 parameter_type = type_int;
4457 parameter_declaration->type = parameter_type;
4461 semantic_parameter(parameter_declaration);
4462 parameter_type = parameter_declaration->type;
4465 * we need the default promoted types for the function type
4467 parameter_type = get_default_promoted_type(parameter_type);
4469 function_parameter_t *function_parameter
4470 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
4471 memset(function_parameter, 0, sizeof(function_parameter[0]));
4473 function_parameter->type = parameter_type;
4474 if (last_parameter != NULL) {
4475 last_parameter->next = function_parameter;
4477 parameters = function_parameter;
4479 last_parameter = function_parameter;
4482 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
4484 new_type->function.parameters = parameters;
4485 new_type->function.unspecified_parameters = true;
4487 type = typehash_insert(new_type);
4488 if (type != new_type) {
4489 obstack_free(type_obst, new_type);
4492 declaration->type = type;
4495 static bool first_err = true;
4498 * When called with first_err set, prints the name of the current function,
4501 static void print_in_function(void) {
4504 diagnosticf("%s: In function '%Y':\n",
4505 current_function->source_position.input_name,
4506 current_function->symbol);
4511 * Check if all labels are defined in the current function.
4512 * Check if all labels are used in the current function.
4514 static void check_labels(void)
4516 for (const goto_statement_t *goto_statement = goto_first;
4517 goto_statement != NULL;
4518 goto_statement = goto_statement->next) {
4519 declaration_t *label = goto_statement->label;
4522 if (label->source_position.input_name == NULL) {
4523 print_in_function();
4524 errorf(&goto_statement->base.source_position,
4525 "label '%Y' used but not defined", label->symbol);
4528 goto_first = goto_last = NULL;
4530 if (warning.unused_label) {
4531 for (const label_statement_t *label_statement = label_first;
4532 label_statement != NULL;
4533 label_statement = label_statement->next) {
4534 const declaration_t *label = label_statement->label;
4536 if (! label->used) {
4537 print_in_function();
4538 warningf(&label_statement->base.source_position,
4539 "label '%Y' defined but not used", label->symbol);
4543 label_first = label_last = NULL;
4547 * Check declarations of current_function for unused entities.
4549 static void check_declarations(void)
4551 if (warning.unused_parameter) {
4552 const scope_t *scope = ¤t_function->scope;
4554 const declaration_t *parameter = scope->declarations;
4555 for (; parameter != NULL; parameter = parameter->next) {
4556 if (! parameter->used) {
4557 print_in_function();
4558 warningf(¶meter->source_position,
4559 "unused parameter '%Y'", parameter->symbol);
4563 if (warning.unused_variable) {
4567 static void parse_external_declaration(void)
4569 /* function-definitions and declarations both start with declaration
4571 declaration_specifiers_t specifiers;
4572 memset(&specifiers, 0, sizeof(specifiers));
4574 add_anchor_token(';');
4575 parse_declaration_specifiers(&specifiers);
4576 rem_anchor_token(';');
4578 /* must be a declaration */
4579 if (token.type == ';') {
4580 parse_anonymous_declaration_rest(&specifiers, append_declaration);
4584 add_anchor_token(',');
4585 add_anchor_token('=');
4586 rem_anchor_token(';');
4588 /* declarator is common to both function-definitions and declarations */
4589 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
4591 rem_anchor_token(',');
4592 rem_anchor_token('=');
4593 rem_anchor_token(';');
4595 /* must be a declaration */
4596 if (token.type == ',' || token.type == '=' || token.type == ';') {
4597 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
4601 /* must be a function definition */
4602 parse_kr_declaration_list(ndeclaration);
4604 if (token.type != '{') {
4605 parse_error_expected("while parsing function definition", '{', NULL);
4606 eat_until_matching_token(';');
4610 type_t *type = ndeclaration->type;
4612 /* note that we don't skip typerefs: the standard doesn't allow them here
4613 * (so we can't use is_type_function here) */
4614 if (type->kind != TYPE_FUNCTION) {
4615 if (is_type_valid(type)) {
4616 errorf(HERE, "declarator '%#T' has a body but is not a function type",
4617 type, ndeclaration->symbol);
4623 /* § 6.7.5.3 (14) a function definition with () means no
4624 * parameters (and not unspecified parameters) */
4625 if (type->function.unspecified_parameters
4626 && type->function.parameters == NULL
4627 && !type->function.kr_style_parameters) {
4628 type_t *duplicate = duplicate_type(type);
4629 duplicate->function.unspecified_parameters = false;
4631 type = typehash_insert(duplicate);
4632 if (type != duplicate) {
4633 obstack_free(type_obst, duplicate);
4635 ndeclaration->type = type;
4638 declaration_t *const declaration = record_function_definition(ndeclaration);
4639 if (ndeclaration != declaration) {
4640 declaration->scope = ndeclaration->scope;
4642 type = skip_typeref(declaration->type);
4644 /* push function parameters and switch scope */
4645 int top = environment_top();
4646 scope_t *last_scope = scope;
4647 set_scope(&declaration->scope);
4649 declaration_t *parameter = declaration->scope.declarations;
4650 for( ; parameter != NULL; parameter = parameter->next) {
4651 if (parameter->parent_scope == &ndeclaration->scope) {
4652 parameter->parent_scope = scope;
4654 assert(parameter->parent_scope == NULL
4655 || parameter->parent_scope == scope);
4656 parameter->parent_scope = scope;
4657 if (parameter->symbol == NULL) {
4658 errorf(&ndeclaration->source_position, "parameter name omitted");
4661 environment_push(parameter);
4664 if (declaration->init.statement != NULL) {
4665 parser_error_multiple_definition(declaration, HERE);
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 assert(scope == &declaration->scope);
4684 set_scope(last_scope);
4685 environment_pop_to(top);
4688 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
4689 source_position_t *source_position)
4691 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
4693 type->bitfield.base_type = base_type;
4694 type->bitfield.size = size;
4699 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
4702 declaration_t *iter = compound_declaration->scope.declarations;
4703 for( ; iter != NULL; iter = iter->next) {
4704 if (iter->namespc != NAMESPACE_NORMAL)
4707 if (iter->symbol == NULL) {
4708 type_t *type = skip_typeref(iter->type);
4709 if (is_type_compound(type)) {
4710 declaration_t *result
4711 = find_compound_entry(type->compound.declaration, symbol);
4718 if (iter->symbol == symbol) {
4726 static void parse_compound_declarators(declaration_t *struct_declaration,
4727 const declaration_specifiers_t *specifiers)
4729 declaration_t *last_declaration = struct_declaration->scope.declarations;
4730 if (last_declaration != NULL) {
4731 while(last_declaration->next != NULL) {
4732 last_declaration = last_declaration->next;
4737 declaration_t *declaration;
4739 if (token.type == ':') {
4740 source_position_t source_position = *HERE;
4743 type_t *base_type = specifiers->type;
4744 expression_t *size = parse_constant_expression();
4746 if (!is_type_integer(skip_typeref(base_type))) {
4747 errorf(HERE, "bitfield base type '%T' is not an integer type",
4751 type_t *type = make_bitfield_type(base_type, size, &source_position);
4753 declaration = allocate_declaration_zero();
4754 declaration->namespc = NAMESPACE_NORMAL;
4755 declaration->declared_storage_class = STORAGE_CLASS_NONE;
4756 declaration->storage_class = STORAGE_CLASS_NONE;
4757 declaration->source_position = source_position;
4758 declaration->modifiers = specifiers->modifiers;
4759 declaration->type = type;
4761 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
4763 type_t *orig_type = declaration->type;
4764 type_t *type = skip_typeref(orig_type);
4766 if (token.type == ':') {
4767 source_position_t source_position = *HERE;
4769 expression_t *size = parse_constant_expression();
4771 if (!is_type_integer(type)) {
4772 errorf(HERE, "bitfield base type '%T' is not an "
4773 "integer type", orig_type);
4776 type_t *bitfield_type = make_bitfield_type(orig_type, size, &source_position);
4777 declaration->type = bitfield_type;
4779 /* TODO we ignore arrays for now... what is missing is a check
4780 * that they're at the end of the struct */
4781 if (is_type_incomplete(type) && !is_type_array(type)) {
4783 "compound member '%Y' has incomplete type '%T'",
4784 declaration->symbol, orig_type);
4785 } else if (is_type_function(type)) {
4786 errorf(HERE, "compound member '%Y' must not have function "
4787 "type '%T'", declaration->symbol, orig_type);
4792 /* make sure we don't define a symbol multiple times */
4793 symbol_t *symbol = declaration->symbol;
4794 if (symbol != NULL) {
4795 declaration_t *prev_decl
4796 = find_compound_entry(struct_declaration, symbol);
4798 if (prev_decl != NULL) {
4799 assert(prev_decl->symbol == symbol);
4800 errorf(&declaration->source_position,
4801 "multiple declarations of symbol '%Y' (declared %P)",
4802 symbol, &prev_decl->source_position);
4806 /* append declaration */
4807 if (last_declaration != NULL) {
4808 last_declaration->next = declaration;
4810 struct_declaration->scope.declarations = declaration;
4812 last_declaration = declaration;
4814 if (token.type != ',')
4824 static void parse_compound_type_entries(declaration_t *compound_declaration)
4827 add_anchor_token('}');
4829 while(token.type != '}' && token.type != T_EOF) {
4830 declaration_specifiers_t specifiers;
4831 memset(&specifiers, 0, sizeof(specifiers));
4832 parse_declaration_specifiers(&specifiers);
4834 parse_compound_declarators(compound_declaration, &specifiers);
4836 rem_anchor_token('}');
4838 if (token.type == T_EOF) {
4839 errorf(HERE, "EOF while parsing struct");
4844 static type_t *parse_typename(void)
4846 declaration_specifiers_t specifiers;
4847 memset(&specifiers, 0, sizeof(specifiers));
4848 parse_declaration_specifiers(&specifiers);
4849 if (specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
4850 /* TODO: improve error message, user does probably not know what a
4851 * storage class is...
4853 errorf(HERE, "typename may not have a storage class");
4856 type_t *result = parse_abstract_declarator(specifiers.type);
4864 typedef expression_t* (*parse_expression_function) (unsigned precedence);
4865 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
4866 expression_t *left);
4868 typedef struct expression_parser_function_t expression_parser_function_t;
4869 struct expression_parser_function_t {
4870 unsigned precedence;
4871 parse_expression_function parser;
4872 unsigned infix_precedence;
4873 parse_expression_infix_function infix_parser;
4876 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
4879 * Prints an error message if an expression was expected but not read
4881 static expression_t *expected_expression_error(void)
4883 /* skip the error message if the error token was read */
4884 if (token.type != T_ERROR) {
4885 errorf(HERE, "expected expression, got token '%K'", &token);
4889 return create_invalid_expression();
4893 * Parse a string constant.
4895 static expression_t *parse_string_const(void)
4898 if (token.type == T_STRING_LITERAL) {
4899 string_t res = token.v.string;
4901 while (token.type == T_STRING_LITERAL) {
4902 res = concat_strings(&res, &token.v.string);
4905 if (token.type != T_WIDE_STRING_LITERAL) {
4906 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
4907 /* note: that we use type_char_ptr here, which is already the
4908 * automatic converted type. revert_automatic_type_conversion
4909 * will construct the array type */
4910 cnst->base.type = type_char_ptr;
4911 cnst->string.value = res;
4915 wres = concat_string_wide_string(&res, &token.v.wide_string);
4917 wres = token.v.wide_string;
4922 switch (token.type) {
4923 case T_WIDE_STRING_LITERAL:
4924 wres = concat_wide_strings(&wres, &token.v.wide_string);
4927 case T_STRING_LITERAL:
4928 wres = concat_wide_string_string(&wres, &token.v.string);
4932 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
4933 cnst->base.type = type_wchar_t_ptr;
4934 cnst->wide_string.value = wres;
4943 * Parse an integer constant.
4945 static expression_t *parse_int_const(void)
4947 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
4948 cnst->base.source_position = *HERE;
4949 cnst->base.type = token.datatype;
4950 cnst->conste.v.int_value = token.v.intvalue;
4958 * Parse a character constant.
4960 static expression_t *parse_character_constant(void)
4962 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
4964 cnst->base.source_position = *HERE;
4965 cnst->base.type = token.datatype;
4966 cnst->conste.v.character = token.v.string;
4968 if (cnst->conste.v.character.size != 1) {
4969 if (warning.multichar && (c_mode & _GNUC)) {
4971 warningf(HERE, "multi-character character constant");
4973 errorf(HERE, "more than 1 characters in character constant");
4982 * Parse a wide character constant.
4984 static expression_t *parse_wide_character_constant(void)
4986 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
4988 cnst->base.source_position = *HERE;
4989 cnst->base.type = token.datatype;
4990 cnst->conste.v.wide_character = token.v.wide_string;
4992 if (cnst->conste.v.wide_character.size != 1) {
4993 if (warning.multichar && (c_mode & _GNUC)) {
4995 warningf(HERE, "multi-character character constant");
4997 errorf(HERE, "more than 1 characters in character constant");
5006 * Parse a float constant.
5008 static expression_t *parse_float_const(void)
5010 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5011 cnst->base.type = token.datatype;
5012 cnst->conste.v.float_value = token.v.floatvalue;
5019 static declaration_t *create_implicit_function(symbol_t *symbol,
5020 const source_position_t *source_position)
5022 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
5023 ntype->function.return_type = type_int;
5024 ntype->function.unspecified_parameters = true;
5026 type_t *type = typehash_insert(ntype);
5027 if (type != ntype) {
5031 declaration_t *const declaration = allocate_declaration_zero();
5032 declaration->storage_class = STORAGE_CLASS_EXTERN;
5033 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
5034 declaration->type = type;
5035 declaration->symbol = symbol;
5036 declaration->source_position = *source_position;
5038 bool strict_prototypes_old = warning.strict_prototypes;
5039 warning.strict_prototypes = false;
5040 record_declaration(declaration);
5041 warning.strict_prototypes = strict_prototypes_old;
5047 * Creates a return_type (func)(argument_type) function type if not
5050 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
5051 type_t *argument_type2)
5053 function_parameter_t *parameter2
5054 = obstack_alloc(type_obst, sizeof(parameter2[0]));
5055 memset(parameter2, 0, sizeof(parameter2[0]));
5056 parameter2->type = argument_type2;
5058 function_parameter_t *parameter1
5059 = obstack_alloc(type_obst, sizeof(parameter1[0]));
5060 memset(parameter1, 0, sizeof(parameter1[0]));
5061 parameter1->type = argument_type1;
5062 parameter1->next = parameter2;
5064 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5065 type->function.return_type = return_type;
5066 type->function.parameters = parameter1;
5068 type_t *result = typehash_insert(type);
5069 if (result != type) {
5077 * Creates a return_type (func)(argument_type) function type if not
5080 * @param return_type the return type
5081 * @param argument_type the argument type
5083 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
5085 function_parameter_t *parameter
5086 = obstack_alloc(type_obst, sizeof(parameter[0]));
5087 memset(parameter, 0, sizeof(parameter[0]));
5088 parameter->type = argument_type;
5090 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5091 type->function.return_type = return_type;
5092 type->function.parameters = parameter;
5094 type_t *result = typehash_insert(type);
5095 if (result != type) {
5102 static type_t *make_function_0_type(type_t *return_type)
5104 type_t *type = allocate_type_zero(TYPE_FUNCTION, &builtin_source_position);
5105 type->function.return_type = return_type;
5106 type->function.parameters = NULL;
5108 type_t *result = typehash_insert(type);
5109 if (result != type) {
5117 * Creates a function type for some function like builtins.
5119 * @param symbol the symbol describing the builtin
5121 static type_t *get_builtin_symbol_type(symbol_t *symbol)
5123 switch(symbol->ID) {
5124 case T___builtin_alloca:
5125 return make_function_1_type(type_void_ptr, type_size_t);
5126 case T___builtin_huge_val:
5127 return make_function_0_type(type_double);
5128 case T___builtin_nan:
5129 return make_function_1_type(type_double, type_char_ptr);
5130 case T___builtin_nanf:
5131 return make_function_1_type(type_float, type_char_ptr);
5132 case T___builtin_nand:
5133 return make_function_1_type(type_long_double, type_char_ptr);
5134 case T___builtin_va_end:
5135 return make_function_1_type(type_void, type_valist);
5136 case T___builtin_expect:
5137 return make_function_2_type(type_long, type_long, type_long);
5139 internal_errorf(HERE, "not implemented builtin symbol found");
5144 * Performs automatic type cast as described in § 6.3.2.1.
5146 * @param orig_type the original type
5148 static type_t *automatic_type_conversion(type_t *orig_type)
5150 type_t *type = skip_typeref(orig_type);
5151 if (is_type_array(type)) {
5152 array_type_t *array_type = &type->array;
5153 type_t *element_type = array_type->element_type;
5154 unsigned qualifiers = array_type->base.qualifiers;
5156 return make_pointer_type(element_type, qualifiers);
5159 if (is_type_function(type)) {
5160 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5167 * reverts the automatic casts of array to pointer types and function
5168 * to function-pointer types as defined § 6.3.2.1
5170 type_t *revert_automatic_type_conversion(const expression_t *expression)
5172 switch (expression->kind) {
5173 case EXPR_REFERENCE: return expression->reference.declaration->type;
5174 case EXPR_SELECT: return expression->select.compound_entry->type;
5176 case EXPR_UNARY_DEREFERENCE: {
5177 const expression_t *const value = expression->unary.value;
5178 type_t *const type = skip_typeref(value->base.type);
5179 assert(is_type_pointer(type));
5180 return type->pointer.points_to;
5183 case EXPR_BUILTIN_SYMBOL:
5184 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
5186 case EXPR_ARRAY_ACCESS: {
5187 const expression_t *array_ref = expression->array_access.array_ref;
5188 type_t *type_left = skip_typeref(array_ref->base.type);
5189 if (!is_type_valid(type_left))
5191 assert(is_type_pointer(type_left));
5192 return type_left->pointer.points_to;
5195 case EXPR_STRING_LITERAL: {
5196 size_t size = expression->string.value.size;
5197 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
5200 case EXPR_WIDE_STRING_LITERAL: {
5201 size_t size = expression->wide_string.value.size;
5202 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
5205 case EXPR_COMPOUND_LITERAL:
5206 return expression->compound_literal.type;
5211 return expression->base.type;
5214 static expression_t *parse_reference(void)
5216 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
5218 reference_expression_t *ref = &expression->reference;
5219 symbol_t *const symbol = token.v.symbol;
5221 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
5223 source_position_t source_position = token.source_position;
5226 if (declaration == NULL) {
5227 if (! strict_mode && token.type == '(') {
5228 /* an implicitly defined function */
5229 if (warning.implicit_function_declaration) {
5230 warningf(HERE, "implicit declaration of function '%Y'",
5234 declaration = create_implicit_function(symbol,
5237 errorf(HERE, "unknown symbol '%Y' found.", symbol);
5238 return create_invalid_expression();
5242 type_t *type = declaration->type;
5244 /* we always do the auto-type conversions; the & and sizeof parser contains
5245 * code to revert this! */
5246 type = automatic_type_conversion(type);
5248 ref->declaration = declaration;
5249 ref->base.type = type;
5251 /* this declaration is used */
5252 declaration->used = true;
5254 /* check for deprecated functions */
5255 if (declaration->deprecated != 0) {
5256 const char *prefix = "";
5257 if (is_type_function(declaration->type))
5258 prefix = "function ";
5260 if (declaration->deprecated_string != NULL) {
5261 warningf(&source_position,
5262 "%s'%Y' was declared 'deprecated(\"%s\")'", prefix, declaration->symbol,
5263 declaration->deprecated_string);
5265 warningf(&source_position,
5266 "%s'%Y' was declared 'deprecated'", prefix, declaration->symbol);
5273 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
5277 /* TODO check if explicit cast is allowed and issue warnings/errors */
5280 static expression_t *parse_compound_literal(type_t *type)
5282 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
5284 parse_initializer_env_t env;
5286 env.declaration = NULL;
5287 env.must_be_constant = false;
5288 initializer_t *initializer = parse_initializer(&env);
5291 expression->compound_literal.initializer = initializer;
5292 expression->compound_literal.type = type;
5293 expression->base.type = automatic_type_conversion(type);
5299 * Parse a cast expression.
5301 static expression_t *parse_cast(void)
5303 source_position_t source_position = token.source_position;
5305 type_t *type = parse_typename();
5307 /* matching add_anchor_token() is at call site */
5308 rem_anchor_token(')');
5311 if (token.type == '{') {
5312 return parse_compound_literal(type);
5315 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
5316 cast->base.source_position = source_position;
5318 expression_t *value = parse_sub_expression(20);
5320 check_cast_allowed(value, type);
5322 cast->base.type = type;
5323 cast->unary.value = value;
5327 return create_invalid_expression();
5331 * Parse a statement expression.
5333 static expression_t *parse_statement_expression(void)
5335 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
5337 statement_t *statement = parse_compound_statement(true);
5338 expression->statement.statement = statement;
5339 expression->base.source_position = statement->base.source_position;
5341 /* find last statement and use its type */
5342 type_t *type = type_void;
5343 const statement_t *stmt = statement->compound.statements;
5345 while (stmt->base.next != NULL)
5346 stmt = stmt->base.next;
5348 if (stmt->kind == STATEMENT_EXPRESSION) {
5349 type = stmt->expression.expression->base.type;
5352 warningf(&expression->base.source_position, "empty statement expression ({})");
5354 expression->base.type = type;
5360 return create_invalid_expression();
5364 * Parse a braced expression.
5366 static expression_t *parse_brace_expression(void)
5369 add_anchor_token(')');
5371 switch(token.type) {
5373 /* gcc extension: a statement expression */
5374 return parse_statement_expression();
5378 return parse_cast();
5380 if (is_typedef_symbol(token.v.symbol)) {
5381 return parse_cast();
5385 expression_t *result = parse_expression();
5386 rem_anchor_token(')');
5391 return create_invalid_expression();
5394 static expression_t *parse_function_keyword(void)
5399 if (current_function == NULL) {
5400 errorf(HERE, "'__func__' used outside of a function");
5403 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5404 expression->base.type = type_char_ptr;
5405 expression->funcname.kind = FUNCNAME_FUNCTION;
5410 static expression_t *parse_pretty_function_keyword(void)
5412 eat(T___PRETTY_FUNCTION__);
5414 if (current_function == NULL) {
5415 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
5418 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5419 expression->base.type = type_char_ptr;
5420 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
5425 static expression_t *parse_funcsig_keyword(void)
5429 if (current_function == NULL) {
5430 errorf(HERE, "'__FUNCSIG__' used outside of a function");
5433 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5434 expression->base.type = type_char_ptr;
5435 expression->funcname.kind = FUNCNAME_FUNCSIG;
5440 static expression_t *parse_funcdname_keyword(void)
5442 eat(T___FUNCDNAME__);
5444 if (current_function == NULL) {
5445 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
5448 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
5449 expression->base.type = type_char_ptr;
5450 expression->funcname.kind = FUNCNAME_FUNCDNAME;
5455 static designator_t *parse_designator(void)
5457 designator_t *result = allocate_ast_zero(sizeof(result[0]));
5458 result->source_position = *HERE;
5460 if (token.type != T_IDENTIFIER) {
5461 parse_error_expected("while parsing member designator",
5462 T_IDENTIFIER, NULL);
5465 result->symbol = token.v.symbol;
5468 designator_t *last_designator = result;
5470 if (token.type == '.') {
5472 if (token.type != T_IDENTIFIER) {
5473 parse_error_expected("while parsing member designator",
5474 T_IDENTIFIER, NULL);
5477 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5478 designator->source_position = *HERE;
5479 designator->symbol = token.v.symbol;
5482 last_designator->next = designator;
5483 last_designator = designator;
5486 if (token.type == '[') {
5488 add_anchor_token(']');
5489 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
5490 designator->source_position = *HERE;
5491 designator->array_index = parse_expression();
5492 rem_anchor_token(']');
5494 if (designator->array_index == NULL) {
5498 last_designator->next = designator;
5499 last_designator = designator;
5511 * Parse the __builtin_offsetof() expression.
5513 static expression_t *parse_offsetof(void)
5515 eat(T___builtin_offsetof);
5517 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
5518 expression->base.type = type_size_t;
5521 add_anchor_token(',');
5522 type_t *type = parse_typename();
5523 rem_anchor_token(',');
5525 add_anchor_token(')');
5526 designator_t *designator = parse_designator();
5527 rem_anchor_token(')');
5530 expression->offsetofe.type = type;
5531 expression->offsetofe.designator = designator;
5534 memset(&path, 0, sizeof(path));
5535 path.top_type = type;
5536 path.path = NEW_ARR_F(type_path_entry_t, 0);
5538 descend_into_subtype(&path);
5540 if (!walk_designator(&path, designator, true)) {
5541 return create_invalid_expression();
5544 DEL_ARR_F(path.path);
5548 return create_invalid_expression();
5552 * Parses a _builtin_va_start() expression.
5554 static expression_t *parse_va_start(void)
5556 eat(T___builtin_va_start);
5558 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
5561 add_anchor_token(',');
5562 expression->va_starte.ap = parse_assignment_expression();
5563 rem_anchor_token(',');
5565 expression_t *const expr = parse_assignment_expression();
5566 if (expr->kind == EXPR_REFERENCE) {
5567 declaration_t *const decl = expr->reference.declaration;
5569 return create_invalid_expression();
5570 if (decl->parent_scope == ¤t_function->scope &&
5571 decl->next == NULL) {
5572 expression->va_starte.parameter = decl;
5577 errorf(&expr->base.source_position,
5578 "second argument of 'va_start' must be last parameter of the current function");
5580 return create_invalid_expression();
5584 * Parses a _builtin_va_arg() expression.
5586 static expression_t *parse_va_arg(void)
5588 eat(T___builtin_va_arg);
5590 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
5593 expression->va_arge.ap = parse_assignment_expression();
5595 expression->base.type = parse_typename();
5600 return create_invalid_expression();
5603 static expression_t *parse_builtin_symbol(void)
5605 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
5607 symbol_t *symbol = token.v.symbol;
5609 expression->builtin_symbol.symbol = symbol;
5612 type_t *type = get_builtin_symbol_type(symbol);
5613 type = automatic_type_conversion(type);
5615 expression->base.type = type;
5620 * Parses a __builtin_constant() expression.
5622 static expression_t *parse_builtin_constant(void)
5624 eat(T___builtin_constant_p);
5626 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
5629 add_anchor_token(')');
5630 expression->builtin_constant.value = parse_assignment_expression();
5631 rem_anchor_token(')');
5633 expression->base.type = type_int;
5637 return create_invalid_expression();
5641 * Parses a __builtin_prefetch() expression.
5643 static expression_t *parse_builtin_prefetch(void)
5645 eat(T___builtin_prefetch);
5647 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
5650 add_anchor_token(')');
5651 expression->builtin_prefetch.adr = parse_assignment_expression();
5652 if (token.type == ',') {
5654 expression->builtin_prefetch.rw = parse_assignment_expression();
5656 if (token.type == ',') {
5658 expression->builtin_prefetch.locality = parse_assignment_expression();
5660 rem_anchor_token(')');
5662 expression->base.type = type_void;
5666 return create_invalid_expression();
5670 * Parses a __builtin_is_*() compare expression.
5672 static expression_t *parse_compare_builtin(void)
5674 expression_t *expression;
5676 switch(token.type) {
5677 case T___builtin_isgreater:
5678 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
5680 case T___builtin_isgreaterequal:
5681 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
5683 case T___builtin_isless:
5684 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
5686 case T___builtin_islessequal:
5687 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
5689 case T___builtin_islessgreater:
5690 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
5692 case T___builtin_isunordered:
5693 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
5696 internal_errorf(HERE, "invalid compare builtin found");
5699 expression->base.source_position = *HERE;
5703 expression->binary.left = parse_assignment_expression();
5705 expression->binary.right = parse_assignment_expression();
5708 type_t *const orig_type_left = expression->binary.left->base.type;
5709 type_t *const orig_type_right = expression->binary.right->base.type;
5711 type_t *const type_left = skip_typeref(orig_type_left);
5712 type_t *const type_right = skip_typeref(orig_type_right);
5713 if (!is_type_float(type_left) && !is_type_float(type_right)) {
5714 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5715 type_error_incompatible("invalid operands in comparison",
5716 &expression->base.source_position, orig_type_left, orig_type_right);
5719 semantic_comparison(&expression->binary);
5724 return create_invalid_expression();
5729 * Parses a __builtin_expect() expression.
5731 static expression_t *parse_builtin_expect(void)
5733 eat(T___builtin_expect);
5735 expression_t *expression
5736 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
5739 expression->binary.left = parse_assignment_expression();
5741 expression->binary.right = parse_constant_expression();
5744 expression->base.type = expression->binary.left->base.type;
5748 return create_invalid_expression();
5753 * Parses a MS assume() expression.
5755 static expression_t *parse_assume(void) {
5758 expression_t *expression
5759 = allocate_expression_zero(EXPR_UNARY_ASSUME);
5762 add_anchor_token(')');
5763 expression->unary.value = parse_assignment_expression();
5764 rem_anchor_token(')');
5767 expression->base.type = type_void;
5770 return create_invalid_expression();
5774 * Parse a microsoft __noop expression.
5776 static expression_t *parse_noop_expression(void) {
5777 source_position_t source_position = *HERE;
5780 if (token.type == '(') {
5781 /* parse arguments */
5783 add_anchor_token(')');
5784 add_anchor_token(',');
5786 if (token.type != ')') {
5788 (void)parse_assignment_expression();
5789 if (token.type != ',')
5795 rem_anchor_token(',');
5796 rem_anchor_token(')');
5799 /* the result is a (int)0 */
5800 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
5801 cnst->base.source_position = source_position;
5802 cnst->base.type = type_int;
5803 cnst->conste.v.int_value = 0;
5804 cnst->conste.is_ms_noop = true;
5809 return create_invalid_expression();
5813 * Parses a primary expression.
5815 static expression_t *parse_primary_expression(void)
5817 switch (token.type) {
5818 case T_INTEGER: return parse_int_const();
5819 case T_CHARACTER_CONSTANT: return parse_character_constant();
5820 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
5821 case T_FLOATINGPOINT: return parse_float_const();
5822 case T_STRING_LITERAL:
5823 case T_WIDE_STRING_LITERAL: return parse_string_const();
5824 case T_IDENTIFIER: return parse_reference();
5825 case T___FUNCTION__:
5826 case T___func__: return parse_function_keyword();
5827 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
5828 case T___FUNCSIG__: return parse_funcsig_keyword();
5829 case T___FUNCDNAME__: return parse_funcdname_keyword();
5830 case T___builtin_offsetof: return parse_offsetof();
5831 case T___builtin_va_start: return parse_va_start();
5832 case T___builtin_va_arg: return parse_va_arg();
5833 case T___builtin_expect:
5834 case T___builtin_alloca:
5835 case T___builtin_nan:
5836 case T___builtin_nand:
5837 case T___builtin_nanf:
5838 case T___builtin_huge_val:
5839 case T___builtin_va_end: return parse_builtin_symbol();
5840 case T___builtin_isgreater:
5841 case T___builtin_isgreaterequal:
5842 case T___builtin_isless:
5843 case T___builtin_islessequal:
5844 case T___builtin_islessgreater:
5845 case T___builtin_isunordered: return parse_compare_builtin();
5846 case T___builtin_constant_p: return parse_builtin_constant();
5847 case T___builtin_prefetch: return parse_builtin_prefetch();
5848 case T__assume: return parse_assume();
5850 case '(': return parse_brace_expression();
5851 case T___noop: return parse_noop_expression();
5854 errorf(HERE, "unexpected token %K, expected an expression", &token);
5855 return create_invalid_expression();
5859 * Check if the expression has the character type and issue a warning then.
5861 static void check_for_char_index_type(const expression_t *expression) {
5862 type_t *const type = expression->base.type;
5863 const type_t *const base_type = skip_typeref(type);
5865 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
5866 warning.char_subscripts) {
5867 warningf(&expression->base.source_position,
5868 "array subscript has type '%T'", type);
5872 static expression_t *parse_array_expression(unsigned precedence,
5878 add_anchor_token(']');
5880 expression_t *inside = parse_expression();
5882 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
5884 array_access_expression_t *array_access = &expression->array_access;
5886 type_t *const orig_type_left = left->base.type;
5887 type_t *const orig_type_inside = inside->base.type;
5889 type_t *const type_left = skip_typeref(orig_type_left);
5890 type_t *const type_inside = skip_typeref(orig_type_inside);
5892 type_t *return_type;
5893 if (is_type_pointer(type_left)) {
5894 return_type = type_left->pointer.points_to;
5895 array_access->array_ref = left;
5896 array_access->index = inside;
5897 check_for_char_index_type(inside);
5898 } else if (is_type_pointer(type_inside)) {
5899 return_type = type_inside->pointer.points_to;
5900 array_access->array_ref = inside;
5901 array_access->index = left;
5902 array_access->flipped = true;
5903 check_for_char_index_type(left);
5905 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
5907 "array access on object with non-pointer types '%T', '%T'",
5908 orig_type_left, orig_type_inside);
5910 return_type = type_error_type;
5911 array_access->array_ref = create_invalid_expression();
5914 rem_anchor_token(']');
5915 if (token.type != ']') {
5916 parse_error_expected("Problem while parsing array access", ']', NULL);
5921 return_type = automatic_type_conversion(return_type);
5922 expression->base.type = return_type;
5927 static expression_t *parse_typeprop(expression_kind_t const kind,
5928 source_position_t const pos,
5929 unsigned const precedence)
5931 expression_t *tp_expression = allocate_expression_zero(kind);
5932 tp_expression->base.type = type_size_t;
5933 tp_expression->base.source_position = pos;
5935 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
5937 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
5939 add_anchor_token(')');
5940 type_t* const orig_type = parse_typename();
5941 tp_expression->typeprop.type = orig_type;
5943 type_t const* const type = skip_typeref(orig_type);
5944 char const* const wrong_type =
5945 is_type_incomplete(type) ? "incomplete" :
5946 type->kind == TYPE_FUNCTION ? "function designator" :
5947 type->kind == TYPE_BITFIELD ? "bitfield" :
5949 if (wrong_type != NULL) {
5950 errorf(&pos, "operand of %s expression must not be %s type '%T'",
5951 what, wrong_type, type);
5954 rem_anchor_token(')');
5957 expression_t *expression = parse_sub_expression(precedence);
5959 type_t* const orig_type = revert_automatic_type_conversion(expression);
5960 expression->base.type = orig_type;
5962 type_t const* const type = skip_typeref(orig_type);
5963 char const* const wrong_type =
5964 is_type_incomplete(type) ? "incomplete" :
5965 type->kind == TYPE_FUNCTION ? "function designator" :
5966 type->kind == TYPE_BITFIELD ? "bitfield" :
5968 if (wrong_type != NULL) {
5969 errorf(&pos, "operand of %s expression must not be expression of %s type '%T'", what, wrong_type, type);
5972 tp_expression->typeprop.type = expression->base.type;
5973 tp_expression->typeprop.tp_expression = expression;
5976 return tp_expression;
5978 return create_invalid_expression();
5981 static expression_t *parse_sizeof(unsigned precedence)
5983 source_position_t pos = *HERE;
5985 return parse_typeprop(EXPR_SIZEOF, pos, precedence);
5988 static expression_t *parse_alignof(unsigned precedence)
5990 source_position_t pos = *HERE;
5992 return parse_typeprop(EXPR_ALIGNOF, pos, precedence);
5995 static expression_t *parse_select_expression(unsigned precedence,
5996 expression_t *compound)
5999 assert(token.type == '.' || token.type == T_MINUSGREATER);
6001 bool is_pointer = (token.type == T_MINUSGREATER);
6004 expression_t *select = allocate_expression_zero(EXPR_SELECT);
6005 select->select.compound = compound;
6007 if (token.type != T_IDENTIFIER) {
6008 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
6011 symbol_t *symbol = token.v.symbol;
6012 select->select.symbol = symbol;
6015 type_t *const orig_type = compound->base.type;
6016 type_t *const type = skip_typeref(orig_type);
6018 type_t *type_left = type;
6020 if (!is_type_pointer(type)) {
6021 if (is_type_valid(type)) {
6022 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6024 return create_invalid_expression();
6026 type_left = type->pointer.points_to;
6028 type_left = skip_typeref(type_left);
6030 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
6031 type_left->kind != TYPE_COMPOUND_UNION) {
6032 if (is_type_valid(type_left)) {
6033 errorf(HERE, "request for member '%Y' in something not a struct or "
6034 "union, but '%T'", symbol, type_left);
6036 return create_invalid_expression();
6039 declaration_t *const declaration = type_left->compound.declaration;
6041 if (!declaration->init.complete) {
6042 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
6044 return create_invalid_expression();
6047 declaration_t *iter = find_compound_entry(declaration, symbol);
6049 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
6050 return create_invalid_expression();
6053 /* we always do the auto-type conversions; the & and sizeof parser contains
6054 * code to revert this! */
6055 type_t *expression_type = automatic_type_conversion(iter->type);
6057 select->select.compound_entry = iter;
6058 select->base.type = expression_type;
6060 type_t *skipped = skip_typeref(iter->type);
6061 if (skipped->kind == TYPE_BITFIELD) {
6062 select->base.type = skipped->bitfield.base_type;
6068 static void check_call_argument(const function_parameter_t *parameter,
6069 call_argument_t *argument)
6071 type_t *expected_type = parameter->type;
6072 type_t *expected_type_skip = skip_typeref(expected_type);
6073 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6074 expression_t *arg_expr = argument->expression;
6076 /* handle transparent union gnu extension */
6077 if (is_type_union(expected_type_skip)
6078 && (expected_type_skip->base.modifiers
6079 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
6080 declaration_t *union_decl = expected_type_skip->compound.declaration;
6082 declaration_t *declaration = union_decl->scope.declarations;
6083 type_t *best_type = NULL;
6084 for ( ; declaration != NULL; declaration = declaration->next) {
6085 type_t *decl_type = declaration->type;
6086 error = semantic_assign(decl_type, arg_expr);
6087 if (error == ASSIGN_ERROR_INCOMPATIBLE
6088 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6091 if (error == ASSIGN_SUCCESS) {
6092 best_type = decl_type;
6093 } else if (best_type == NULL) {
6094 best_type = decl_type;
6098 if (best_type != NULL) {
6099 expected_type = best_type;
6103 error = semantic_assign(expected_type, arg_expr);
6104 argument->expression = create_implicit_cast(argument->expression,
6107 /* TODO report exact scope in error messages (like "in 3rd parameter") */
6108 report_assign_error(error, expected_type, arg_expr, "function call",
6109 &arg_expr->base.source_position);
6113 * Parse a call expression, ie. expression '( ... )'.
6115 * @param expression the function address
6117 static expression_t *parse_call_expression(unsigned precedence,
6118 expression_t *expression)
6121 expression_t *result = allocate_expression_zero(EXPR_CALL);
6122 result->base.source_position = expression->base.source_position;
6124 call_expression_t *call = &result->call;
6125 call->function = expression;
6127 type_t *const orig_type = expression->base.type;
6128 type_t *const type = skip_typeref(orig_type);
6130 function_type_t *function_type = NULL;
6131 if (is_type_pointer(type)) {
6132 type_t *const to_type = skip_typeref(type->pointer.points_to);
6134 if (is_type_function(to_type)) {
6135 function_type = &to_type->function;
6136 call->base.type = function_type->return_type;
6140 if (function_type == NULL && is_type_valid(type)) {
6141 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
6144 /* parse arguments */
6146 add_anchor_token(')');
6147 add_anchor_token(',');
6149 if (token.type != ')') {
6150 call_argument_t *last_argument = NULL;
6153 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
6155 argument->expression = parse_assignment_expression();
6156 if (last_argument == NULL) {
6157 call->arguments = argument;
6159 last_argument->next = argument;
6161 last_argument = argument;
6163 if (token.type != ',')
6168 rem_anchor_token(',');
6169 rem_anchor_token(')');
6172 if (function_type == NULL)
6175 function_parameter_t *parameter = function_type->parameters;
6176 call_argument_t *argument = call->arguments;
6177 if (!function_type->unspecified_parameters) {
6178 for( ; parameter != NULL && argument != NULL;
6179 parameter = parameter->next, argument = argument->next) {
6180 check_call_argument(parameter, argument);
6183 if (parameter != NULL) {
6184 errorf(HERE, "too few arguments to function '%E'", expression);
6185 } else if (argument != NULL && !function_type->variadic) {
6186 errorf(HERE, "too many arguments to function '%E'", expression);
6190 /* do default promotion */
6191 for( ; argument != NULL; argument = argument->next) {
6192 type_t *type = argument->expression->base.type;
6194 type = get_default_promoted_type(type);
6196 argument->expression
6197 = create_implicit_cast(argument->expression, type);
6200 check_format(&result->call);
6204 return create_invalid_expression();
6207 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
6209 static bool same_compound_type(const type_t *type1, const type_t *type2)
6212 is_type_compound(type1) &&
6213 type1->kind == type2->kind &&
6214 type1->compound.declaration == type2->compound.declaration;
6218 * Parse a conditional expression, ie. 'expression ? ... : ...'.
6220 * @param expression the conditional expression
6222 static expression_t *parse_conditional_expression(unsigned precedence,
6223 expression_t *expression)
6226 add_anchor_token(':');
6228 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
6230 conditional_expression_t *conditional = &result->conditional;
6231 conditional->condition = expression;
6234 type_t *const condition_type_orig = expression->base.type;
6235 type_t *const condition_type = skip_typeref(condition_type_orig);
6236 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
6237 type_error("expected a scalar type in conditional condition",
6238 &expression->base.source_position, condition_type_orig);
6241 expression_t *true_expression = parse_expression();
6242 rem_anchor_token(':');
6244 expression_t *false_expression = parse_sub_expression(precedence);
6246 type_t *const orig_true_type = true_expression->base.type;
6247 type_t *const orig_false_type = false_expression->base.type;
6248 type_t *const true_type = skip_typeref(orig_true_type);
6249 type_t *const false_type = skip_typeref(orig_false_type);
6252 type_t *result_type;
6253 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
6254 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6255 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID)
6256 || !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
6257 warningf(&expression->base.source_position,
6258 "ISO C forbids conditional expression with only one void side");
6260 result_type = type_void;
6261 } else if (is_type_arithmetic(true_type)
6262 && is_type_arithmetic(false_type)) {
6263 result_type = semantic_arithmetic(true_type, false_type);
6265 true_expression = create_implicit_cast(true_expression, result_type);
6266 false_expression = create_implicit_cast(false_expression, result_type);
6268 conditional->true_expression = true_expression;
6269 conditional->false_expression = false_expression;
6270 conditional->base.type = result_type;
6271 } else if (same_compound_type(true_type, false_type)) {
6272 /* just take 1 of the 2 types */
6273 result_type = true_type;
6274 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
6275 type_t *pointer_type;
6277 expression_t *other_expression;
6278 if (is_type_pointer(true_type) &&
6279 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
6280 pointer_type = true_type;
6281 other_type = false_type;
6282 other_expression = false_expression;
6284 pointer_type = false_type;
6285 other_type = true_type;
6286 other_expression = true_expression;
6289 if (is_null_pointer_constant(other_expression)) {
6290 result_type = pointer_type;
6291 } else if (is_type_pointer(other_type)) {
6292 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
6293 type_t *to2 = skip_typeref(other_type->pointer.points_to);
6296 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
6297 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
6299 } else if (types_compatible(get_unqualified_type(to1),
6300 get_unqualified_type(to2))) {
6303 warningf(&expression->base.source_position,
6304 "pointer types '%T' and '%T' in conditional expression are incompatible",
6305 true_type, false_type);
6309 type_t *const copy = duplicate_type(to);
6310 copy->base.qualifiers = to1->base.qualifiers | to2->base.qualifiers;
6312 type_t *const type = typehash_insert(copy);
6316 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
6317 } else if (is_type_integer(other_type)) {
6318 warningf(&expression->base.source_position,
6319 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
6320 result_type = pointer_type;
6322 type_error_incompatible("while parsing conditional",
6323 &expression->base.source_position, true_type, false_type);
6324 result_type = type_error_type;
6327 /* TODO: one pointer to void*, other some pointer */
6329 if (is_type_valid(true_type) && is_type_valid(false_type)) {
6330 type_error_incompatible("while parsing conditional",
6331 &expression->base.source_position, true_type,
6334 result_type = type_error_type;
6337 conditional->true_expression
6338 = create_implicit_cast(true_expression, result_type);
6339 conditional->false_expression
6340 = create_implicit_cast(false_expression, result_type);
6341 conditional->base.type = result_type;
6344 return create_invalid_expression();
6348 * Parse an extension expression.
6350 static expression_t *parse_extension(unsigned precedence)
6352 eat(T___extension__);
6354 /* TODO enable extensions */
6355 expression_t *expression = parse_sub_expression(precedence);
6356 /* TODO disable extensions */
6361 * Parse a __builtin_classify_type() expression.
6363 static expression_t *parse_builtin_classify_type(const unsigned precedence)
6365 eat(T___builtin_classify_type);
6367 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
6368 result->base.type = type_int;
6371 add_anchor_token(')');
6372 expression_t *expression = parse_sub_expression(precedence);
6373 rem_anchor_token(')');
6375 result->classify_type.type_expression = expression;
6379 return create_invalid_expression();
6382 static void check_pointer_arithmetic(const source_position_t *source_position,
6383 type_t *pointer_type,
6384 type_t *orig_pointer_type)
6386 type_t *points_to = pointer_type->pointer.points_to;
6387 points_to = skip_typeref(points_to);
6389 if (is_type_incomplete(points_to) &&
6391 || !is_type_atomic(points_to, ATOMIC_TYPE_VOID))) {
6392 errorf(source_position,
6393 "arithmetic with pointer to incomplete type '%T' not allowed",
6395 } else if (is_type_function(points_to)) {
6396 errorf(source_position,
6397 "arithmetic with pointer to function type '%T' not allowed",
6402 static void semantic_incdec(unary_expression_t *expression)
6404 type_t *const orig_type = expression->value->base.type;
6405 type_t *const type = skip_typeref(orig_type);
6406 if (is_type_pointer(type)) {
6407 check_pointer_arithmetic(&expression->base.source_position,
6409 } else if (!is_type_real(type) && is_type_valid(type)) {
6410 /* TODO: improve error message */
6411 errorf(HERE, "operation needs an arithmetic or pointer type");
6413 expression->base.type = orig_type;
6416 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
6418 type_t *const orig_type = expression->value->base.type;
6419 type_t *const type = skip_typeref(orig_type);
6420 if (!is_type_arithmetic(type)) {
6421 if (is_type_valid(type)) {
6422 /* TODO: improve error message */
6423 errorf(HERE, "operation needs an arithmetic type");
6428 expression->base.type = orig_type;
6431 static void semantic_unexpr_scalar(unary_expression_t *expression)
6433 type_t *const orig_type = expression->value->base.type;
6434 type_t *const type = skip_typeref(orig_type);
6435 if (!is_type_scalar(type)) {
6436 if (is_type_valid(type)) {
6437 errorf(HERE, "operand of ! must be of scalar type");
6442 expression->base.type = orig_type;
6445 static void semantic_unexpr_integer(unary_expression_t *expression)
6447 type_t *const orig_type = expression->value->base.type;
6448 type_t *const type = skip_typeref(orig_type);
6449 if (!is_type_integer(type)) {
6450 if (is_type_valid(type)) {
6451 errorf(HERE, "operand of ~ must be of integer type");
6456 expression->base.type = orig_type;
6459 static void semantic_dereference(unary_expression_t *expression)
6461 type_t *const orig_type = expression->value->base.type;
6462 type_t *const type = skip_typeref(orig_type);
6463 if (!is_type_pointer(type)) {
6464 if (is_type_valid(type)) {
6465 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
6470 type_t *result_type = type->pointer.points_to;
6471 result_type = automatic_type_conversion(result_type);
6472 expression->base.type = result_type;
6475 static void set_address_taken(expression_t *expression, bool may_be_register)
6477 if (expression->kind != EXPR_REFERENCE)
6480 declaration_t *const declaration = expression->reference.declaration;
6481 /* happens for parse errors */
6482 if (declaration == NULL)
6485 if (declaration->storage_class == STORAGE_CLASS_REGISTER && !may_be_register) {
6486 errorf(&expression->base.source_position,
6487 "address of register variable '%Y' requested",
6488 declaration->symbol);
6490 declaration->address_taken = 1;
6495 * Check the semantic of the address taken expression.
6497 static void semantic_take_addr(unary_expression_t *expression)
6499 expression_t *value = expression->value;
6500 value->base.type = revert_automatic_type_conversion(value);
6502 type_t *orig_type = value->base.type;
6503 if (!is_type_valid(orig_type))
6506 set_address_taken(value, false);
6508 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6511 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
6512 static expression_t *parse_##unexpression_type(unsigned precedence) \
6516 expression_t *unary_expression \
6517 = allocate_expression_zero(unexpression_type); \
6518 unary_expression->base.source_position = *HERE; \
6519 unary_expression->unary.value = parse_sub_expression(precedence); \
6521 sfunc(&unary_expression->unary); \
6523 return unary_expression; \
6526 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
6527 semantic_unexpr_arithmetic)
6528 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
6529 semantic_unexpr_arithmetic)
6530 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
6531 semantic_unexpr_scalar)
6532 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
6533 semantic_dereference)
6534 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
6536 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
6537 semantic_unexpr_integer)
6538 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
6540 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
6543 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
6545 static expression_t *parse_##unexpression_type(unsigned precedence, \
6546 expression_t *left) \
6548 (void) precedence; \
6551 expression_t *unary_expression \
6552 = allocate_expression_zero(unexpression_type); \
6553 unary_expression->unary.value = left; \
6555 sfunc(&unary_expression->unary); \
6557 return unary_expression; \
6560 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
6561 EXPR_UNARY_POSTFIX_INCREMENT,
6563 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
6564 EXPR_UNARY_POSTFIX_DECREMENT,
6567 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
6569 /* TODO: handle complex + imaginary types */
6571 /* § 6.3.1.8 Usual arithmetic conversions */
6572 if (type_left == type_long_double || type_right == type_long_double) {
6573 return type_long_double;
6574 } else if (type_left == type_double || type_right == type_double) {
6576 } else if (type_left == type_float || type_right == type_float) {
6580 type_right = promote_integer(type_right);
6581 type_left = promote_integer(type_left);
6583 if (type_left == type_right)
6586 bool signed_left = is_type_signed(type_left);
6587 bool signed_right = is_type_signed(type_right);
6588 int rank_left = get_rank(type_left);
6589 int rank_right = get_rank(type_right);
6590 if (rank_left < rank_right) {
6591 if (signed_left == signed_right || !signed_right) {
6597 if (signed_left == signed_right || !signed_left) {
6606 * Check the semantic restrictions for a binary expression.
6608 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
6610 expression_t *const left = expression->left;
6611 expression_t *const right = expression->right;
6612 type_t *const orig_type_left = left->base.type;
6613 type_t *const orig_type_right = right->base.type;
6614 type_t *const type_left = skip_typeref(orig_type_left);
6615 type_t *const type_right = skip_typeref(orig_type_right);
6617 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6618 /* TODO: improve error message */
6619 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6620 errorf(HERE, "operation needs arithmetic types");
6625 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6626 expression->left = create_implicit_cast(left, arithmetic_type);
6627 expression->right = create_implicit_cast(right, arithmetic_type);
6628 expression->base.type = arithmetic_type;
6631 static void semantic_shift_op(binary_expression_t *expression)
6633 expression_t *const left = expression->left;
6634 expression_t *const right = expression->right;
6635 type_t *const orig_type_left = left->base.type;
6636 type_t *const orig_type_right = right->base.type;
6637 type_t * type_left = skip_typeref(orig_type_left);
6638 type_t * type_right = skip_typeref(orig_type_right);
6640 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
6641 /* TODO: improve error message */
6642 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6643 errorf(HERE, "operation needs integer types");
6648 type_left = promote_integer(type_left);
6649 type_right = promote_integer(type_right);
6651 expression->left = create_implicit_cast(left, type_left);
6652 expression->right = create_implicit_cast(right, type_right);
6653 expression->base.type = type_left;
6656 static void semantic_add(binary_expression_t *expression)
6658 expression_t *const left = expression->left;
6659 expression_t *const right = expression->right;
6660 type_t *const orig_type_left = left->base.type;
6661 type_t *const orig_type_right = right->base.type;
6662 type_t *const type_left = skip_typeref(orig_type_left);
6663 type_t *const type_right = skip_typeref(orig_type_right);
6666 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6667 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6668 expression->left = create_implicit_cast(left, arithmetic_type);
6669 expression->right = create_implicit_cast(right, arithmetic_type);
6670 expression->base.type = arithmetic_type;
6672 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6673 check_pointer_arithmetic(&expression->base.source_position,
6674 type_left, orig_type_left);
6675 expression->base.type = type_left;
6676 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
6677 check_pointer_arithmetic(&expression->base.source_position,
6678 type_right, orig_type_right);
6679 expression->base.type = type_right;
6680 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6681 errorf(&expression->base.source_position,
6682 "invalid operands to binary + ('%T', '%T')",
6683 orig_type_left, orig_type_right);
6687 static void semantic_sub(binary_expression_t *expression)
6689 expression_t *const left = expression->left;
6690 expression_t *const right = expression->right;
6691 type_t *const orig_type_left = left->base.type;
6692 type_t *const orig_type_right = right->base.type;
6693 type_t *const type_left = skip_typeref(orig_type_left);
6694 type_t *const type_right = skip_typeref(orig_type_right);
6697 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6698 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6699 expression->left = create_implicit_cast(left, arithmetic_type);
6700 expression->right = create_implicit_cast(right, arithmetic_type);
6701 expression->base.type = arithmetic_type;
6703 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6704 check_pointer_arithmetic(&expression->base.source_position,
6705 type_left, orig_type_left);
6706 expression->base.type = type_left;
6707 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6708 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
6709 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
6710 if (!types_compatible(unqual_left, unqual_right)) {
6711 errorf(&expression->base.source_position,
6712 "subtracting pointers to incompatible types '%T' and '%T'",
6713 orig_type_left, orig_type_right);
6714 } else if (!is_type_object(unqual_left)) {
6715 if (is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
6716 warningf(&expression->base.source_position,
6717 "subtracting pointers to void");
6719 errorf(&expression->base.source_position,
6720 "subtracting pointers to non-object types '%T'",
6724 expression->base.type = type_ptrdiff_t;
6725 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6726 errorf(HERE, "invalid operands of types '%T' and '%T' to binary '-'",
6727 orig_type_left, orig_type_right);
6732 * Check the semantics of comparison expressions.
6734 * @param expression The expression to check.
6736 static void semantic_comparison(binary_expression_t *expression)
6738 expression_t *left = expression->left;
6739 expression_t *right = expression->right;
6740 type_t *orig_type_left = left->base.type;
6741 type_t *orig_type_right = right->base.type;
6743 type_t *type_left = skip_typeref(orig_type_left);
6744 type_t *type_right = skip_typeref(orig_type_right);
6746 /* TODO non-arithmetic types */
6747 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6748 /* test for signed vs unsigned compares */
6749 if (warning.sign_compare &&
6750 (expression->base.kind != EXPR_BINARY_EQUAL &&
6751 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
6752 (is_type_signed(type_left) != is_type_signed(type_right))) {
6754 /* check if 1 of the operands is a constant, in this case we just
6755 * check wether we can safely represent the resulting constant in
6756 * the type of the other operand. */
6757 expression_t *const_expr = NULL;
6758 expression_t *other_expr = NULL;
6760 if (is_constant_expression(left)) {
6763 } else if (is_constant_expression(right)) {
6768 if (const_expr != NULL) {
6769 type_t *other_type = skip_typeref(other_expr->base.type);
6770 long val = fold_constant(const_expr);
6771 /* TODO: check if val can be represented by other_type */
6775 warningf(&expression->base.source_position,
6776 "comparison between signed and unsigned");
6778 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6779 expression->left = create_implicit_cast(left, arithmetic_type);
6780 expression->right = create_implicit_cast(right, arithmetic_type);
6781 expression->base.type = arithmetic_type;
6782 if (warning.float_equal &&
6783 (expression->base.kind == EXPR_BINARY_EQUAL ||
6784 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
6785 is_type_float(arithmetic_type)) {
6786 warningf(&expression->base.source_position,
6787 "comparing floating point with == or != is unsafe");
6789 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
6790 /* TODO check compatibility */
6791 } else if (is_type_pointer(type_left)) {
6792 expression->right = create_implicit_cast(right, type_left);
6793 } else if (is_type_pointer(type_right)) {
6794 expression->left = create_implicit_cast(left, type_right);
6795 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6796 type_error_incompatible("invalid operands in comparison",
6797 &expression->base.source_position,
6798 type_left, type_right);
6800 expression->base.type = type_int;
6804 * Checks if a compound type has constant fields.
6806 static bool has_const_fields(const compound_type_t *type)
6808 const scope_t *scope = &type->declaration->scope;
6809 const declaration_t *declaration = scope->declarations;
6811 for (; declaration != NULL; declaration = declaration->next) {
6812 if (declaration->namespc != NAMESPACE_NORMAL)
6815 const type_t *decl_type = skip_typeref(declaration->type);
6816 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
6823 static bool is_lvalue(const expression_t *expression)
6825 switch (expression->kind) {
6826 case EXPR_REFERENCE:
6827 case EXPR_ARRAY_ACCESS:
6829 case EXPR_UNARY_DEREFERENCE:
6837 static bool is_valid_assignment_lhs(expression_t const* const left)
6839 type_t *const orig_type_left = revert_automatic_type_conversion(left);
6840 type_t *const type_left = skip_typeref(orig_type_left);
6842 if (!is_lvalue(left)) {
6843 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
6848 if (is_type_array(type_left)) {
6849 errorf(HERE, "cannot assign to arrays ('%E')", left);
6852 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
6853 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
6857 if (is_type_incomplete(type_left)) {
6858 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
6859 left, orig_type_left);
6862 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
6863 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
6864 left, orig_type_left);
6871 static void semantic_arithmetic_assign(binary_expression_t *expression)
6873 expression_t *left = expression->left;
6874 expression_t *right = expression->right;
6875 type_t *orig_type_left = left->base.type;
6876 type_t *orig_type_right = right->base.type;
6878 if (!is_valid_assignment_lhs(left))
6881 type_t *type_left = skip_typeref(orig_type_left);
6882 type_t *type_right = skip_typeref(orig_type_right);
6884 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
6885 /* TODO: improve error message */
6886 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6887 errorf(HERE, "operation needs arithmetic types");
6892 /* combined instructions are tricky. We can't create an implicit cast on
6893 * the left side, because we need the uncasted form for the store.
6894 * The ast2firm pass has to know that left_type must be right_type
6895 * for the arithmetic operation and create a cast by itself */
6896 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
6897 expression->right = create_implicit_cast(right, arithmetic_type);
6898 expression->base.type = type_left;
6901 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
6903 expression_t *const left = expression->left;
6904 expression_t *const right = expression->right;
6905 type_t *const orig_type_left = left->base.type;
6906 type_t *const orig_type_right = right->base.type;
6907 type_t *const type_left = skip_typeref(orig_type_left);
6908 type_t *const type_right = skip_typeref(orig_type_right);
6910 if (!is_valid_assignment_lhs(left))
6913 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
6914 /* combined instructions are tricky. We can't create an implicit cast on
6915 * the left side, because we need the uncasted form for the store.
6916 * The ast2firm pass has to know that left_type must be right_type
6917 * for the arithmetic operation and create a cast by itself */
6918 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
6919 expression->right = create_implicit_cast(right, arithmetic_type);
6920 expression->base.type = type_left;
6921 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
6922 check_pointer_arithmetic(&expression->base.source_position,
6923 type_left, orig_type_left);
6924 expression->base.type = type_left;
6925 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
6926 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
6931 * Check the semantic restrictions of a logical expression.
6933 static void semantic_logical_op(binary_expression_t *expression)
6935 expression_t *const left = expression->left;
6936 expression_t *const right = expression->right;
6937 type_t *const orig_type_left = left->base.type;
6938 type_t *const orig_type_right = right->base.type;
6939 type_t *const type_left = skip_typeref(orig_type_left);
6940 type_t *const type_right = skip_typeref(orig_type_right);
6942 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
6943 /* TODO: improve error message */
6944 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6945 errorf(HERE, "operation needs scalar types");
6950 expression->base.type = type_int;
6954 * Check the semantic restrictions of a binary assign expression.
6956 static void semantic_binexpr_assign(binary_expression_t *expression)
6958 expression_t *left = expression->left;
6959 type_t *orig_type_left = left->base.type;
6961 type_t *type_left = revert_automatic_type_conversion(left);
6962 type_left = skip_typeref(orig_type_left);
6964 if (!is_valid_assignment_lhs(left))
6967 assign_error_t error = semantic_assign(orig_type_left, expression->right);
6968 report_assign_error(error, orig_type_left, expression->right,
6969 "assignment", &left->base.source_position);
6970 expression->right = create_implicit_cast(expression->right, orig_type_left);
6971 expression->base.type = orig_type_left;
6975 * Determine if the outermost operation (or parts thereof) of the given
6976 * expression has no effect in order to generate a warning about this fact.
6977 * Therefore in some cases this only examines some of the operands of the
6978 * expression (see comments in the function and examples below).
6980 * f() + 23; // warning, because + has no effect
6981 * x || f(); // no warning, because x controls execution of f()
6982 * x ? y : f(); // warning, because y has no effect
6983 * (void)x; // no warning to be able to suppress the warning
6984 * This function can NOT be used for an "expression has definitely no effect"-
6986 static bool expression_has_effect(const expression_t *const expr)
6988 switch (expr->kind) {
6989 case EXPR_UNKNOWN: break;
6990 case EXPR_INVALID: return true; /* do NOT warn */
6991 case EXPR_REFERENCE: return false;
6992 /* suppress the warning for microsoft __noop operations */
6993 case EXPR_CONST: return expr->conste.is_ms_noop;
6994 case EXPR_CHARACTER_CONSTANT: return false;
6995 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
6996 case EXPR_STRING_LITERAL: return false;
6997 case EXPR_WIDE_STRING_LITERAL: return false;
7000 const call_expression_t *const call = &expr->call;
7001 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
7004 switch (call->function->builtin_symbol.symbol->ID) {
7005 case T___builtin_va_end: return true;
7006 default: return false;
7010 /* Generate the warning if either the left or right hand side of a
7011 * conditional expression has no effect */
7012 case EXPR_CONDITIONAL: {
7013 const conditional_expression_t *const cond = &expr->conditional;
7015 expression_has_effect(cond->true_expression) &&
7016 expression_has_effect(cond->false_expression);
7019 case EXPR_SELECT: return false;
7020 case EXPR_ARRAY_ACCESS: return false;
7021 case EXPR_SIZEOF: return false;
7022 case EXPR_CLASSIFY_TYPE: return false;
7023 case EXPR_ALIGNOF: return false;
7025 case EXPR_FUNCNAME: return false;
7026 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
7027 case EXPR_BUILTIN_CONSTANT_P: return false;
7028 case EXPR_BUILTIN_PREFETCH: return true;
7029 case EXPR_OFFSETOF: return false;
7030 case EXPR_VA_START: return true;
7031 case EXPR_VA_ARG: return true;
7032 case EXPR_STATEMENT: return true; // TODO
7033 case EXPR_COMPOUND_LITERAL: return false;
7035 case EXPR_UNARY_NEGATE: return false;
7036 case EXPR_UNARY_PLUS: return false;
7037 case EXPR_UNARY_BITWISE_NEGATE: return false;
7038 case EXPR_UNARY_NOT: return false;
7039 case EXPR_UNARY_DEREFERENCE: return false;
7040 case EXPR_UNARY_TAKE_ADDRESS: return false;
7041 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
7042 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
7043 case EXPR_UNARY_PREFIX_INCREMENT: return true;
7044 case EXPR_UNARY_PREFIX_DECREMENT: return true;
7046 /* Treat void casts as if they have an effect in order to being able to
7047 * suppress the warning */
7048 case EXPR_UNARY_CAST: {
7049 type_t *const type = skip_typeref(expr->base.type);
7050 return is_type_atomic(type, ATOMIC_TYPE_VOID);
7053 case EXPR_UNARY_CAST_IMPLICIT: return true;
7054 case EXPR_UNARY_ASSUME: return true;
7056 case EXPR_BINARY_ADD: return false;
7057 case EXPR_BINARY_SUB: return false;
7058 case EXPR_BINARY_MUL: return false;
7059 case EXPR_BINARY_DIV: return false;
7060 case EXPR_BINARY_MOD: return false;
7061 case EXPR_BINARY_EQUAL: return false;
7062 case EXPR_BINARY_NOTEQUAL: return false;
7063 case EXPR_BINARY_LESS: return false;
7064 case EXPR_BINARY_LESSEQUAL: return false;
7065 case EXPR_BINARY_GREATER: return false;
7066 case EXPR_BINARY_GREATEREQUAL: return false;
7067 case EXPR_BINARY_BITWISE_AND: return false;
7068 case EXPR_BINARY_BITWISE_OR: return false;
7069 case EXPR_BINARY_BITWISE_XOR: return false;
7070 case EXPR_BINARY_SHIFTLEFT: return false;
7071 case EXPR_BINARY_SHIFTRIGHT: return false;
7072 case EXPR_BINARY_ASSIGN: return true;
7073 case EXPR_BINARY_MUL_ASSIGN: return true;
7074 case EXPR_BINARY_DIV_ASSIGN: return true;
7075 case EXPR_BINARY_MOD_ASSIGN: return true;
7076 case EXPR_BINARY_ADD_ASSIGN: return true;
7077 case EXPR_BINARY_SUB_ASSIGN: return true;
7078 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
7079 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
7080 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
7081 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
7082 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
7084 /* Only examine the right hand side of && and ||, because the left hand
7085 * side already has the effect of controlling the execution of the right
7087 case EXPR_BINARY_LOGICAL_AND:
7088 case EXPR_BINARY_LOGICAL_OR:
7089 /* Only examine the right hand side of a comma expression, because the left
7090 * hand side has a separate warning */
7091 case EXPR_BINARY_COMMA:
7092 return expression_has_effect(expr->binary.right);
7094 case EXPR_BINARY_BUILTIN_EXPECT: return true;
7095 case EXPR_BINARY_ISGREATER: return false;
7096 case EXPR_BINARY_ISGREATEREQUAL: return false;
7097 case EXPR_BINARY_ISLESS: return false;
7098 case EXPR_BINARY_ISLESSEQUAL: return false;
7099 case EXPR_BINARY_ISLESSGREATER: return false;
7100 case EXPR_BINARY_ISUNORDERED: return false;
7103 internal_errorf(HERE, "unexpected expression");
7106 static void semantic_comma(binary_expression_t *expression)
7108 if (warning.unused_value) {
7109 const expression_t *const left = expression->left;
7110 if (!expression_has_effect(left)) {
7111 warningf(&left->base.source_position,
7112 "left-hand operand of comma expression has no effect");
7115 expression->base.type = expression->right->base.type;
7118 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
7119 static expression_t *parse_##binexpression_type(unsigned precedence, \
7120 expression_t *left) \
7123 source_position_t pos = *HERE; \
7125 expression_t *right = parse_sub_expression(precedence + lr); \
7127 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
7128 binexpr->base.source_position = pos; \
7129 binexpr->binary.left = left; \
7130 binexpr->binary.right = right; \
7131 sfunc(&binexpr->binary); \
7136 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
7137 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
7138 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
7139 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
7140 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
7141 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
7142 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
7143 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
7144 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
7146 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
7147 semantic_comparison, 1)
7148 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
7149 semantic_comparison, 1)
7150 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
7151 semantic_comparison, 1)
7152 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
7153 semantic_comparison, 1)
7155 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
7156 semantic_binexpr_arithmetic, 1)
7157 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
7158 semantic_binexpr_arithmetic, 1)
7159 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
7160 semantic_binexpr_arithmetic, 1)
7161 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
7162 semantic_logical_op, 1)
7163 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
7164 semantic_logical_op, 1)
7165 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
7166 semantic_shift_op, 1)
7167 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
7168 semantic_shift_op, 1)
7169 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
7170 semantic_arithmetic_addsubb_assign, 0)
7171 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
7172 semantic_arithmetic_addsubb_assign, 0)
7173 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
7174 semantic_arithmetic_assign, 0)
7175 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
7176 semantic_arithmetic_assign, 0)
7177 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
7178 semantic_arithmetic_assign, 0)
7179 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
7180 semantic_arithmetic_assign, 0)
7181 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7182 semantic_arithmetic_assign, 0)
7183 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
7184 semantic_arithmetic_assign, 0)
7185 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
7186 semantic_arithmetic_assign, 0)
7187 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
7188 semantic_arithmetic_assign, 0)
7190 static expression_t *parse_sub_expression(unsigned precedence)
7192 if (token.type < 0) {
7193 return expected_expression_error();
7196 expression_parser_function_t *parser
7197 = &expression_parsers[token.type];
7198 source_position_t source_position = token.source_position;
7201 if (parser->parser != NULL) {
7202 left = parser->parser(parser->precedence);
7204 left = parse_primary_expression();
7206 assert(left != NULL);
7207 left->base.source_position = source_position;
7210 if (token.type < 0) {
7211 return expected_expression_error();
7214 parser = &expression_parsers[token.type];
7215 if (parser->infix_parser == NULL)
7217 if (parser->infix_precedence < precedence)
7220 left = parser->infix_parser(parser->infix_precedence, left);
7222 assert(left != NULL);
7223 assert(left->kind != EXPR_UNKNOWN);
7224 left->base.source_position = source_position;
7231 * Parse an expression.
7233 static expression_t *parse_expression(void)
7235 return parse_sub_expression(1);
7239 * Register a parser for a prefix-like operator with given precedence.
7241 * @param parser the parser function
7242 * @param token_type the token type of the prefix token
7243 * @param precedence the precedence of the operator
7245 static void register_expression_parser(parse_expression_function parser,
7246 int token_type, unsigned precedence)
7248 expression_parser_function_t *entry = &expression_parsers[token_type];
7250 if (entry->parser != NULL) {
7251 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7252 panic("trying to register multiple expression parsers for a token");
7254 entry->parser = parser;
7255 entry->precedence = precedence;
7259 * Register a parser for an infix operator with given precedence.
7261 * @param parser the parser function
7262 * @param token_type the token type of the infix operator
7263 * @param precedence the precedence of the operator
7265 static void register_infix_parser(parse_expression_infix_function parser,
7266 int token_type, unsigned precedence)
7268 expression_parser_function_t *entry = &expression_parsers[token_type];
7270 if (entry->infix_parser != NULL) {
7271 diagnosticf("for token '%k'\n", (token_type_t)token_type);
7272 panic("trying to register multiple infix expression parsers for a "
7275 entry->infix_parser = parser;
7276 entry->infix_precedence = precedence;
7280 * Initialize the expression parsers.
7282 static void init_expression_parsers(void)
7284 memset(&expression_parsers, 0, sizeof(expression_parsers));
7286 register_infix_parser(parse_array_expression, '[', 30);
7287 register_infix_parser(parse_call_expression, '(', 30);
7288 register_infix_parser(parse_select_expression, '.', 30);
7289 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
7290 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
7292 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
7295 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 17);
7296 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 17);
7297 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 17);
7298 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 16);
7299 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 16);
7300 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 15);
7301 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 15);
7302 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
7303 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
7304 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
7305 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
7306 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
7307 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
7308 T_EXCLAMATIONMARKEQUAL, 13);
7309 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
7310 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
7311 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
7312 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
7313 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
7314 register_infix_parser(parse_conditional_expression, '?', 7);
7315 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
7316 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
7317 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
7318 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
7319 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
7320 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
7321 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
7322 T_LESSLESSEQUAL, 2);
7323 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
7324 T_GREATERGREATEREQUAL, 2);
7325 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
7327 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
7329 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
7332 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
7334 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
7335 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
7336 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
7337 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
7338 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
7339 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
7340 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
7342 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
7344 register_expression_parser(parse_sizeof, T_sizeof, 25);
7345 register_expression_parser(parse_alignof, T___alignof__, 25);
7346 register_expression_parser(parse_extension, T___extension__, 25);
7347 register_expression_parser(parse_builtin_classify_type,
7348 T___builtin_classify_type, 25);
7352 * Parse a asm statement arguments specification.
7354 static asm_argument_t *parse_asm_arguments(bool is_out)
7356 asm_argument_t *result = NULL;
7357 asm_argument_t *last = NULL;
7359 while (token.type == T_STRING_LITERAL || token.type == '[') {
7360 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7361 memset(argument, 0, sizeof(argument[0]));
7363 if (token.type == '[') {
7365 if (token.type != T_IDENTIFIER) {
7366 parse_error_expected("while parsing asm argument",
7367 T_IDENTIFIER, NULL);
7370 argument->symbol = token.v.symbol;
7375 argument->constraints = parse_string_literals();
7377 expression_t *expression = parse_expression();
7378 argument->expression = expression;
7379 if (is_out && !is_lvalue(expression)) {
7380 errorf(&expression->base.source_position,
7381 "asm output argument is not an lvalue");
7385 set_address_taken(expression, true);
7388 last->next = argument;
7394 if (token.type != ',')
7405 * Parse a asm statement clobber specification.
7407 static asm_clobber_t *parse_asm_clobbers(void)
7409 asm_clobber_t *result = NULL;
7410 asm_clobber_t *last = NULL;
7412 while(token.type == T_STRING_LITERAL) {
7413 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
7414 clobber->clobber = parse_string_literals();
7417 last->next = clobber;
7423 if (token.type != ',')
7432 * Parse an asm statement.
7434 static statement_t *parse_asm_statement(void)
7438 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
7439 statement->base.source_position = token.source_position;
7441 asm_statement_t *asm_statement = &statement->asms;
7443 if (token.type == T_volatile) {
7445 asm_statement->is_volatile = true;
7449 add_anchor_token(')');
7450 add_anchor_token(':');
7451 asm_statement->asm_text = parse_string_literals();
7453 if (token.type != ':') {
7454 rem_anchor_token(':');
7459 asm_statement->outputs = parse_asm_arguments(true);
7460 if (token.type != ':') {
7461 rem_anchor_token(':');
7466 asm_statement->inputs = parse_asm_arguments(false);
7467 if (token.type != ':') {
7468 rem_anchor_token(':');
7471 rem_anchor_token(':');
7474 asm_statement->clobbers = parse_asm_clobbers();
7477 rem_anchor_token(')');
7482 return create_invalid_statement();
7486 * Parse a case statement.
7488 static statement_t *parse_case_statement(void)
7492 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7494 statement->base.source_position = token.source_position;
7495 statement->case_label.expression = parse_expression();
7497 if (c_mode & _GNUC) {
7498 if (token.type == T_DOTDOTDOT) {
7500 statement->case_label.end_range = parse_expression();
7506 if (! is_constant_expression(statement->case_label.expression)) {
7507 errorf(&statement->base.source_position,
7508 "case label does not reduce to an integer constant");
7510 /* TODO: check if the case label is already known */
7511 if (current_switch != NULL) {
7512 /* link all cases into the switch statement */
7513 if (current_switch->last_case == NULL) {
7514 current_switch->first_case =
7515 current_switch->last_case = &statement->case_label;
7517 current_switch->last_case->next = &statement->case_label;
7520 errorf(&statement->base.source_position,
7521 "case label not within a switch statement");
7524 statement->case_label.statement = parse_statement();
7528 return create_invalid_statement();
7532 * Finds an existing default label of a switch statement.
7534 static case_label_statement_t *
7535 find_default_label(const switch_statement_t *statement)
7537 case_label_statement_t *label = statement->first_case;
7538 for ( ; label != NULL; label = label->next) {
7539 if (label->expression == NULL)
7546 * Parse a default statement.
7548 static statement_t *parse_default_statement(void)
7552 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
7554 statement->base.source_position = token.source_position;
7557 if (current_switch != NULL) {
7558 const case_label_statement_t *def_label = find_default_label(current_switch);
7559 if (def_label != NULL) {
7560 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
7561 &def_label->base.source_position);
7563 /* link all cases into the switch statement */
7564 if (current_switch->last_case == NULL) {
7565 current_switch->first_case =
7566 current_switch->last_case = &statement->case_label;
7568 current_switch->last_case->next = &statement->case_label;
7572 errorf(&statement->base.source_position,
7573 "'default' label not within a switch statement");
7575 statement->case_label.statement = parse_statement();
7579 return create_invalid_statement();
7583 * Return the declaration for a given label symbol or create a new one.
7585 static declaration_t *get_label(symbol_t *symbol)
7587 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
7588 assert(current_function != NULL);
7589 /* if we found a label in the same function, then we already created the
7591 if (candidate != NULL
7592 && candidate->parent_scope == ¤t_function->scope) {
7596 /* otherwise we need to create a new one */
7597 declaration_t *const declaration = allocate_declaration_zero();
7598 declaration->namespc = NAMESPACE_LABEL;
7599 declaration->symbol = symbol;
7601 label_push(declaration);
7607 * Parse a label statement.
7609 static statement_t *parse_label_statement(void)
7611 assert(token.type == T_IDENTIFIER);
7612 symbol_t *symbol = token.v.symbol;
7615 declaration_t *label = get_label(symbol);
7617 /* if source position is already set then the label is defined twice,
7618 * otherwise it was just mentioned in a goto so far */
7619 if (label->source_position.input_name != NULL) {
7620 errorf(HERE, "duplicate label '%Y' (declared %P)",
7621 symbol, &label->source_position);
7623 label->source_position = token.source_position;
7626 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
7628 statement->base.source_position = token.source_position;
7629 statement->label.label = label;
7633 if (token.type == '}') {
7634 /* TODO only warn? */
7636 warningf(HERE, "label at end of compound statement");
7637 statement->label.statement = create_empty_statement();
7639 errorf(HERE, "label at end of compound statement");
7640 statement->label.statement = create_invalid_statement();
7644 if (token.type == ';') {
7645 /* eat an empty statement here, to avoid the warning about an empty
7646 * after a label. label:; is commonly used to have a label before
7648 statement->label.statement = create_empty_statement();
7651 statement->label.statement = parse_statement();
7655 /* remember the labels in a list for later checking */
7656 if (label_last == NULL) {
7657 label_first = &statement->label;
7659 label_last->next = &statement->label;
7661 label_last = &statement->label;
7667 * Parse an if statement.
7669 static statement_t *parse_if(void)
7673 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
7674 statement->base.source_position = token.source_position;
7677 add_anchor_token(')');
7678 statement->ifs.condition = parse_expression();
7679 rem_anchor_token(')');
7682 add_anchor_token(T_else);
7683 statement->ifs.true_statement = parse_statement();
7684 rem_anchor_token(T_else);
7686 if (token.type == T_else) {
7688 statement->ifs.false_statement = parse_statement();
7693 return create_invalid_statement();
7697 * Parse a switch statement.
7699 static statement_t *parse_switch(void)
7703 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
7704 statement->base.source_position = token.source_position;
7707 expression_t *const expr = parse_expression();
7708 type_t * type = skip_typeref(expr->base.type);
7709 if (is_type_integer(type)) {
7710 type = promote_integer(type);
7711 } else if (is_type_valid(type)) {
7712 errorf(&expr->base.source_position,
7713 "switch quantity is not an integer, but '%T'", type);
7714 type = type_error_type;
7716 statement->switchs.expression = create_implicit_cast(expr, type);
7719 switch_statement_t *rem = current_switch;
7720 current_switch = &statement->switchs;
7721 statement->switchs.body = parse_statement();
7722 current_switch = rem;
7724 if (warning.switch_default &&
7725 find_default_label(&statement->switchs) == NULL) {
7726 warningf(&statement->base.source_position, "switch has no default case");
7731 return create_invalid_statement();
7734 static statement_t *parse_loop_body(statement_t *const loop)
7736 statement_t *const rem = current_loop;
7737 current_loop = loop;
7739 statement_t *const body = parse_statement();
7746 * Parse a while statement.
7748 static statement_t *parse_while(void)
7752 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
7753 statement->base.source_position = token.source_position;
7756 add_anchor_token(')');
7757 statement->whiles.condition = parse_expression();
7758 rem_anchor_token(')');
7761 statement->whiles.body = parse_loop_body(statement);
7765 return create_invalid_statement();
7769 * Parse a do statement.
7771 static statement_t *parse_do(void)
7775 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
7777 statement->base.source_position = token.source_position;
7779 add_anchor_token(T_while);
7780 statement->do_while.body = parse_loop_body(statement);
7781 rem_anchor_token(T_while);
7785 add_anchor_token(')');
7786 statement->do_while.condition = parse_expression();
7787 rem_anchor_token(')');
7793 return create_invalid_statement();
7797 * Parse a for statement.
7799 static statement_t *parse_for(void)
7803 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
7804 statement->base.source_position = token.source_position;
7806 int top = environment_top();
7807 scope_t *last_scope = scope;
7808 set_scope(&statement->fors.scope);
7811 add_anchor_token(')');
7813 if (token.type != ';') {
7814 if (is_declaration_specifier(&token, false)) {
7815 parse_declaration(record_declaration);
7817 add_anchor_token(';');
7818 expression_t *const init = parse_expression();
7819 statement->fors.initialisation = init;
7820 if (warning.unused_value && !expression_has_effect(init)) {
7821 warningf(&init->base.source_position,
7822 "initialisation of 'for'-statement has no effect");
7824 rem_anchor_token(';');
7831 if (token.type != ';') {
7832 add_anchor_token(';');
7833 statement->fors.condition = parse_expression();
7834 rem_anchor_token(';');
7837 if (token.type != ')') {
7838 expression_t *const step = parse_expression();
7839 statement->fors.step = step;
7840 if (warning.unused_value && !expression_has_effect(step)) {
7841 warningf(&step->base.source_position,
7842 "step of 'for'-statement has no effect");
7845 rem_anchor_token(')');
7847 statement->fors.body = parse_loop_body(statement);
7849 assert(scope == &statement->fors.scope);
7850 set_scope(last_scope);
7851 environment_pop_to(top);
7856 rem_anchor_token(')');
7857 assert(scope == &statement->fors.scope);
7858 set_scope(last_scope);
7859 environment_pop_to(top);
7861 return create_invalid_statement();
7865 * Parse a goto statement.
7867 static statement_t *parse_goto(void)
7871 if (token.type != T_IDENTIFIER) {
7872 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
7876 symbol_t *symbol = token.v.symbol;
7879 declaration_t *label = get_label(symbol);
7881 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
7882 statement->base.source_position = token.source_position;
7884 statement->gotos.label = label;
7886 /* remember the goto's in a list for later checking */
7887 if (goto_last == NULL) {
7888 goto_first = &statement->gotos;
7890 goto_last->next = &statement->gotos;
7892 goto_last = &statement->gotos;
7898 return create_invalid_statement();
7902 * Parse a continue statement.
7904 static statement_t *parse_continue(void)
7906 statement_t *statement;
7907 if (current_loop == NULL) {
7908 errorf(HERE, "continue statement not within loop");
7909 statement = create_invalid_statement();
7911 statement = allocate_statement_zero(STATEMENT_CONTINUE);
7913 statement->base.source_position = token.source_position;
7921 return create_invalid_statement();
7925 * Parse a break statement.
7927 static statement_t *parse_break(void)
7929 statement_t *statement;
7930 if (current_switch == NULL && current_loop == NULL) {
7931 errorf(HERE, "break statement not within loop or switch");
7932 statement = create_invalid_statement();
7934 statement = allocate_statement_zero(STATEMENT_BREAK);
7936 statement->base.source_position = token.source_position;
7944 return create_invalid_statement();
7948 * Parse a __leave statement.
7950 static statement_t *parse_leave(void)
7952 statement_t *statement;
7953 if (current_try == NULL) {
7954 errorf(HERE, "__leave statement not within __try");
7955 statement = create_invalid_statement();
7957 statement = allocate_statement_zero(STATEMENT_LEAVE);
7959 statement->base.source_position = token.source_position;
7967 return create_invalid_statement();
7971 * Check if a given declaration represents a local variable.
7973 static bool is_local_var_declaration(const declaration_t *declaration) {
7974 switch ((storage_class_tag_t) declaration->storage_class) {
7975 case STORAGE_CLASS_AUTO:
7976 case STORAGE_CLASS_REGISTER: {
7977 const type_t *type = skip_typeref(declaration->type);
7978 if (is_type_function(type)) {
7990 * Check if a given declaration represents a variable.
7992 static bool is_var_declaration(const declaration_t *declaration) {
7993 if (declaration->storage_class == STORAGE_CLASS_TYPEDEF)
7996 const type_t *type = skip_typeref(declaration->type);
7997 return !is_type_function(type);
8001 * Check if a given expression represents a local variable.
8003 static bool is_local_variable(const expression_t *expression)
8005 if (expression->base.kind != EXPR_REFERENCE) {
8008 const declaration_t *declaration = expression->reference.declaration;
8009 return is_local_var_declaration(declaration);
8013 * Check if a given expression represents a local variable and
8014 * return its declaration then, else return NULL.
8016 declaration_t *expr_is_variable(const expression_t *expression)
8018 if (expression->base.kind != EXPR_REFERENCE) {
8021 declaration_t *declaration = expression->reference.declaration;
8022 if (is_var_declaration(declaration))
8028 * Parse a return statement.
8030 static statement_t *parse_return(void)
8032 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
8033 statement->base.source_position = token.source_position;
8037 expression_t *return_value = NULL;
8038 if (token.type != ';') {
8039 return_value = parse_expression();
8043 const type_t *const func_type = current_function->type;
8044 assert(is_type_function(func_type));
8045 type_t *const return_type = skip_typeref(func_type->function.return_type);
8047 if (return_value != NULL) {
8048 type_t *return_value_type = skip_typeref(return_value->base.type);
8050 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)
8051 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
8052 warningf(&statement->base.source_position,
8053 "'return' with a value, in function returning void");
8054 return_value = NULL;
8056 assign_error_t error = semantic_assign(return_type, return_value);
8057 report_assign_error(error, return_type, return_value, "'return'",
8058 &statement->base.source_position);
8059 return_value = create_implicit_cast(return_value, return_type);
8061 /* check for returning address of a local var */
8062 if (return_value != NULL &&
8063 return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
8064 const expression_t *expression = return_value->unary.value;
8065 if (is_local_variable(expression)) {
8066 warningf(&statement->base.source_position,
8067 "function returns address of local variable");
8071 if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
8072 warningf(&statement->base.source_position,
8073 "'return' without value, in function returning non-void");
8076 statement->returns.value = return_value;
8080 return create_invalid_statement();
8084 * Parse a declaration statement.
8086 static statement_t *parse_declaration_statement(void)
8088 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
8090 statement->base.source_position = token.source_position;
8092 declaration_t *before = last_declaration;
8093 parse_declaration(record_declaration);
8095 if (before == NULL) {
8096 statement->declaration.declarations_begin = scope->declarations;
8098 statement->declaration.declarations_begin = before->next;
8100 statement->declaration.declarations_end = last_declaration;
8106 * Parse an expression statement, ie. expr ';'.
8108 static statement_t *parse_expression_statement(void)
8110 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
8112 statement->base.source_position = token.source_position;
8113 expression_t *const expr = parse_expression();
8114 statement->expression.expression = expr;
8120 return create_invalid_statement();
8124 * Parse a microsoft __try { } __finally { } or
8125 * __try{ } __except() { }
8127 static statement_t *parse_ms_try_statment(void) {
8128 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
8130 statement->base.source_position = token.source_position;
8133 ms_try_statement_t *rem = current_try;
8134 current_try = &statement->ms_try;
8135 statement->ms_try.try_statement = parse_compound_statement(false);
8138 if (token.type == T___except) {
8141 add_anchor_token(')');
8142 expression_t *const expr = parse_expression();
8143 type_t * type = skip_typeref(expr->base.type);
8144 if (is_type_integer(type)) {
8145 type = promote_integer(type);
8146 } else if (is_type_valid(type)) {
8147 errorf(&expr->base.source_position,
8148 "__expect expression is not an integer, but '%T'", type);
8149 type = type_error_type;
8151 statement->ms_try.except_expression = create_implicit_cast(expr, type);
8152 rem_anchor_token(')');
8154 statement->ms_try.final_statement = parse_compound_statement(false);
8155 } else if (token.type == T__finally) {
8157 statement->ms_try.final_statement = parse_compound_statement(false);
8159 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
8160 return create_invalid_statement();
8164 return create_invalid_statement();
8168 * Parse a statement.
8169 * There's also parse_statement() which additionally checks for
8170 * "statement has no effect" warnings
8172 static statement_t *intern_parse_statement(void)
8174 statement_t *statement = NULL;
8176 /* declaration or statement */
8177 add_anchor_token(';');
8178 switch(token.type) {
8180 statement = parse_asm_statement();
8184 statement = parse_case_statement();
8188 statement = parse_default_statement();
8192 statement = parse_compound_statement(false);
8196 statement = parse_if ();
8200 statement = parse_switch();
8204 statement = parse_while();
8208 statement = parse_do();
8212 statement = parse_for();
8216 statement = parse_goto();
8220 statement = parse_continue();
8224 statement = parse_break();
8228 statement = parse_leave();
8232 statement = parse_return();
8236 if (warning.empty_statement) {
8237 warningf(HERE, "statement is empty");
8239 statement = create_empty_statement();
8244 if (look_ahead(1)->type == ':') {
8245 statement = parse_label_statement();
8249 if (is_typedef_symbol(token.v.symbol)) {
8250 statement = parse_declaration_statement();
8254 statement = parse_expression_statement();
8257 case T___extension__:
8258 /* this can be a prefix to a declaration or an expression statement */
8259 /* we simply eat it now and parse the rest with tail recursion */
8262 } while(token.type == T___extension__);
8263 statement = parse_statement();
8267 statement = parse_declaration_statement();
8271 statement = parse_ms_try_statment();
8275 statement = parse_expression_statement();
8278 rem_anchor_token(';');
8280 assert(statement != NULL
8281 && statement->base.source_position.input_name != NULL);
8287 * parse a statement and emits "statement has no effect" warning if needed
8288 * (This is really a wrapper around intern_parse_statement with check for 1
8289 * single warning. It is needed, because for statement expressions we have
8290 * to avoid the warning on the last statement)
8292 static statement_t *parse_statement(void)
8294 statement_t *statement = intern_parse_statement();
8296 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
8297 expression_t *expression = statement->expression.expression;
8298 if (!expression_has_effect(expression)) {
8299 warningf(&expression->base.source_position,
8300 "statement has no effect");
8308 * Parse a compound statement.
8310 static statement_t *parse_compound_statement(bool inside_expression_statement)
8312 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
8314 statement->base.source_position = token.source_position;
8317 add_anchor_token('}');
8319 int top = environment_top();
8320 scope_t *last_scope = scope;
8321 set_scope(&statement->compound.scope);
8323 statement_t *last_statement = NULL;
8325 while(token.type != '}' && token.type != T_EOF) {
8326 statement_t *sub_statement = intern_parse_statement();
8327 if (is_invalid_statement(sub_statement)) {
8328 /* an error occurred. if we are at an anchor, return */
8334 if (last_statement != NULL) {
8335 last_statement->base.next = sub_statement;
8337 statement->compound.statements = sub_statement;
8340 while(sub_statement->base.next != NULL)
8341 sub_statement = sub_statement->base.next;
8343 last_statement = sub_statement;
8346 if (token.type == '}') {
8349 errorf(&statement->base.source_position,
8350 "end of file while looking for closing '}'");
8353 /* look over all statements again to produce no effect warnings */
8354 if (warning.unused_value) {
8355 statement_t *sub_statement = statement->compound.statements;
8356 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
8357 if (sub_statement->kind != STATEMENT_EXPRESSION)
8359 /* don't emit a warning for the last expression in an expression
8360 * statement as it has always an effect */
8361 if (inside_expression_statement && sub_statement->base.next == NULL)
8364 expression_t *expression = sub_statement->expression.expression;
8365 if (!expression_has_effect(expression)) {
8366 warningf(&expression->base.source_position,
8367 "statement has no effect");
8373 rem_anchor_token('}');
8374 assert(scope == &statement->compound.scope);
8375 set_scope(last_scope);
8376 environment_pop_to(top);
8382 * Initialize builtin types.
8384 static void initialize_builtin_types(void)
8386 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
8387 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
8388 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
8389 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
8390 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
8391 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
8392 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
8393 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
8395 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
8396 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
8397 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
8398 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
8402 * Check for unused global static functions and variables
8404 static void check_unused_globals(void)
8406 if (!warning.unused_function && !warning.unused_variable)
8409 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
8411 decl->modifiers & DM_USED ||
8412 decl->storage_class != STORAGE_CLASS_STATIC)
8415 type_t *const type = decl->type;
8417 if (is_type_function(skip_typeref(type))) {
8418 if (!warning.unused_function || decl->is_inline)
8421 s = (decl->init.statement != NULL ? "defined" : "declared");
8423 if (!warning.unused_variable)
8429 warningf(&decl->source_position, "'%#T' %s but not used",
8430 type, decl->symbol, s);
8434 static void parse_global_asm(void)
8439 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8440 statement->base.source_position = token.source_position;
8441 statement->asms.asm_text = parse_string_literals();
8442 statement->base.next = unit->global_asm;
8443 unit->global_asm = statement;
8452 * Parse a translation unit.
8454 static void parse_translation_unit(void)
8456 while(token.type != T_EOF) {
8457 switch (token.type) {
8459 /* TODO error in strict mode */
8460 warningf(HERE, "stray ';' outside of function");
8469 parse_external_declaration();
8478 * @return the translation unit or NULL if errors occurred.
8480 void start_parsing(void)
8482 environment_stack = NEW_ARR_F(stack_entry_t, 0);
8483 label_stack = NEW_ARR_F(stack_entry_t, 0);
8484 diagnostic_count = 0;
8488 type_set_output(stderr);
8489 ast_set_output(stderr);
8491 assert(unit == NULL);
8492 unit = allocate_ast_zero(sizeof(unit[0]));
8494 assert(global_scope == NULL);
8495 global_scope = &unit->scope;
8497 assert(scope == NULL);
8498 set_scope(&unit->scope);
8500 initialize_builtin_types();
8503 translation_unit_t *finish_parsing(void)
8505 assert(scope == &unit->scope);
8507 last_declaration = NULL;
8509 assert(global_scope == &unit->scope);
8510 check_unused_globals();
8511 global_scope = NULL;
8513 DEL_ARR_F(environment_stack);
8514 DEL_ARR_F(label_stack);
8516 translation_unit_t *result = unit;
8523 lookahead_bufpos = 0;
8524 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
8527 parse_translation_unit();
8531 * Initialize the parser.
8533 void init_parser(void)
8536 /* add predefined symbols for extended-decl-modifier */
8537 sym_align = symbol_table_insert("align");
8538 sym_allocate = symbol_table_insert("allocate");
8539 sym_dllimport = symbol_table_insert("dllimport");
8540 sym_dllexport = symbol_table_insert("dllexport");
8541 sym_naked = symbol_table_insert("naked");
8542 sym_noinline = symbol_table_insert("noinline");
8543 sym_noreturn = symbol_table_insert("noreturn");
8544 sym_nothrow = symbol_table_insert("nothrow");
8545 sym_novtable = symbol_table_insert("novtable");
8546 sym_property = symbol_table_insert("property");
8547 sym_get = symbol_table_insert("get");
8548 sym_put = symbol_table_insert("put");
8549 sym_selectany = symbol_table_insert("selectany");
8550 sym_thread = symbol_table_insert("thread");
8551 sym_uuid = symbol_table_insert("uuid");
8552 sym_deprecated = symbol_table_insert("deprecated");
8553 sym_restrict = symbol_table_insert("restrict");
8554 sym_noalias = symbol_table_insert("noalias");
8556 memset(token_anchor_set, 0, sizeof(token_anchor_set));
8558 init_expression_parsers();
8559 obstack_init(&temp_obst);
8561 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
8562 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
8566 * Terminate the parser.
8568 void exit_parser(void)
8570 obstack_free(&temp_obst, NULL);