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 declaration_specifiers_t declaration_specifiers_t;
52 struct declaration_specifiers_t {
53 source_position_t source_position;
54 unsigned char declared_storage_class;
55 unsigned char alignment; /**< Alignment, 0 if not set. */
57 decl_modifiers_t decl_modifiers;
62 * An environment for parsing initializers (and compound literals).
64 typedef struct parse_initializer_env_t {
65 type_t *type; /**< the type of the initializer. In case of an
66 array type with unspecified size this gets
67 adjusted to the actual size. */
68 declaration_t *declaration; /**< the declaration that is initialized if any */
69 bool must_be_constant;
70 } parse_initializer_env_t;
72 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
75 static token_t lookahead_buffer[MAX_LOOKAHEAD];
76 static int lookahead_bufpos;
77 static stack_entry_t *environment_stack = NULL;
78 static stack_entry_t *label_stack = NULL;
79 static scope_t *global_scope = NULL;
80 static scope_t *scope = NULL;
81 static declaration_t *last_declaration = NULL;
82 static declaration_t *current_function = NULL;
83 static switch_statement_t *current_switch = NULL;
84 static statement_t *current_loop = NULL;
85 static goto_statement_t *goto_first = NULL;
86 static goto_statement_t *goto_last = NULL;
87 static label_statement_t *label_first = NULL;
88 static label_statement_t *label_last = NULL;
89 static struct obstack temp_obst;
91 /* symbols for Microsoft extended-decl-modifier */
92 static const symbol_t *sym_align = NULL;
93 static const symbol_t *sym_allocate = NULL;
94 static const symbol_t *sym_dllimport = NULL;
95 static const symbol_t *sym_dllexport = NULL;
96 static const symbol_t *sym_naked = NULL;
97 static const symbol_t *sym_noinline = NULL;
98 static const symbol_t *sym_noreturn = NULL;
99 static const symbol_t *sym_nothrow = NULL;
100 static const symbol_t *sym_novtable = NULL;
101 static const symbol_t *sym_property = NULL;
102 static const symbol_t *sym_get = NULL;
103 static const symbol_t *sym_put = NULL;
104 static const symbol_t *sym_selectany = NULL;
105 static const symbol_t *sym_thread = NULL;
106 static const symbol_t *sym_uuid = NULL;
108 /** The current source position. */
109 #define HERE token.source_position
111 static type_t *type_valist;
113 static statement_t *parse_compound_statement(void);
114 static statement_t *parse_statement(void);
116 static expression_t *parse_sub_expression(unsigned precedence);
117 static expression_t *parse_expression(void);
118 static type_t *parse_typename(void);
120 static void parse_compound_type_entries(declaration_t *compound_declaration);
121 static declaration_t *parse_declarator(
122 const declaration_specifiers_t *specifiers, bool may_be_abstract);
123 static declaration_t *record_declaration(declaration_t *declaration);
125 static void semantic_comparison(binary_expression_t *expression);
127 #define STORAGE_CLASSES \
134 #define TYPE_QUALIFIERS \
141 #ifdef PROVIDE_COMPLEX
142 #define COMPLEX_SPECIFIERS \
144 #define IMAGINARY_SPECIFIERS \
147 #define COMPLEX_SPECIFIERS
148 #define IMAGINARY_SPECIFIERS
151 #define TYPE_SPECIFIERS \
166 case T___builtin_va_list: \
170 #define DECLARATION_START \
175 #define TYPENAME_START \
180 * Allocate an AST node with given size and
181 * initialize all fields with zero.
183 static void *allocate_ast_zero(size_t size)
185 void *res = allocate_ast(size);
186 memset(res, 0, size);
190 static declaration_t *allocate_declaration_zero(void)
192 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
193 declaration->type = type_error_type;
194 declaration->alignment = 0;
199 * Returns the size of a statement node.
201 * @param kind the statement kind
203 static size_t get_statement_struct_size(statement_kind_t kind)
205 static const size_t sizes[] = {
206 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
207 [STATEMENT_RETURN] = sizeof(return_statement_t),
208 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
209 [STATEMENT_IF] = sizeof(if_statement_t),
210 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
211 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
212 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
213 [STATEMENT_BREAK] = sizeof(statement_base_t),
214 [STATEMENT_GOTO] = sizeof(goto_statement_t),
215 [STATEMENT_LABEL] = sizeof(label_statement_t),
216 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
217 [STATEMENT_WHILE] = sizeof(while_statement_t),
218 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
219 [STATEMENT_FOR] = sizeof(for_statement_t),
220 [STATEMENT_ASM] = sizeof(asm_statement_t)
222 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
223 assert(sizes[kind] != 0);
228 * Allocate a statement node of given kind and initialize all
231 static statement_t *allocate_statement_zero(statement_kind_t kind)
233 size_t size = get_statement_struct_size(kind);
234 statement_t *res = allocate_ast_zero(size);
236 res->base.kind = kind;
241 * Returns the size of an expression node.
243 * @param kind the expression kind
245 static size_t get_expression_struct_size(expression_kind_t kind)
247 static const size_t sizes[] = {
248 [EXPR_INVALID] = sizeof(expression_base_t),
249 [EXPR_REFERENCE] = sizeof(reference_expression_t),
250 [EXPR_CONST] = sizeof(const_expression_t),
251 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
252 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
253 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
254 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
255 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
256 [EXPR_CALL] = sizeof(call_expression_t),
257 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
258 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
259 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
260 [EXPR_SELECT] = sizeof(select_expression_t),
261 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
262 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
263 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
264 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
265 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
266 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
267 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
268 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
269 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
270 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
271 [EXPR_VA_START] = sizeof(va_start_expression_t),
272 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
273 [EXPR_STATEMENT] = sizeof(statement_expression_t),
275 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
276 return sizes[EXPR_UNARY_FIRST];
278 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
279 return sizes[EXPR_BINARY_FIRST];
281 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
282 assert(sizes[kind] != 0);
287 * Allocate an expression node of given kind and initialize all
290 static expression_t *allocate_expression_zero(expression_kind_t kind)
292 size_t size = get_expression_struct_size(kind);
293 expression_t *res = allocate_ast_zero(size);
295 res->base.kind = kind;
296 res->base.type = type_error_type;
301 * Returns the size of a type node.
303 * @param kind the type kind
305 static size_t get_type_struct_size(type_kind_t kind)
307 static const size_t sizes[] = {
308 [TYPE_ATOMIC] = sizeof(atomic_type_t),
309 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
310 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
311 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
312 [TYPE_ENUM] = sizeof(enum_type_t),
313 [TYPE_FUNCTION] = sizeof(function_type_t),
314 [TYPE_POINTER] = sizeof(pointer_type_t),
315 [TYPE_ARRAY] = sizeof(array_type_t),
316 [TYPE_BUILTIN] = sizeof(builtin_type_t),
317 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
318 [TYPE_TYPEOF] = sizeof(typeof_type_t),
320 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
321 assert(kind <= TYPE_TYPEOF);
322 assert(sizes[kind] != 0);
327 * Allocate a type node of given kind and initialize all
330 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
332 size_t size = get_type_struct_size(kind);
333 type_t *res = obstack_alloc(type_obst, size);
334 memset(res, 0, size);
336 res->base.kind = kind;
337 res->base.source_position = source_position;
342 * Returns the size of an initializer node.
344 * @param kind the initializer kind
346 static size_t get_initializer_size(initializer_kind_t kind)
348 static const size_t sizes[] = {
349 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
350 [INITIALIZER_STRING] = sizeof(initializer_string_t),
351 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
352 [INITIALIZER_LIST] = sizeof(initializer_list_t),
353 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
355 assert(kind < sizeof(sizes) / sizeof(*sizes));
356 assert(sizes[kind] != 0);
361 * Allocate an initializer node of given kind and initialize all
364 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
366 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
373 * Free a type from the type obstack.
375 static void free_type(void *type)
377 obstack_free(type_obst, type);
381 * Returns the index of the top element of the environment stack.
383 static size_t environment_top(void)
385 return ARR_LEN(environment_stack);
389 * Returns the index of the top element of the label stack.
391 static size_t label_top(void)
393 return ARR_LEN(label_stack);
398 * Return the next token.
400 static inline void next_token(void)
402 token = lookahead_buffer[lookahead_bufpos];
403 lookahead_buffer[lookahead_bufpos] = lexer_token;
406 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
409 print_token(stderr, &token);
410 fprintf(stderr, "\n");
415 * Return the next token with a given lookahead.
417 static inline const token_t *look_ahead(int num)
419 assert(num > 0 && num <= MAX_LOOKAHEAD);
420 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
421 return &lookahead_buffer[pos];
424 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
427 * Report a parse error because an expected token was not found.
429 static void parse_error_expected(const char *message, ...)
431 if(message != NULL) {
432 errorf(HERE, "%s", message);
435 va_start(ap, message);
436 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
441 * Report a type error.
443 static void type_error(const char *msg, const source_position_t source_position,
446 errorf(source_position, "%s, but found type '%T'", msg, type);
450 * Report an incompatible type.
452 static void type_error_incompatible(const char *msg,
453 const source_position_t source_position, type_t *type1, type_t *type2)
455 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
459 * Eat an complete block, ie. '{ ... }'.
461 static void eat_block(void)
463 if(token.type == '{')
466 while(token.type != '}') {
467 if(token.type == T_EOF)
469 if(token.type == '{') {
479 * Eat a statement until an ';' token.
481 static void eat_statement(void)
483 while(token.type != ';') {
484 if(token.type == T_EOF)
486 if(token.type == '}')
488 if(token.type == '{') {
498 * Eat a parenthesed term, ie. '( ... )'.
500 static void eat_paren(void)
502 if(token.type == '(')
505 while(token.type != ')') {
506 if(token.type == T_EOF)
508 if(token.type == ')' || token.type == ';' || token.type == '}') {
511 if(token.type == ')') {
515 if(token.type == '(') {
519 if(token.type == '{') {
528 * Expect the the current token is the expected token.
529 * If not, generate an error, eat the current statement,
530 * and goto the end_error label.
532 #define expect(expected) \
534 if(UNLIKELY(token.type != (expected))) { \
535 parse_error_expected(NULL, (expected), 0); \
542 #define expect_block(expected) \
544 if(UNLIKELY(token.type != (expected))) { \
545 parse_error_expected(NULL, (expected), 0); \
552 static void set_scope(scope_t *new_scope)
555 scope->last_declaration = last_declaration;
559 last_declaration = new_scope->last_declaration;
563 * Search a symbol in a given namespace and returns its declaration or
564 * NULL if this symbol was not found.
566 static declaration_t *get_declaration(const symbol_t *const symbol,
567 const namespace_t namespc)
569 declaration_t *declaration = symbol->declaration;
570 for( ; declaration != NULL; declaration = declaration->symbol_next) {
571 if(declaration->namespc == namespc)
579 * pushs an environment_entry on the environment stack and links the
580 * corresponding symbol to the new entry
582 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
584 symbol_t *symbol = declaration->symbol;
585 namespace_t namespc = (namespace_t) declaration->namespc;
587 /* replace/add declaration into declaration list of the symbol */
588 declaration_t *iter = symbol->declaration;
590 symbol->declaration = declaration;
592 declaration_t *iter_last = NULL;
593 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
594 /* replace an entry? */
595 if(iter->namespc == namespc) {
596 if(iter_last == NULL) {
597 symbol->declaration = declaration;
599 iter_last->symbol_next = declaration;
601 declaration->symbol_next = iter->symbol_next;
606 assert(iter_last->symbol_next == NULL);
607 iter_last->symbol_next = declaration;
611 /* remember old declaration */
613 entry.symbol = symbol;
614 entry.old_declaration = iter;
615 entry.namespc = (unsigned short) namespc;
616 ARR_APP1(stack_entry_t, *stack_ptr, entry);
619 static void environment_push(declaration_t *declaration)
621 assert(declaration->source_position.input_name != NULL);
622 assert(declaration->parent_scope != NULL);
623 stack_push(&environment_stack, declaration);
626 static void label_push(declaration_t *declaration)
628 declaration->parent_scope = ¤t_function->scope;
629 stack_push(&label_stack, declaration);
633 * pops symbols from the environment stack until @p new_top is the top element
635 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
637 stack_entry_t *stack = *stack_ptr;
638 size_t top = ARR_LEN(stack);
641 assert(new_top <= top);
645 for(i = top; i > new_top; --i) {
646 stack_entry_t *entry = &stack[i - 1];
648 declaration_t *old_declaration = entry->old_declaration;
649 symbol_t *symbol = entry->symbol;
650 namespace_t namespc = (namespace_t)entry->namespc;
652 /* replace/remove declaration */
653 declaration_t *declaration = symbol->declaration;
654 assert(declaration != NULL);
655 if(declaration->namespc == namespc) {
656 if(old_declaration == NULL) {
657 symbol->declaration = declaration->symbol_next;
659 symbol->declaration = old_declaration;
662 declaration_t *iter_last = declaration;
663 declaration_t *iter = declaration->symbol_next;
664 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
665 /* replace an entry? */
666 if(iter->namespc == namespc) {
667 assert(iter_last != NULL);
668 iter_last->symbol_next = old_declaration;
669 if(old_declaration != NULL) {
670 old_declaration->symbol_next = iter->symbol_next;
675 assert(iter != NULL);
679 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
682 static void environment_pop_to(size_t new_top)
684 stack_pop_to(&environment_stack, new_top);
687 static void label_pop_to(size_t new_top)
689 stack_pop_to(&label_stack, new_top);
693 static int get_rank(const type_t *type)
695 assert(!is_typeref(type));
696 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
697 * and esp. footnote 108). However we can't fold constants (yet), so we
698 * can't decide whether unsigned int is possible, while int always works.
699 * (unsigned int would be preferable when possible... for stuff like
700 * struct { enum { ... } bla : 4; } ) */
701 if(type->kind == TYPE_ENUM)
702 return ATOMIC_TYPE_INT;
704 assert(type->kind == TYPE_ATOMIC);
705 return type->atomic.akind;
708 static type_t *promote_integer(type_t *type)
710 if(type->kind == TYPE_BITFIELD)
711 type = type->bitfield.base;
713 if(get_rank(type) < ATOMIC_TYPE_INT)
720 * Create a cast expression.
722 * @param expression the expression to cast
723 * @param dest_type the destination type
725 static expression_t *create_cast_expression(expression_t *expression,
728 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
730 cast->unary.value = expression;
731 cast->base.type = dest_type;
737 * Check if a given expression represents the 0 pointer constant.
739 static bool is_null_pointer_constant(const expression_t *expression)
741 /* skip void* cast */
742 if(expression->kind == EXPR_UNARY_CAST
743 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
744 expression = expression->unary.value;
747 /* TODO: not correct yet, should be any constant integer expression
748 * which evaluates to 0 */
749 if (expression->kind != EXPR_CONST)
752 type_t *const type = skip_typeref(expression->base.type);
753 if (!is_type_integer(type))
756 return expression->conste.v.int_value == 0;
760 * Create an implicit cast expression.
762 * @param expression the expression to cast
763 * @param dest_type the destination type
765 static expression_t *create_implicit_cast(expression_t *expression,
768 type_t *const source_type = expression->base.type;
770 if (source_type == dest_type)
773 return create_cast_expression(expression, dest_type);
776 /** Implements the rules from § 6.5.16.1 */
777 static type_t *semantic_assign(type_t *orig_type_left,
778 const expression_t *const right,
781 type_t *const orig_type_right = right->base.type;
782 type_t *const type_left = skip_typeref(orig_type_left);
783 type_t *const type_right = skip_typeref(orig_type_right);
785 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
786 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
787 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
788 && is_type_pointer(type_right))) {
789 return orig_type_left;
792 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
793 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
794 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
796 /* the left type has all qualifiers from the right type */
797 unsigned missing_qualifiers
798 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
799 if(missing_qualifiers != 0) {
800 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
801 return orig_type_left;
804 points_to_left = get_unqualified_type(points_to_left);
805 points_to_right = get_unqualified_type(points_to_right);
807 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
808 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
809 return orig_type_left;
812 if (!types_compatible(points_to_left, points_to_right)) {
813 warningf(right->base.source_position,
814 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
815 orig_type_left, context, right, orig_type_right);
818 return orig_type_left;
821 if ((is_type_compound(type_left) && is_type_compound(type_right))
822 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
823 type_t *const unqual_type_left = get_unqualified_type(type_left);
824 type_t *const unqual_type_right = get_unqualified_type(type_right);
825 if (types_compatible(unqual_type_left, unqual_type_right)) {
826 return orig_type_left;
830 if (!is_type_valid(type_left))
833 if (!is_type_valid(type_right))
834 return orig_type_right;
839 static expression_t *parse_constant_expression(void)
841 /* start parsing at precedence 7 (conditional expression) */
842 expression_t *result = parse_sub_expression(7);
844 if(!is_constant_expression(result)) {
845 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
851 static expression_t *parse_assignment_expression(void)
853 /* start parsing at precedence 2 (assignment expression) */
854 return parse_sub_expression(2);
857 static type_t *make_global_typedef(const char *name, type_t *type)
859 symbol_t *const symbol = symbol_table_insert(name);
861 declaration_t *const declaration = allocate_declaration_zero();
862 declaration->namespc = NAMESPACE_NORMAL;
863 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
864 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
865 declaration->type = type;
866 declaration->symbol = symbol;
867 declaration->source_position = builtin_source_position;
869 record_declaration(declaration);
871 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
872 typedef_type->typedeft.declaration = declaration;
877 static string_t parse_string_literals(void)
879 assert(token.type == T_STRING_LITERAL);
880 string_t result = token.v.string;
884 while (token.type == T_STRING_LITERAL) {
885 result = concat_strings(&result, &token.v.string);
892 static void parse_attributes(void)
896 case T___attribute__: {
904 errorf(HERE, "EOF while parsing attribute");
923 if(token.type != T_STRING_LITERAL) {
924 parse_error_expected("while parsing assembler attribute",
929 parse_string_literals();
934 goto attributes_finished;
943 static designator_t *parse_designation(void)
945 designator_t *result = NULL;
946 designator_t *last = NULL;
949 designator_t *designator;
952 designator = allocate_ast_zero(sizeof(designator[0]));
953 designator->source_position = token.source_position;
955 designator->array_index = parse_constant_expression();
959 designator = allocate_ast_zero(sizeof(designator[0]));
960 designator->source_position = token.source_position;
962 if(token.type != T_IDENTIFIER) {
963 parse_error_expected("while parsing designator",
967 designator->symbol = token.v.symbol;
975 assert(designator != NULL);
977 last->next = designator;
987 static initializer_t *initializer_from_string(array_type_t *type,
988 const string_t *const string)
990 /* TODO: check len vs. size of array type */
993 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
994 initializer->string.string = *string;
999 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1000 wide_string_t *const string)
1002 /* TODO: check len vs. size of array type */
1005 initializer_t *const initializer =
1006 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1007 initializer->wide_string.string = *string;
1013 * Build an initializer from a given expression.
1015 static initializer_t *initializer_from_expression(type_t *orig_type,
1016 expression_t *expression)
1018 /* TODO check that expression is a constant expression */
1020 /* § 6.7.8.14/15 char array may be initialized by string literals */
1021 type_t *type = skip_typeref(orig_type);
1022 type_t *expr_type_orig = expression->base.type;
1023 type_t *expr_type = skip_typeref(expr_type_orig);
1024 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1025 array_type_t *const array_type = &type->array;
1026 type_t *const element_type = skip_typeref(array_type->element_type);
1028 if (element_type->kind == TYPE_ATOMIC) {
1029 atomic_type_kind_t akind = element_type->atomic.akind;
1030 switch (expression->kind) {
1031 case EXPR_STRING_LITERAL:
1032 if (akind == ATOMIC_TYPE_CHAR
1033 || akind == ATOMIC_TYPE_SCHAR
1034 || akind == ATOMIC_TYPE_UCHAR) {
1035 return initializer_from_string(array_type,
1036 &expression->string.value);
1039 case EXPR_WIDE_STRING_LITERAL: {
1040 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1041 if (get_unqualified_type(element_type) == bare_wchar_type) {
1042 return initializer_from_wide_string(array_type,
1043 &expression->wide_string.value);
1053 type_t *const res_type = semantic_assign(type, expression, "initializer");
1054 if (res_type == NULL)
1057 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1058 result->value.value = create_implicit_cast(expression, res_type);
1064 * Checks if a given expression can be used as an constant initializer.
1066 static bool is_initializer_constant(const expression_t *expression)
1068 return is_constant_expression(expression)
1069 || is_address_constant(expression);
1073 * Parses an scalar initializer.
1075 * § 6.7.8.11; eat {} without warning
1077 static initializer_t *parse_scalar_initializer(type_t *type,
1078 bool must_be_constant)
1080 /* there might be extra {} hierarchies */
1082 while(token.type == '{') {
1085 warningf(HERE, "extra curly braces around scalar initializer");
1090 expression_t *expression = parse_assignment_expression();
1091 if(must_be_constant && !is_initializer_constant(expression)) {
1092 errorf(expression->base.source_position,
1093 "Initialisation expression '%E' is not constant\n",
1097 initializer_t *initializer = initializer_from_expression(type, expression);
1099 if(initializer == NULL) {
1100 errorf(expression->base.source_position,
1101 "expression '%E' doesn't match expected type '%T'",
1107 bool additional_warning_displayed = false;
1109 if(token.type == ',') {
1112 if(token.type != '}') {
1113 if(!additional_warning_displayed) {
1114 warningf(HERE, "additional elements in scalar initializer");
1115 additional_warning_displayed = true;
1126 * An entry in the type path.
1128 typedef struct type_path_entry_t type_path_entry_t;
1129 struct type_path_entry_t {
1130 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1132 size_t index; /**< For array types: the current index. */
1133 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1138 * A type path expression a position inside compound or array types.
1140 typedef struct type_path_t type_path_t;
1141 struct type_path_t {
1142 type_path_entry_t *path; /**< An flexible array containing the current path. */
1143 type_t *top_type; /**< type of the element the path points */
1144 size_t max_index; /**< largest index in outermost array */
1148 * Prints a type path for debugging.
1150 static __attribute__((unused)) void debug_print_type_path(
1151 const type_path_t *path)
1153 size_t len = ARR_LEN(path->path);
1155 for(size_t i = 0; i < len; ++i) {
1156 const type_path_entry_t *entry = & path->path[i];
1158 type_t *type = skip_typeref(entry->type);
1159 if(is_type_compound(type)) {
1160 /* in gcc mode structs can have no members */
1161 if(entry->v.compound_entry == NULL) {
1165 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1166 } else if(is_type_array(type)) {
1167 fprintf(stderr, "[%u]", entry->v.index);
1169 fprintf(stderr, "-INVALID-");
1172 if(path->top_type != NULL) {
1173 fprintf(stderr, " (");
1174 print_type(path->top_type);
1175 fprintf(stderr, ")");
1180 * Return the top type path entry, ie. in a path
1181 * (type).a.b returns the b.
1183 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1185 size_t len = ARR_LEN(path->path);
1187 return &path->path[len-1];
1191 * Enlarge the type path by an (empty) element.
1193 static type_path_entry_t *append_to_type_path(type_path_t *path)
1195 size_t len = ARR_LEN(path->path);
1196 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1198 type_path_entry_t *result = & path->path[len];
1199 memset(result, 0, sizeof(result[0]));
1204 * Descending into a sub-type. Enter the scope of the current
1207 static void descend_into_subtype(type_path_t *path)
1209 type_t *orig_top_type = path->top_type;
1210 type_t *top_type = skip_typeref(orig_top_type);
1212 assert(is_type_compound(top_type) || is_type_array(top_type));
1214 type_path_entry_t *top = append_to_type_path(path);
1215 top->type = top_type;
1217 if(is_type_compound(top_type)) {
1218 declaration_t *declaration = top_type->compound.declaration;
1219 declaration_t *entry = declaration->scope.declarations;
1220 top->v.compound_entry = entry;
1223 path->top_type = entry->type;
1225 path->top_type = NULL;
1228 assert(is_type_array(top_type));
1231 path->top_type = top_type->array.element_type;
1236 * Pop an entry from the given type path, ie. returning from
1237 * (type).a.b to (type).a
1239 static void ascend_from_subtype(type_path_t *path)
1241 type_path_entry_t *top = get_type_path_top(path);
1243 path->top_type = top->type;
1245 size_t len = ARR_LEN(path->path);
1246 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1250 * Pop entries from the given type path until the given
1251 * path level is reached.
1253 static void ascend_to(type_path_t *path, size_t top_path_level)
1255 size_t len = ARR_LEN(path->path);
1257 while(len > top_path_level) {
1258 ascend_from_subtype(path);
1259 len = ARR_LEN(path->path);
1263 static bool walk_designator(type_path_t *path, const designator_t *designator,
1264 bool used_in_offsetof)
1266 for( ; designator != NULL; designator = designator->next) {
1267 type_path_entry_t *top = get_type_path_top(path);
1268 type_t *orig_type = top->type;
1270 type_t *type = skip_typeref(orig_type);
1272 if(designator->symbol != NULL) {
1273 symbol_t *symbol = designator->symbol;
1274 if(!is_type_compound(type)) {
1275 if(is_type_valid(type)) {
1276 errorf(designator->source_position,
1277 "'.%Y' designator used for non-compound type '%T'",
1283 declaration_t *declaration = type->compound.declaration;
1284 declaration_t *iter = declaration->scope.declarations;
1285 for( ; iter != NULL; iter = iter->next) {
1286 if(iter->symbol == symbol) {
1291 errorf(designator->source_position,
1292 "'%T' has no member named '%Y'", orig_type, symbol);
1295 if(used_in_offsetof) {
1296 type_t *real_type = skip_typeref(iter->type);
1297 if(real_type->kind == TYPE_BITFIELD) {
1298 errorf(designator->source_position,
1299 "offsetof designator '%Y' may not specify bitfield",
1305 top->type = orig_type;
1306 top->v.compound_entry = iter;
1307 orig_type = iter->type;
1309 expression_t *array_index = designator->array_index;
1310 assert(designator->array_index != NULL);
1312 if(!is_type_array(type)) {
1313 if(is_type_valid(type)) {
1314 errorf(designator->source_position,
1315 "[%E] designator used for non-array type '%T'",
1316 array_index, orig_type);
1320 if(!is_type_valid(array_index->base.type)) {
1324 long index = fold_constant(array_index);
1325 if(!used_in_offsetof) {
1327 errorf(designator->source_position,
1328 "array index [%E] must be positive", array_index);
1331 if(type->array.size_constant == true) {
1332 long array_size = type->array.size;
1333 if(index >= array_size) {
1334 errorf(designator->source_position,
1335 "designator [%E] (%d) exceeds array size %d",
1336 array_index, index, array_size);
1342 top->type = orig_type;
1343 top->v.index = (size_t) index;
1344 orig_type = type->array.element_type;
1346 path->top_type = orig_type;
1348 if(designator->next != NULL) {
1349 descend_into_subtype(path);
1358 static void advance_current_object(type_path_t *path, size_t top_path_level)
1360 type_path_entry_t *top = get_type_path_top(path);
1362 type_t *type = skip_typeref(top->type);
1363 if(is_type_union(type)) {
1364 /* in unions only the first element is initialized */
1365 top->v.compound_entry = NULL;
1366 } else if(is_type_struct(type)) {
1367 declaration_t *entry = top->v.compound_entry;
1369 entry = entry->next;
1370 top->v.compound_entry = entry;
1372 path->top_type = entry->type;
1376 assert(is_type_array(type));
1380 if(!type->array.size_constant || top->v.index < type->array.size) {
1385 /* we're past the last member of the current sub-aggregate, try if we
1386 * can ascend in the type hierarchy and continue with another subobject */
1387 size_t len = ARR_LEN(path->path);
1389 if(len > top_path_level) {
1390 ascend_from_subtype(path);
1391 advance_current_object(path, top_path_level);
1393 path->top_type = NULL;
1398 * skip any {...} blocks until a closing braket is reached.
1400 static void skip_initializers(void)
1402 if(token.type == '{')
1405 while(token.type != '}') {
1406 if(token.type == T_EOF)
1408 if(token.type == '{') {
1417 * Parse a part of an initialiser for a struct or union,
1419 static initializer_t *parse_sub_initializer(type_path_t *path,
1420 type_t *outer_type, size_t top_path_level,
1421 parse_initializer_env_t *env)
1423 if(token.type == '}') {
1424 /* empty initializer */
1428 type_t *orig_type = path->top_type;
1429 type_t *type = NULL;
1431 if (orig_type == NULL) {
1432 /* We are initializing an empty compound. */
1434 type = skip_typeref(orig_type);
1436 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1437 * initializers in this case. */
1438 if(!is_type_valid(type)) {
1439 skip_initializers();
1444 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1447 designator_t *designator = NULL;
1448 if(token.type == '.' || token.type == '[') {
1449 designator = parse_designation();
1451 /* reset path to toplevel, evaluate designator from there */
1452 ascend_to(path, top_path_level);
1453 if(!walk_designator(path, designator, false)) {
1454 /* can't continue after designation error */
1458 initializer_t *designator_initializer
1459 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1460 designator_initializer->designator.designator = designator;
1461 ARR_APP1(initializer_t*, initializers, designator_initializer);
1466 if(token.type == '{') {
1467 if(type != NULL && is_type_scalar(type)) {
1468 sub = parse_scalar_initializer(type, env->must_be_constant);
1472 if (env->declaration != NULL)
1473 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1474 env->declaration->symbol);
1476 errorf(HERE, "extra brace group at end of initializer");
1478 descend_into_subtype(path);
1480 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1484 ascend_from_subtype(path);
1488 goto error_parse_next;
1492 /* must be an expression */
1493 expression_t *expression = parse_assignment_expression();
1495 if(env->must_be_constant && !is_initializer_constant(expression)) {
1496 errorf(expression->base.source_position,
1497 "Initialisation expression '%E' is not constant\n",
1502 /* we are already outside, ... */
1506 /* handle { "string" } special case */
1507 if((expression->kind == EXPR_STRING_LITERAL
1508 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1509 && outer_type != NULL) {
1510 sub = initializer_from_expression(outer_type, expression);
1512 if(token.type == ',') {
1515 if(token.type != '}') {
1516 warningf(HERE, "excessive elements in initializer for type '%T'",
1519 /* TODO: eat , ... */
1524 /* descend into subtypes until expression matches type */
1526 orig_type = path->top_type;
1527 type = skip_typeref(orig_type);
1529 sub = initializer_from_expression(orig_type, expression);
1533 if(!is_type_valid(type)) {
1536 if(is_type_scalar(type)) {
1537 errorf(expression->base.source_position,
1538 "expression '%E' doesn't match expected type '%T'",
1539 expression, orig_type);
1543 descend_into_subtype(path);
1547 /* update largest index of top array */
1548 const type_path_entry_t *first = &path->path[0];
1549 type_t *first_type = first->type;
1550 first_type = skip_typeref(first_type);
1551 if(is_type_array(first_type)) {
1552 size_t index = first->v.index;
1553 if(index > path->max_index)
1554 path->max_index = index;
1558 /* append to initializers list */
1559 ARR_APP1(initializer_t*, initializers, sub);
1562 if(env->declaration != NULL)
1563 warningf(HERE, "excess elements in struct initializer for '%Y'",
1564 env->declaration->symbol);
1566 warningf(HERE, "excess elements in struct initializer");
1570 if(token.type == '}') {
1574 if(token.type == '}') {
1579 /* advance to the next declaration if we are not at the end */
1580 advance_current_object(path, top_path_level);
1581 orig_type = path->top_type;
1582 if(orig_type != NULL)
1583 type = skip_typeref(orig_type);
1589 size_t len = ARR_LEN(initializers);
1590 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1591 initializer_t *result = allocate_ast_zero(size);
1592 result->kind = INITIALIZER_LIST;
1593 result->list.len = len;
1594 memcpy(&result->list.initializers, initializers,
1595 len * sizeof(initializers[0]));
1597 DEL_ARR_F(initializers);
1598 ascend_to(path, top_path_level);
1603 skip_initializers();
1604 DEL_ARR_F(initializers);
1605 ascend_to(path, top_path_level);
1610 * Parses an initializer. Parsers either a compound literal
1611 * (env->declaration == NULL) or an initializer of a declaration.
1613 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1615 type_t *type = skip_typeref(env->type);
1616 initializer_t *result = NULL;
1619 if(is_type_scalar(type)) {
1620 result = parse_scalar_initializer(type, env->must_be_constant);
1621 } else if(token.type == '{') {
1625 memset(&path, 0, sizeof(path));
1626 path.top_type = env->type;
1627 path.path = NEW_ARR_F(type_path_entry_t, 0);
1629 descend_into_subtype(&path);
1631 result = parse_sub_initializer(&path, env->type, 1, env);
1633 max_index = path.max_index;
1634 DEL_ARR_F(path.path);
1638 /* parse_scalar_initializer() also works in this case: we simply
1639 * have an expression without {} around it */
1640 result = parse_scalar_initializer(type, env->must_be_constant);
1643 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1644 * the array type size */
1645 if(is_type_array(type) && type->array.size_expression == NULL
1646 && result != NULL) {
1648 switch (result->kind) {
1649 case INITIALIZER_LIST:
1650 size = max_index + 1;
1653 case INITIALIZER_STRING:
1654 size = result->string.string.size;
1657 case INITIALIZER_WIDE_STRING:
1658 size = result->wide_string.string.size;
1662 panic("invalid initializer type");
1665 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1666 cnst->base.type = type_size_t;
1667 cnst->conste.v.int_value = size;
1669 type_t *new_type = duplicate_type(type);
1671 new_type->array.size_expression = cnst;
1672 new_type->array.size_constant = true;
1673 new_type->array.size = size;
1674 env->type = new_type;
1682 static declaration_t *append_declaration(declaration_t *declaration);
1684 static declaration_t *parse_compound_type_specifier(bool is_struct)
1692 symbol_t *symbol = NULL;
1693 declaration_t *declaration = NULL;
1695 if (token.type == T___attribute__) {
1700 if(token.type == T_IDENTIFIER) {
1701 symbol = token.v.symbol;
1705 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1707 declaration = get_declaration(symbol, NAMESPACE_UNION);
1709 } else if(token.type != '{') {
1711 parse_error_expected("while parsing struct type specifier",
1712 T_IDENTIFIER, '{', 0);
1714 parse_error_expected("while parsing union type specifier",
1715 T_IDENTIFIER, '{', 0);
1721 if(declaration == NULL) {
1722 declaration = allocate_declaration_zero();
1723 declaration->namespc =
1724 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1725 declaration->source_position = token.source_position;
1726 declaration->symbol = symbol;
1727 declaration->parent_scope = scope;
1728 if (symbol != NULL) {
1729 environment_push(declaration);
1731 append_declaration(declaration);
1734 if(token.type == '{') {
1735 if(declaration->init.is_defined) {
1736 assert(symbol != NULL);
1737 errorf(HERE, "multiple definitions of '%s %Y'",
1738 is_struct ? "struct" : "union", symbol);
1739 declaration->scope.declarations = NULL;
1741 declaration->init.is_defined = true;
1743 parse_compound_type_entries(declaration);
1750 static void parse_enum_entries(type_t *const enum_type)
1754 if(token.type == '}') {
1756 errorf(HERE, "empty enum not allowed");
1761 if(token.type != T_IDENTIFIER) {
1762 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1767 declaration_t *const entry = allocate_declaration_zero();
1768 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1769 entry->type = enum_type;
1770 entry->symbol = token.v.symbol;
1771 entry->source_position = token.source_position;
1774 if(token.type == '=') {
1776 expression_t *value = parse_constant_expression();
1778 value = create_implicit_cast(value, enum_type);
1779 entry->init.enum_value = value;
1784 record_declaration(entry);
1786 if(token.type != ',')
1789 } while(token.type != '}');
1797 static type_t *parse_enum_specifier(void)
1801 declaration_t *declaration;
1804 if(token.type == T_IDENTIFIER) {
1805 symbol = token.v.symbol;
1808 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1809 } else if(token.type != '{') {
1810 parse_error_expected("while parsing enum type specifier",
1811 T_IDENTIFIER, '{', 0);
1818 if(declaration == NULL) {
1819 declaration = allocate_declaration_zero();
1820 declaration->namespc = NAMESPACE_ENUM;
1821 declaration->source_position = token.source_position;
1822 declaration->symbol = symbol;
1823 declaration->parent_scope = scope;
1826 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1827 type->enumt.declaration = declaration;
1829 if(token.type == '{') {
1830 if(declaration->init.is_defined) {
1831 errorf(HERE, "multiple definitions of enum %Y", symbol);
1833 if (symbol != NULL) {
1834 environment_push(declaration);
1836 append_declaration(declaration);
1837 declaration->init.is_defined = 1;
1839 parse_enum_entries(type);
1847 * if a symbol is a typedef to another type, return true
1849 static bool is_typedef_symbol(symbol_t *symbol)
1851 const declaration_t *const declaration =
1852 get_declaration(symbol, NAMESPACE_NORMAL);
1854 declaration != NULL &&
1855 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1858 static type_t *parse_typeof(void)
1866 expression_t *expression = NULL;
1869 switch(token.type) {
1870 case T___extension__:
1871 /* this can be a prefix to a typename or an expression */
1872 /* we simply eat it now. */
1875 } while(token.type == T___extension__);
1879 if(is_typedef_symbol(token.v.symbol)) {
1880 type = parse_typename();
1882 expression = parse_expression();
1883 type = expression->base.type;
1888 type = parse_typename();
1892 expression = parse_expression();
1893 type = expression->base.type;
1899 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1900 typeof_type->typeoft.expression = expression;
1901 typeof_type->typeoft.typeof_type = type;
1909 SPECIFIER_SIGNED = 1 << 0,
1910 SPECIFIER_UNSIGNED = 1 << 1,
1911 SPECIFIER_LONG = 1 << 2,
1912 SPECIFIER_INT = 1 << 3,
1913 SPECIFIER_DOUBLE = 1 << 4,
1914 SPECIFIER_CHAR = 1 << 5,
1915 SPECIFIER_SHORT = 1 << 6,
1916 SPECIFIER_LONG_LONG = 1 << 7,
1917 SPECIFIER_FLOAT = 1 << 8,
1918 SPECIFIER_BOOL = 1 << 9,
1919 SPECIFIER_VOID = 1 << 10,
1920 #ifdef PROVIDE_COMPLEX
1921 SPECIFIER_COMPLEX = 1 << 11,
1922 SPECIFIER_IMAGINARY = 1 << 12,
1926 static type_t *create_builtin_type(symbol_t *const symbol,
1927 type_t *const real_type)
1929 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1930 type->builtin.symbol = symbol;
1931 type->builtin.real_type = real_type;
1933 type_t *result = typehash_insert(type);
1934 if (type != result) {
1941 static type_t *get_typedef_type(symbol_t *symbol)
1943 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1944 if(declaration == NULL
1945 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1948 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1949 type->typedeft.declaration = declaration;
1955 * check for the allowed MS alignment values.
1957 static bool check_elignment_value(long long intvalue) {
1958 if(intvalue < 1 || intvalue > 8192) {
1959 errorf(HERE, "illegal alignment value");
1962 unsigned v = (unsigned)intvalue;
1963 for(unsigned i = 1; i <= 8192; i += i) {
1967 errorf(HERE, "alignment must be power of two");
1971 #define DET_MOD(name, tag) do { \
1972 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
1973 *modifiers |= tag; \
1976 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
1979 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
1982 switch(token.type) {
1984 symbol = token.v.symbol;
1985 if(symbol == sym_align) {
1988 if(token.type != T_INTEGER)
1990 if(check_elignment_value(token.v.intvalue)) {
1991 if(specifiers->alignment != 0)
1992 warningf(HERE, "align used more than once");
1993 specifiers->alignment = (unsigned char)token.v.intvalue;
1997 } else if(symbol == sym_allocate) {
2000 if(token.type != T_IDENTIFIER)
2002 (void)token.v.symbol;
2004 } else if(symbol == sym_dllimport) {
2006 DET_MOD(dllimport, DM_DLLIMPORT);
2007 } else if(symbol == sym_dllexport) {
2009 DET_MOD(dllexport, DM_DLLEXPORT);
2010 } else if(symbol == sym_thread) {
2012 DET_MOD(thread, DM_THREAD);
2013 } else if(symbol == sym_naked) {
2015 DET_MOD(naked, DM_NAKED);
2016 } else if(symbol == sym_noinline) {
2018 DET_MOD(noinline, DM_NOINLINE);
2019 } else if(symbol == sym_noreturn) {
2021 DET_MOD(noreturn, DM_NORETURN);
2022 } else if(symbol == sym_nothrow) {
2024 DET_MOD(nothrow, DM_NOTHROW);
2025 } else if(symbol == sym_novtable) {
2027 DET_MOD(novtable, DM_NOVTABLE);
2028 } else if(symbol == sym_property) {
2031 if(token.type != T_IDENTIFIER)
2033 if(token.v.symbol == sym_get) {
2034 } else if(token.v.symbol == sym_put) {
2039 if(token.type != T_IDENTIFIER)
2041 (void)token.v.symbol;
2044 } else if(symbol == sym_selectany) {
2046 DET_MOD(selectany, DM_SELECTANY);
2047 } else if(symbol == sym_uuid) {
2050 if(token.type != T_STRING_LITERAL)
2064 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2066 type_t *type = NULL;
2067 unsigned type_qualifiers = 0;
2068 unsigned type_specifiers = 0;
2071 specifiers->source_position = token.source_position;
2074 switch(token.type) {
2077 #define MATCH_STORAGE_CLASS(token, class) \
2079 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2080 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2082 specifiers->declared_storage_class = class; \
2086 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2087 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2088 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2089 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2090 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2095 parse_microsoft_extended_decl_modifier(specifiers);
2100 switch (specifiers->declared_storage_class) {
2101 case STORAGE_CLASS_NONE:
2102 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2105 case STORAGE_CLASS_EXTERN:
2106 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2109 case STORAGE_CLASS_STATIC:
2110 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2114 errorf(HERE, "multiple storage classes in declaration specifiers");
2120 /* type qualifiers */
2121 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2123 type_qualifiers |= qualifier; \
2127 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2128 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2129 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2131 case T___extension__:
2136 /* type specifiers */
2137 #define MATCH_SPECIFIER(token, specifier, name) \
2140 if(type_specifiers & specifier) { \
2141 errorf(HERE, "multiple " name " type specifiers given"); \
2143 type_specifiers |= specifier; \
2147 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2148 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2149 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2150 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2151 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2152 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2153 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2154 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2155 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2156 #ifdef PROVIDE_COMPLEX
2157 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2158 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2161 /* only in microsoft mode */
2162 specifiers->decl_modifiers |= DM_FORCEINLINE;
2166 specifiers->is_inline = true;
2171 if(type_specifiers & SPECIFIER_LONG_LONG) {
2172 errorf(HERE, "multiple type specifiers given");
2173 } else if(type_specifiers & SPECIFIER_LONG) {
2174 type_specifiers |= SPECIFIER_LONG_LONG;
2176 type_specifiers |= SPECIFIER_LONG;
2181 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2183 type->compound.declaration = parse_compound_type_specifier(true);
2187 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2189 type->compound.declaration = parse_compound_type_specifier(false);
2193 type = parse_enum_specifier();
2196 type = parse_typeof();
2198 case T___builtin_va_list:
2199 type = duplicate_type(type_valist);
2203 case T___attribute__:
2207 case T_IDENTIFIER: {
2208 /* only parse identifier if we haven't found a type yet */
2209 if(type != NULL || type_specifiers != 0)
2210 goto finish_specifiers;
2212 type_t *typedef_type = get_typedef_type(token.v.symbol);
2214 if(typedef_type == NULL)
2215 goto finish_specifiers;
2218 type = typedef_type;
2222 /* function specifier */
2224 goto finish_specifiers;
2231 atomic_type_kind_t atomic_type;
2233 /* match valid basic types */
2234 switch(type_specifiers) {
2235 case SPECIFIER_VOID:
2236 atomic_type = ATOMIC_TYPE_VOID;
2238 case SPECIFIER_CHAR:
2239 atomic_type = ATOMIC_TYPE_CHAR;
2241 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2242 atomic_type = ATOMIC_TYPE_SCHAR;
2244 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2245 atomic_type = ATOMIC_TYPE_UCHAR;
2247 case SPECIFIER_SHORT:
2248 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2249 case SPECIFIER_SHORT | SPECIFIER_INT:
2250 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2251 atomic_type = ATOMIC_TYPE_SHORT;
2253 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2254 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2255 atomic_type = ATOMIC_TYPE_USHORT;
2258 case SPECIFIER_SIGNED:
2259 case SPECIFIER_SIGNED | SPECIFIER_INT:
2260 atomic_type = ATOMIC_TYPE_INT;
2262 case SPECIFIER_UNSIGNED:
2263 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2264 atomic_type = ATOMIC_TYPE_UINT;
2266 case SPECIFIER_LONG:
2267 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2268 case SPECIFIER_LONG | SPECIFIER_INT:
2269 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2270 atomic_type = ATOMIC_TYPE_LONG;
2272 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2273 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2274 atomic_type = ATOMIC_TYPE_ULONG;
2276 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2277 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2278 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2279 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2281 atomic_type = ATOMIC_TYPE_LONGLONG;
2283 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2284 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2286 atomic_type = ATOMIC_TYPE_ULONGLONG;
2288 case SPECIFIER_FLOAT:
2289 atomic_type = ATOMIC_TYPE_FLOAT;
2291 case SPECIFIER_DOUBLE:
2292 atomic_type = ATOMIC_TYPE_DOUBLE;
2294 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2295 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2297 case SPECIFIER_BOOL:
2298 atomic_type = ATOMIC_TYPE_BOOL;
2300 #ifdef PROVIDE_COMPLEX
2301 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2302 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2304 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2305 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2307 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2308 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2310 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2311 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2313 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2314 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2316 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2317 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2321 /* invalid specifier combination, give an error message */
2322 if(type_specifiers == 0) {
2323 if (! strict_mode) {
2324 if (warning.implicit_int) {
2325 warningf(HERE, "no type specifiers in declaration, using 'int'");
2327 atomic_type = ATOMIC_TYPE_INT;
2330 errorf(HERE, "no type specifiers given in declaration");
2332 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2333 (type_specifiers & SPECIFIER_UNSIGNED)) {
2334 errorf(HERE, "signed and unsigned specifiers gives");
2335 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2336 errorf(HERE, "only integer types can be signed or unsigned");
2338 errorf(HERE, "multiple datatypes in declaration");
2340 atomic_type = ATOMIC_TYPE_INVALID;
2343 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2344 type->atomic.akind = atomic_type;
2347 if(type_specifiers != 0) {
2348 errorf(HERE, "multiple datatypes in declaration");
2352 type->base.qualifiers = type_qualifiers;
2354 type_t *result = typehash_insert(type);
2355 if(newtype && result != type) {
2359 specifiers->type = result;
2364 static type_qualifiers_t parse_type_qualifiers(void)
2366 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2369 switch(token.type) {
2370 /* type qualifiers */
2371 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2372 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2373 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2376 return type_qualifiers;
2381 static declaration_t *parse_identifier_list(void)
2383 declaration_t *declarations = NULL;
2384 declaration_t *last_declaration = NULL;
2386 declaration_t *const declaration = allocate_declaration_zero();
2387 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2388 declaration->source_position = token.source_position;
2389 declaration->symbol = token.v.symbol;
2392 if(last_declaration != NULL) {
2393 last_declaration->next = declaration;
2395 declarations = declaration;
2397 last_declaration = declaration;
2399 if(token.type != ',')
2402 } while(token.type == T_IDENTIFIER);
2404 return declarations;
2407 static void semantic_parameter(declaration_t *declaration)
2409 /* TODO: improve error messages */
2411 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2412 errorf(HERE, "typedef not allowed in parameter list");
2413 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2414 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2415 errorf(HERE, "parameter may only have none or register storage class");
2418 type_t *const orig_type = declaration->type;
2419 type_t * type = skip_typeref(orig_type);
2421 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2422 * into a pointer. § 6.7.5.3 (7) */
2423 if (is_type_array(type)) {
2424 type_t *const element_type = type->array.element_type;
2426 type = make_pointer_type(element_type, type->base.qualifiers);
2428 declaration->type = type;
2431 if(is_type_incomplete(type)) {
2432 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2433 orig_type, declaration->symbol);
2437 static declaration_t *parse_parameter(void)
2439 declaration_specifiers_t specifiers;
2440 memset(&specifiers, 0, sizeof(specifiers));
2442 parse_declaration_specifiers(&specifiers);
2444 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2446 semantic_parameter(declaration);
2451 static declaration_t *parse_parameters(function_type_t *type)
2453 if(token.type == T_IDENTIFIER) {
2454 symbol_t *symbol = token.v.symbol;
2455 if(!is_typedef_symbol(symbol)) {
2456 type->kr_style_parameters = true;
2457 return parse_identifier_list();
2461 if(token.type == ')') {
2462 type->unspecified_parameters = 1;
2465 if(token.type == T_void && look_ahead(1)->type == ')') {
2470 declaration_t *declarations = NULL;
2471 declaration_t *declaration;
2472 declaration_t *last_declaration = NULL;
2473 function_parameter_t *parameter;
2474 function_parameter_t *last_parameter = NULL;
2477 switch(token.type) {
2481 return declarations;
2484 case T___extension__:
2486 declaration = parse_parameter();
2488 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2489 memset(parameter, 0, sizeof(parameter[0]));
2490 parameter->type = declaration->type;
2492 if(last_parameter != NULL) {
2493 last_declaration->next = declaration;
2494 last_parameter->next = parameter;
2496 type->parameters = parameter;
2497 declarations = declaration;
2499 last_parameter = parameter;
2500 last_declaration = declaration;
2504 return declarations;
2506 if(token.type != ',')
2507 return declarations;
2517 } construct_type_kind_t;
2519 typedef struct construct_type_t construct_type_t;
2520 struct construct_type_t {
2521 construct_type_kind_t kind;
2522 construct_type_t *next;
2525 typedef struct parsed_pointer_t parsed_pointer_t;
2526 struct parsed_pointer_t {
2527 construct_type_t construct_type;
2528 type_qualifiers_t type_qualifiers;
2531 typedef struct construct_function_type_t construct_function_type_t;
2532 struct construct_function_type_t {
2533 construct_type_t construct_type;
2534 type_t *function_type;
2537 typedef struct parsed_array_t parsed_array_t;
2538 struct parsed_array_t {
2539 construct_type_t construct_type;
2540 type_qualifiers_t type_qualifiers;
2546 typedef struct construct_base_type_t construct_base_type_t;
2547 struct construct_base_type_t {
2548 construct_type_t construct_type;
2552 static construct_type_t *parse_pointer_declarator(void)
2556 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2557 memset(pointer, 0, sizeof(pointer[0]));
2558 pointer->construct_type.kind = CONSTRUCT_POINTER;
2559 pointer->type_qualifiers = parse_type_qualifiers();
2561 return (construct_type_t*) pointer;
2564 static construct_type_t *parse_array_declarator(void)
2568 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2569 memset(array, 0, sizeof(array[0]));
2570 array->construct_type.kind = CONSTRUCT_ARRAY;
2572 if(token.type == T_static) {
2573 array->is_static = true;
2577 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2578 if(type_qualifiers != 0) {
2579 if(token.type == T_static) {
2580 array->is_static = true;
2584 array->type_qualifiers = type_qualifiers;
2586 if(token.type == '*' && look_ahead(1)->type == ']') {
2587 array->is_variable = true;
2589 } else if(token.type != ']') {
2590 array->size = parse_assignment_expression();
2595 return (construct_type_t*) array;
2600 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2605 if(declaration != NULL) {
2606 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2608 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2611 declaration_t *parameters = parse_parameters(&type->function);
2612 if(declaration != NULL) {
2613 declaration->scope.declarations = parameters;
2616 construct_function_type_t *construct_function_type =
2617 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2618 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2619 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2620 construct_function_type->function_type = type;
2624 return (construct_type_t*) construct_function_type;
2629 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2630 bool may_be_abstract)
2632 /* construct a single linked list of construct_type_t's which describe
2633 * how to construct the final declarator type */
2634 construct_type_t *first = NULL;
2635 construct_type_t *last = NULL;
2638 while(token.type == '*') {
2639 construct_type_t *type = parse_pointer_declarator();
2650 /* TODO: find out if this is correct */
2653 construct_type_t *inner_types = NULL;
2655 switch(token.type) {
2657 if(declaration == NULL) {
2658 errorf(HERE, "no identifier expected in typename");
2660 declaration->symbol = token.v.symbol;
2661 declaration->source_position = token.source_position;
2667 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2673 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2674 /* avoid a loop in the outermost scope, because eat_statement doesn't
2676 if(token.type == '}' && current_function == NULL) {
2684 construct_type_t *p = last;
2687 construct_type_t *type;
2688 switch(token.type) {
2690 type = parse_function_declarator(declaration);
2693 type = parse_array_declarator();
2696 goto declarator_finished;
2699 /* insert in the middle of the list (behind p) */
2701 type->next = p->next;
2712 declarator_finished:
2715 /* append inner_types at the end of the list, we don't to set last anymore
2716 * as it's not needed anymore */
2718 assert(first == NULL);
2719 first = inner_types;
2721 last->next = inner_types;
2729 static type_t *construct_declarator_type(construct_type_t *construct_list,
2732 construct_type_t *iter = construct_list;
2733 for( ; iter != NULL; iter = iter->next) {
2734 switch(iter->kind) {
2735 case CONSTRUCT_INVALID:
2736 panic("invalid type construction found");
2737 case CONSTRUCT_FUNCTION: {
2738 construct_function_type_t *construct_function_type
2739 = (construct_function_type_t*) iter;
2741 type_t *function_type = construct_function_type->function_type;
2743 function_type->function.return_type = type;
2745 type_t *skipped_return_type = skip_typeref(type);
2746 if (is_type_function(skipped_return_type)) {
2747 errorf(HERE, "function returning function is not allowed");
2748 type = type_error_type;
2749 } else if (is_type_array(skipped_return_type)) {
2750 errorf(HERE, "function returning array is not allowed");
2751 type = type_error_type;
2753 type = function_type;
2758 case CONSTRUCT_POINTER: {
2759 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2760 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2761 pointer_type->pointer.points_to = type;
2762 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2764 type = pointer_type;
2768 case CONSTRUCT_ARRAY: {
2769 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2770 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2772 expression_t *size_expression = parsed_array->size;
2773 if(size_expression != NULL) {
2775 = create_implicit_cast(size_expression, type_size_t);
2778 array_type->base.qualifiers = parsed_array->type_qualifiers;
2779 array_type->array.element_type = type;
2780 array_type->array.is_static = parsed_array->is_static;
2781 array_type->array.is_variable = parsed_array->is_variable;
2782 array_type->array.size_expression = size_expression;
2784 if(size_expression != NULL) {
2785 if(is_constant_expression(size_expression)) {
2786 array_type->array.size_constant = true;
2787 array_type->array.size
2788 = fold_constant(size_expression);
2790 array_type->array.is_vla = true;
2794 type_t *skipped_type = skip_typeref(type);
2795 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2796 errorf(HERE, "array of void is not allowed");
2797 type = type_error_type;
2805 type_t *hashed_type = typehash_insert(type);
2806 if(hashed_type != type) {
2807 /* the function type was constructed earlier freeing it here will
2808 * destroy other types... */
2809 if(iter->kind != CONSTRUCT_FUNCTION) {
2819 static declaration_t *parse_declarator(
2820 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2822 declaration_t *const declaration = allocate_declaration_zero();
2823 declaration->declared_storage_class = specifiers->declared_storage_class;
2824 declaration->modifiers = specifiers->decl_modifiers;
2825 declaration->is_inline = specifiers->is_inline;
2827 declaration->storage_class = specifiers->declared_storage_class;
2828 if(declaration->storage_class == STORAGE_CLASS_NONE
2829 && scope != global_scope) {
2830 declaration->storage_class = STORAGE_CLASS_AUTO;
2833 if(specifiers->alignment != 0) {
2834 /* TODO: add checks here */
2835 declaration->alignment = specifiers->alignment;
2838 construct_type_t *construct_type
2839 = parse_inner_declarator(declaration, may_be_abstract);
2840 type_t *const type = specifiers->type;
2841 declaration->type = construct_declarator_type(construct_type, type);
2843 if(construct_type != NULL) {
2844 obstack_free(&temp_obst, construct_type);
2850 static type_t *parse_abstract_declarator(type_t *base_type)
2852 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2854 type_t *result = construct_declarator_type(construct_type, base_type);
2855 if(construct_type != NULL) {
2856 obstack_free(&temp_obst, construct_type);
2862 static declaration_t *append_declaration(declaration_t* const declaration)
2864 if (last_declaration != NULL) {
2865 last_declaration->next = declaration;
2867 scope->declarations = declaration;
2869 last_declaration = declaration;
2874 * Check if the declaration of main is suspicious. main should be a
2875 * function with external linkage, returning int, taking either zero
2876 * arguments, two, or three arguments of appropriate types, ie.
2878 * int main([ int argc, char **argv [, char **env ] ]).
2880 * @param decl the declaration to check
2881 * @param type the function type of the declaration
2883 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2885 if (decl->storage_class == STORAGE_CLASS_STATIC) {
2886 warningf(decl->source_position, "'main' is normally a non-static function");
2888 if (skip_typeref(func_type->return_type) != type_int) {
2889 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2891 const function_parameter_t *parm = func_type->parameters;
2893 type_t *const first_type = parm->type;
2894 if (!types_compatible(skip_typeref(first_type), type_int)) {
2895 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2899 type_t *const second_type = parm->type;
2900 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2901 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2905 type_t *const third_type = parm->type;
2906 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2907 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2911 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2915 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2921 * Check if a symbol is the equal to "main".
2923 static bool is_sym_main(const symbol_t *const sym)
2925 return strcmp(sym->string, "main") == 0;
2928 static declaration_t *internal_record_declaration(
2929 declaration_t *const declaration,
2930 const bool is_function_definition)
2932 const symbol_t *const symbol = declaration->symbol;
2933 const namespace_t namespc = (namespace_t)declaration->namespc;
2935 type_t *const orig_type = declaration->type;
2936 type_t *const type = skip_typeref(orig_type);
2937 if (is_type_function(type) &&
2938 type->function.unspecified_parameters &&
2939 warning.strict_prototypes) {
2940 warningf(declaration->source_position,
2941 "function declaration '%#T' is not a prototype",
2942 orig_type, declaration->symbol);
2945 if (is_function_definition && warning.main && is_sym_main(symbol)) {
2946 check_type_of_main(declaration, &type->function);
2949 assert(declaration->symbol != NULL);
2950 declaration_t *previous_declaration = get_declaration(symbol, namespc);
2952 assert(declaration != previous_declaration);
2953 if (previous_declaration != NULL) {
2954 if (previous_declaration->parent_scope == scope) {
2955 /* can happen for K&R style declarations */
2956 if(previous_declaration->type == NULL) {
2957 previous_declaration->type = declaration->type;
2960 const type_t *prev_type = skip_typeref(previous_declaration->type);
2961 if (!types_compatible(type, prev_type)) {
2962 errorf(declaration->source_position,
2963 "declaration '%#T' is incompatible with "
2964 "previous declaration '%#T'",
2965 orig_type, symbol, previous_declaration->type, symbol);
2966 errorf(previous_declaration->source_position,
2967 "previous declaration of '%Y' was here", symbol);
2969 unsigned old_storage_class = previous_declaration->storage_class;
2970 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
2971 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
2972 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2973 return previous_declaration;
2976 unsigned new_storage_class = declaration->storage_class;
2978 if(is_type_incomplete(prev_type)) {
2979 previous_declaration->type = type;
2983 /* pretend no storage class means extern for function
2984 * declarations (except if the previous declaration is neither
2985 * none nor extern) */
2986 if (is_type_function(type)) {
2987 switch (old_storage_class) {
2988 case STORAGE_CLASS_NONE:
2989 old_storage_class = STORAGE_CLASS_EXTERN;
2991 case STORAGE_CLASS_EXTERN:
2992 if (is_function_definition) {
2993 if (warning.missing_prototypes &&
2994 prev_type->function.unspecified_parameters &&
2995 !is_sym_main(symbol)) {
2996 warningf(declaration->source_position,
2997 "no previous prototype for '%#T'",
3000 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3001 new_storage_class = STORAGE_CLASS_EXTERN;
3009 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3010 new_storage_class == STORAGE_CLASS_EXTERN) {
3011 warn_redundant_declaration:
3012 if (warning.redundant_decls) {
3013 warningf(declaration->source_position,
3014 "redundant declaration for '%Y'", symbol);
3015 warningf(previous_declaration->source_position,
3016 "previous declaration of '%Y' was here",
3019 } else if (current_function == NULL) {
3020 if (old_storage_class != STORAGE_CLASS_STATIC &&
3021 new_storage_class == STORAGE_CLASS_STATIC) {
3022 errorf(declaration->source_position,
3023 "static declaration of '%Y' follows non-static declaration",
3025 errorf(previous_declaration->source_position,
3026 "previous declaration of '%Y' was here", symbol);
3028 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3029 goto warn_redundant_declaration;
3031 if (new_storage_class == STORAGE_CLASS_NONE) {
3032 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3033 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3037 if (old_storage_class == new_storage_class) {
3038 errorf(declaration->source_position,
3039 "redeclaration of '%Y'", symbol);
3041 errorf(declaration->source_position,
3042 "redeclaration of '%Y' with different linkage",
3045 errorf(previous_declaration->source_position,
3046 "previous declaration of '%Y' was here", symbol);
3049 return previous_declaration;
3051 } else if (is_function_definition) {
3052 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3053 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3054 warningf(declaration->source_position,
3055 "no previous prototype for '%#T'", orig_type, symbol);
3056 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3057 warningf(declaration->source_position,
3058 "no previous declaration for '%#T'", orig_type,
3062 } else if (warning.missing_declarations &&
3063 scope == global_scope &&
3064 !is_type_function(type) && (
3065 declaration->storage_class == STORAGE_CLASS_NONE ||
3066 declaration->storage_class == STORAGE_CLASS_THREAD
3068 warningf(declaration->source_position,
3069 "no previous declaration for '%#T'", orig_type, symbol);
3072 assert(declaration->parent_scope == NULL);
3073 assert(scope != NULL);
3075 declaration->parent_scope = scope;
3077 environment_push(declaration);
3078 return append_declaration(declaration);
3081 static declaration_t *record_declaration(declaration_t *declaration)
3083 return internal_record_declaration(declaration, false);
3086 static declaration_t *record_function_definition(declaration_t *declaration)
3088 return internal_record_declaration(declaration, true);
3091 static void parser_error_multiple_definition(declaration_t *declaration,
3092 const source_position_t source_position)
3094 errorf(source_position, "multiple definition of symbol '%Y'",
3095 declaration->symbol);
3096 errorf(declaration->source_position,
3097 "this is the location of the previous definition.");
3100 static bool is_declaration_specifier(const token_t *token,
3101 bool only_type_specifiers)
3103 switch(token->type) {
3107 return is_typedef_symbol(token->v.symbol);
3109 case T___extension__:
3112 return !only_type_specifiers;
3119 static void parse_init_declarator_rest(declaration_t *declaration)
3123 type_t *orig_type = declaration->type;
3124 type_t *type = skip_typeref(orig_type);
3126 if(declaration->init.initializer != NULL) {
3127 parser_error_multiple_definition(declaration, token.source_position);
3130 bool must_be_constant = false;
3131 if(declaration->storage_class == STORAGE_CLASS_STATIC
3132 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3133 || declaration->parent_scope == global_scope) {
3134 must_be_constant = true;
3137 parse_initializer_env_t env;
3138 env.type = orig_type;
3139 env.must_be_constant = must_be_constant;
3140 env.declaration = declaration;
3142 initializer_t *initializer = parse_initializer(&env);
3144 if(env.type != orig_type) {
3145 orig_type = env.type;
3146 type = skip_typeref(orig_type);
3147 declaration->type = env.type;
3150 if(is_type_function(type)) {
3151 errorf(declaration->source_position,
3152 "initializers not allowed for function types at declator '%Y' (type '%T')",
3153 declaration->symbol, orig_type);
3155 declaration->init.initializer = initializer;
3159 /* parse rest of a declaration without any declarator */
3160 static void parse_anonymous_declaration_rest(
3161 const declaration_specifiers_t *specifiers,
3162 parsed_declaration_func finished_declaration)
3166 declaration_t *const declaration = allocate_declaration_zero();
3167 declaration->type = specifiers->type;
3168 declaration->declared_storage_class = specifiers->declared_storage_class;
3169 declaration->source_position = specifiers->source_position;
3170 declaration->modifiers = specifiers->decl_modifiers;
3172 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3173 warningf(declaration->source_position, "useless storage class in empty declaration");
3175 declaration->storage_class = STORAGE_CLASS_NONE;
3177 type_t *type = declaration->type;
3178 switch (type->kind) {
3179 case TYPE_COMPOUND_STRUCT:
3180 case TYPE_COMPOUND_UNION: {
3181 if (type->compound.declaration->symbol == NULL) {
3182 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3191 warningf(declaration->source_position, "empty declaration");
3195 finished_declaration(declaration);
3198 static void parse_declaration_rest(declaration_t *ndeclaration,
3199 const declaration_specifiers_t *specifiers,
3200 parsed_declaration_func finished_declaration)
3203 declaration_t *declaration = finished_declaration(ndeclaration);
3205 type_t *orig_type = declaration->type;
3206 type_t *type = skip_typeref(orig_type);
3208 if (type->kind != TYPE_FUNCTION &&
3209 declaration->is_inline &&
3210 is_type_valid(type)) {
3211 warningf(declaration->source_position,
3212 "variable '%Y' declared 'inline'\n", declaration->symbol);
3215 if(token.type == '=') {
3216 parse_init_declarator_rest(declaration);
3219 if(token.type != ',')
3223 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3231 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3233 symbol_t *symbol = declaration->symbol;
3234 if(symbol == NULL) {
3235 errorf(HERE, "anonymous declaration not valid as function parameter");
3238 namespace_t namespc = (namespace_t) declaration->namespc;
3239 if(namespc != NAMESPACE_NORMAL) {
3240 return record_declaration(declaration);
3243 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3244 if(previous_declaration == NULL ||
3245 previous_declaration->parent_scope != scope) {
3246 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3251 if(previous_declaration->type == NULL) {
3252 previous_declaration->type = declaration->type;
3253 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3254 previous_declaration->storage_class = declaration->storage_class;
3255 previous_declaration->parent_scope = scope;
3256 return previous_declaration;
3258 return record_declaration(declaration);
3262 static void parse_declaration(parsed_declaration_func finished_declaration)
3264 declaration_specifiers_t specifiers;
3265 memset(&specifiers, 0, sizeof(specifiers));
3266 parse_declaration_specifiers(&specifiers);
3268 if(token.type == ';') {
3269 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3271 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3272 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3276 static void parse_kr_declaration_list(declaration_t *declaration)
3278 type_t *type = skip_typeref(declaration->type);
3279 if(!is_type_function(type))
3282 if(!type->function.kr_style_parameters)
3285 /* push function parameters */
3286 int top = environment_top();
3287 scope_t *last_scope = scope;
3288 set_scope(&declaration->scope);
3290 declaration_t *parameter = declaration->scope.declarations;
3291 for( ; parameter != NULL; parameter = parameter->next) {
3292 assert(parameter->parent_scope == NULL);
3293 parameter->parent_scope = scope;
3294 environment_push(parameter);
3297 /* parse declaration list */
3298 while(is_declaration_specifier(&token, false)) {
3299 parse_declaration(finished_kr_declaration);
3302 /* pop function parameters */
3303 assert(scope == &declaration->scope);
3304 set_scope(last_scope);
3305 environment_pop_to(top);
3307 /* update function type */
3308 type_t *new_type = duplicate_type(type);
3309 new_type->function.kr_style_parameters = false;
3311 function_parameter_t *parameters = NULL;
3312 function_parameter_t *last_parameter = NULL;
3314 declaration_t *parameter_declaration = declaration->scope.declarations;
3315 for( ; parameter_declaration != NULL;
3316 parameter_declaration = parameter_declaration->next) {
3317 type_t *parameter_type = parameter_declaration->type;
3318 if(parameter_type == NULL) {
3320 errorf(HERE, "no type specified for function parameter '%Y'",
3321 parameter_declaration->symbol);
3323 if (warning.implicit_int) {
3324 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3325 parameter_declaration->symbol);
3327 parameter_type = type_int;
3328 parameter_declaration->type = parameter_type;
3332 semantic_parameter(parameter_declaration);
3333 parameter_type = parameter_declaration->type;
3335 function_parameter_t *function_parameter
3336 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3337 memset(function_parameter, 0, sizeof(function_parameter[0]));
3339 function_parameter->type = parameter_type;
3340 if(last_parameter != NULL) {
3341 last_parameter->next = function_parameter;
3343 parameters = function_parameter;
3345 last_parameter = function_parameter;
3347 new_type->function.parameters = parameters;
3349 type = typehash_insert(new_type);
3350 if(type != new_type) {
3351 obstack_free(type_obst, new_type);
3354 declaration->type = type;
3357 static bool first_err = true;
3360 * When called with first_err set, prints the name of the current function,
3363 static void print_in_function(void) {
3366 diagnosticf("%s: In function '%Y':\n",
3367 current_function->source_position.input_name,
3368 current_function->symbol);
3373 * Check if all labels are defined in the current function.
3374 * Check if all labels are used in the current function.
3376 static void check_labels(void)
3378 for (const goto_statement_t *goto_statement = goto_first;
3379 goto_statement != NULL;
3380 goto_statement = goto_statement->next) {
3381 declaration_t *label = goto_statement->label;
3384 if (label->source_position.input_name == NULL) {
3385 print_in_function();
3386 errorf(goto_statement->base.source_position,
3387 "label '%Y' used but not defined", label->symbol);
3390 goto_first = goto_last = NULL;
3392 if (warning.unused_label) {
3393 for (const label_statement_t *label_statement = label_first;
3394 label_statement != NULL;
3395 label_statement = label_statement->next) {
3396 const declaration_t *label = label_statement->label;
3398 if (! label->used) {
3399 print_in_function();
3400 warningf(label_statement->base.source_position,
3401 "label '%Y' defined but not used", label->symbol);
3405 label_first = label_last = NULL;
3409 * Check declarations of current_function for unused entities.
3411 static void check_declarations(void)
3413 if (warning.unused_parameter) {
3414 const scope_t *scope = ¤t_function->scope;
3416 const declaration_t *parameter = scope->declarations;
3417 for (; parameter != NULL; parameter = parameter->next) {
3418 if (! parameter->used) {
3419 print_in_function();
3420 warningf(parameter->source_position,
3421 "unused parameter '%Y'", parameter->symbol);
3425 if (warning.unused_variable) {
3429 static void parse_external_declaration(void)
3431 /* function-definitions and declarations both start with declaration
3433 declaration_specifiers_t specifiers;
3434 memset(&specifiers, 0, sizeof(specifiers));
3435 parse_declaration_specifiers(&specifiers);
3437 /* must be a declaration */
3438 if(token.type == ';') {
3439 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3443 /* declarator is common to both function-definitions and declarations */
3444 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3446 /* must be a declaration */
3447 if(token.type == ',' || token.type == '=' || token.type == ';') {
3448 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3452 /* must be a function definition */
3453 parse_kr_declaration_list(ndeclaration);
3455 if(token.type != '{') {
3456 parse_error_expected("while parsing function definition", '{', 0);
3461 type_t *type = ndeclaration->type;
3463 /* note that we don't skip typerefs: the standard doesn't allow them here
3464 * (so we can't use is_type_function here) */
3465 if(type->kind != TYPE_FUNCTION) {
3466 if (is_type_valid(type)) {
3467 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3468 type, ndeclaration->symbol);
3474 /* § 6.7.5.3 (14) a function definition with () means no
3475 * parameters (and not unspecified parameters) */
3476 if(type->function.unspecified_parameters) {
3477 type_t *duplicate = duplicate_type(type);
3478 duplicate->function.unspecified_parameters = false;
3480 type = typehash_insert(duplicate);
3481 if(type != duplicate) {
3482 obstack_free(type_obst, duplicate);
3484 ndeclaration->type = type;
3487 declaration_t *const declaration = record_function_definition(ndeclaration);
3488 if(ndeclaration != declaration) {
3489 declaration->scope = ndeclaration->scope;
3491 type = skip_typeref(declaration->type);
3493 /* push function parameters and switch scope */
3494 int top = environment_top();
3495 scope_t *last_scope = scope;
3496 set_scope(&declaration->scope);
3498 declaration_t *parameter = declaration->scope.declarations;
3499 for( ; parameter != NULL; parameter = parameter->next) {
3500 if(parameter->parent_scope == &ndeclaration->scope) {
3501 parameter->parent_scope = scope;
3503 assert(parameter->parent_scope == NULL
3504 || parameter->parent_scope == scope);
3505 parameter->parent_scope = scope;
3506 environment_push(parameter);
3509 if(declaration->init.statement != NULL) {
3510 parser_error_multiple_definition(declaration, token.source_position);
3512 goto end_of_parse_external_declaration;
3514 /* parse function body */
3515 int label_stack_top = label_top();
3516 declaration_t *old_current_function = current_function;
3517 current_function = declaration;
3519 declaration->init.statement = parse_compound_statement();
3522 check_declarations();
3524 assert(current_function == declaration);
3525 current_function = old_current_function;
3526 label_pop_to(label_stack_top);
3529 end_of_parse_external_declaration:
3530 assert(scope == &declaration->scope);
3531 set_scope(last_scope);
3532 environment_pop_to(top);
3535 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3536 source_position_t source_position)
3538 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3539 type->bitfield.base = base;
3540 type->bitfield.size = size;
3545 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3548 declaration_t *iter = compound_declaration->scope.declarations;
3549 for( ; iter != NULL; iter = iter->next) {
3550 if(iter->namespc != NAMESPACE_NORMAL)
3553 if(iter->symbol == NULL) {
3554 type_t *type = skip_typeref(iter->type);
3555 if(is_type_compound(type)) {
3556 declaration_t *result
3557 = find_compound_entry(type->compound.declaration, symbol);
3564 if(iter->symbol == symbol) {
3572 static void parse_compound_declarators(declaration_t *struct_declaration,
3573 const declaration_specifiers_t *specifiers)
3575 declaration_t *last_declaration = struct_declaration->scope.declarations;
3576 if(last_declaration != NULL) {
3577 while(last_declaration->next != NULL) {
3578 last_declaration = last_declaration->next;
3583 declaration_t *declaration;
3585 if(token.type == ':') {
3586 source_position_t source_position = HERE;
3589 type_t *base_type = specifiers->type;
3590 expression_t *size = parse_constant_expression();
3592 if(!is_type_integer(skip_typeref(base_type))) {
3593 errorf(HERE, "bitfield base type '%T' is not an integer type",
3597 type_t *type = make_bitfield_type(base_type, size, source_position);
3599 declaration = allocate_declaration_zero();
3600 declaration->namespc = NAMESPACE_NORMAL;
3601 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3602 declaration->storage_class = STORAGE_CLASS_NONE;
3603 declaration->source_position = source_position;
3604 declaration->modifiers = specifiers->decl_modifiers;
3605 declaration->type = type;
3607 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3609 type_t *orig_type = declaration->type;
3610 type_t *type = skip_typeref(orig_type);
3612 if(token.type == ':') {
3613 source_position_t source_position = HERE;
3615 expression_t *size = parse_constant_expression();
3617 if(!is_type_integer(type)) {
3618 errorf(HERE, "bitfield base type '%T' is not an "
3619 "integer type", orig_type);
3622 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3623 declaration->type = bitfield_type;
3625 /* TODO we ignore arrays for now... what is missing is a check
3626 * that they're at the end of the struct */
3627 if(is_type_incomplete(type) && !is_type_array(type)) {
3629 "compound member '%Y' has incomplete type '%T'",
3630 declaration->symbol, orig_type);
3631 } else if(is_type_function(type)) {
3632 errorf(HERE, "compound member '%Y' must not have function "
3633 "type '%T'", declaration->symbol, orig_type);
3638 /* make sure we don't define a symbol multiple times */
3639 symbol_t *symbol = declaration->symbol;
3640 if(symbol != NULL) {
3641 declaration_t *prev_decl
3642 = find_compound_entry(struct_declaration, symbol);
3644 if(prev_decl != NULL) {
3645 assert(prev_decl->symbol == symbol);
3646 errorf(declaration->source_position,
3647 "multiple declarations of symbol '%Y'", symbol);
3648 errorf(prev_decl->source_position,
3649 "previous declaration of '%Y' was here", symbol);
3653 /* append declaration */
3654 if(last_declaration != NULL) {
3655 last_declaration->next = declaration;
3657 struct_declaration->scope.declarations = declaration;
3659 last_declaration = declaration;
3661 if(token.type != ',')
3671 static void parse_compound_type_entries(declaration_t *compound_declaration)
3675 while(token.type != '}' && token.type != T_EOF) {
3676 declaration_specifiers_t specifiers;
3677 memset(&specifiers, 0, sizeof(specifiers));
3678 parse_declaration_specifiers(&specifiers);
3680 parse_compound_declarators(compound_declaration, &specifiers);
3682 if(token.type == T_EOF) {
3683 errorf(HERE, "EOF while parsing struct");
3688 static type_t *parse_typename(void)
3690 declaration_specifiers_t specifiers;
3691 memset(&specifiers, 0, sizeof(specifiers));
3692 parse_declaration_specifiers(&specifiers);
3693 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3694 /* TODO: improve error message, user does probably not know what a
3695 * storage class is...
3697 errorf(HERE, "typename may not have a storage class");
3700 type_t *result = parse_abstract_declarator(specifiers.type);
3708 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3709 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3710 expression_t *left);
3712 typedef struct expression_parser_function_t expression_parser_function_t;
3713 struct expression_parser_function_t {
3714 unsigned precedence;
3715 parse_expression_function parser;
3716 unsigned infix_precedence;
3717 parse_expression_infix_function infix_parser;
3720 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3723 * Creates a new invalid expression.
3725 static expression_t *create_invalid_expression(void)
3727 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3728 expression->base.source_position = token.source_position;
3733 * Prints an error message if an expression was expected but not read
3735 static expression_t *expected_expression_error(void)
3737 /* skip the error message if the error token was read */
3738 if (token.type != T_ERROR) {
3739 errorf(HERE, "expected expression, got token '%K'", &token);
3743 return create_invalid_expression();
3747 * Parse a string constant.
3749 static expression_t *parse_string_const(void)
3752 if (token.type == T_STRING_LITERAL) {
3753 string_t res = token.v.string;
3755 while (token.type == T_STRING_LITERAL) {
3756 res = concat_strings(&res, &token.v.string);
3759 if (token.type != T_WIDE_STRING_LITERAL) {
3760 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3761 /* note: that we use type_char_ptr here, which is already the
3762 * automatic converted type. revert_automatic_type_conversion
3763 * will construct the array type */
3764 cnst->base.type = type_char_ptr;
3765 cnst->string.value = res;
3769 wres = concat_string_wide_string(&res, &token.v.wide_string);
3771 wres = token.v.wide_string;
3776 switch (token.type) {
3777 case T_WIDE_STRING_LITERAL:
3778 wres = concat_wide_strings(&wres, &token.v.wide_string);
3781 case T_STRING_LITERAL:
3782 wres = concat_wide_string_string(&wres, &token.v.string);
3786 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3787 cnst->base.type = type_wchar_t_ptr;
3788 cnst->wide_string.value = wres;
3797 * Parse an integer constant.
3799 static expression_t *parse_int_const(void)
3801 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3802 cnst->base.source_position = HERE;
3803 cnst->base.type = token.datatype;
3804 cnst->conste.v.int_value = token.v.intvalue;
3812 * Parse a character constant.
3814 static expression_t *parse_character_constant(void)
3816 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3818 cnst->base.source_position = HERE;
3819 cnst->base.type = token.datatype;
3820 cnst->conste.v.character = token.v.string;
3822 if (cnst->conste.v.character.size != 1) {
3823 if (warning.multichar && (c_mode & _GNUC)) {
3825 warningf(HERE, "multi-character character constant");
3827 errorf(HERE, "more than 1 characters in character constant");
3836 * Parse a wide character constant.
3838 static expression_t *parse_wide_character_constant(void)
3840 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3842 cnst->base.source_position = HERE;
3843 cnst->base.type = token.datatype;
3844 cnst->conste.v.wide_character = token.v.wide_string;
3846 if (cnst->conste.v.wide_character.size != 1) {
3847 if (warning.multichar && (c_mode & _GNUC)) {
3849 warningf(HERE, "multi-character character constant");
3851 errorf(HERE, "more than 1 characters in character constant");
3860 * Parse a float constant.
3862 static expression_t *parse_float_const(void)
3864 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3865 cnst->base.type = token.datatype;
3866 cnst->conste.v.float_value = token.v.floatvalue;
3873 static declaration_t *create_implicit_function(symbol_t *symbol,
3874 const source_position_t source_position)
3876 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
3877 ntype->function.return_type = type_int;
3878 ntype->function.unspecified_parameters = true;
3880 type_t *type = typehash_insert(ntype);
3885 declaration_t *const declaration = allocate_declaration_zero();
3886 declaration->storage_class = STORAGE_CLASS_EXTERN;
3887 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3888 declaration->type = type;
3889 declaration->symbol = symbol;
3890 declaration->source_position = source_position;
3891 declaration->parent_scope = global_scope;
3893 scope_t *old_scope = scope;
3894 set_scope(global_scope);
3896 environment_push(declaration);
3897 /* prepends the declaration to the global declarations list */
3898 declaration->next = scope->declarations;
3899 scope->declarations = declaration;
3901 assert(scope == global_scope);
3902 set_scope(old_scope);
3908 * Creates a return_type (func)(argument_type) function type if not
3911 * @param return_type the return type
3912 * @param argument_type the argument type
3914 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3916 function_parameter_t *parameter
3917 = obstack_alloc(type_obst, sizeof(parameter[0]));
3918 memset(parameter, 0, sizeof(parameter[0]));
3919 parameter->type = argument_type;
3921 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3922 type->function.return_type = return_type;
3923 type->function.parameters = parameter;
3925 type_t *result = typehash_insert(type);
3926 if(result != type) {
3934 * Creates a function type for some function like builtins.
3936 * @param symbol the symbol describing the builtin
3938 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3940 switch(symbol->ID) {
3941 case T___builtin_alloca:
3942 return make_function_1_type(type_void_ptr, type_size_t);
3943 case T___builtin_nan:
3944 return make_function_1_type(type_double, type_char_ptr);
3945 case T___builtin_nanf:
3946 return make_function_1_type(type_float, type_char_ptr);
3947 case T___builtin_nand:
3948 return make_function_1_type(type_long_double, type_char_ptr);
3949 case T___builtin_va_end:
3950 return make_function_1_type(type_void, type_valist);
3952 panic("not implemented builtin symbol found");
3957 * Performs automatic type cast as described in § 6.3.2.1.
3959 * @param orig_type the original type
3961 static type_t *automatic_type_conversion(type_t *orig_type)
3963 type_t *type = skip_typeref(orig_type);
3964 if(is_type_array(type)) {
3965 array_type_t *array_type = &type->array;
3966 type_t *element_type = array_type->element_type;
3967 unsigned qualifiers = array_type->type.qualifiers;
3969 return make_pointer_type(element_type, qualifiers);
3972 if(is_type_function(type)) {
3973 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3980 * reverts the automatic casts of array to pointer types and function
3981 * to function-pointer types as defined § 6.3.2.1
3983 type_t *revert_automatic_type_conversion(const expression_t *expression)
3985 switch (expression->kind) {
3986 case EXPR_REFERENCE: return expression->reference.declaration->type;
3987 case EXPR_SELECT: return expression->select.compound_entry->type;
3989 case EXPR_UNARY_DEREFERENCE: {
3990 const expression_t *const value = expression->unary.value;
3991 type_t *const type = skip_typeref(value->base.type);
3992 assert(is_type_pointer(type));
3993 return type->pointer.points_to;
3996 case EXPR_BUILTIN_SYMBOL:
3997 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3999 case EXPR_ARRAY_ACCESS: {
4000 const expression_t *array_ref = expression->array_access.array_ref;
4001 type_t *type_left = skip_typeref(array_ref->base.type);
4002 if (!is_type_valid(type_left))
4004 assert(is_type_pointer(type_left));
4005 return type_left->pointer.points_to;
4008 case EXPR_STRING_LITERAL: {
4009 size_t size = expression->string.value.size;
4010 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4013 case EXPR_WIDE_STRING_LITERAL: {
4014 size_t size = expression->wide_string.value.size;
4015 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4018 case EXPR_COMPOUND_LITERAL:
4019 return expression->compound_literal.type;
4024 return expression->base.type;
4027 static expression_t *parse_reference(void)
4029 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4031 reference_expression_t *ref = &expression->reference;
4032 ref->symbol = token.v.symbol;
4034 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4036 source_position_t source_position = token.source_position;
4039 if(declaration == NULL) {
4040 if (! strict_mode && token.type == '(') {
4041 /* an implicitly defined function */
4042 if (warning.implicit_function_declaration) {
4043 warningf(HERE, "implicit declaration of function '%Y'",
4047 declaration = create_implicit_function(ref->symbol,
4050 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4051 return create_invalid_expression();
4055 type_t *type = declaration->type;
4057 /* we always do the auto-type conversions; the & and sizeof parser contains
4058 * code to revert this! */
4059 type = automatic_type_conversion(type);
4061 ref->declaration = declaration;
4062 ref->base.type = type;
4064 /* this declaration is used */
4065 declaration->used = true;
4070 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4074 /* TODO check if explicit cast is allowed and issue warnings/errors */
4077 static expression_t *parse_compound_literal(type_t *type)
4079 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4081 parse_initializer_env_t env;
4083 env.declaration = NULL;
4084 env.must_be_constant = false;
4085 initializer_t *initializer = parse_initializer(&env);
4088 expression->compound_literal.initializer = initializer;
4089 expression->compound_literal.type = type;
4090 expression->base.type = automatic_type_conversion(type);
4096 * Parse a cast expression.
4098 static expression_t *parse_cast(void)
4100 source_position_t source_position = token.source_position;
4102 type_t *type = parse_typename();
4106 if(token.type == '{') {
4107 return parse_compound_literal(type);
4110 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4111 cast->base.source_position = source_position;
4113 expression_t *value = parse_sub_expression(20);
4115 check_cast_allowed(value, type);
4117 cast->base.type = type;
4118 cast->unary.value = value;
4122 return create_invalid_expression();
4126 * Parse a statement expression.
4128 static expression_t *parse_statement_expression(void)
4130 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4132 statement_t *statement = parse_compound_statement();
4133 expression->statement.statement = statement;
4134 expression->base.source_position = statement->base.source_position;
4136 /* find last statement and use its type */
4137 type_t *type = type_void;
4138 const statement_t *stmt = statement->compound.statements;
4140 while (stmt->base.next != NULL)
4141 stmt = stmt->base.next;
4143 if (stmt->kind == STATEMENT_EXPRESSION) {
4144 type = stmt->expression.expression->base.type;
4147 warningf(expression->base.source_position, "empty statement expression ({})");
4149 expression->base.type = type;
4155 return create_invalid_expression();
4159 * Parse a braced expression.
4161 static expression_t *parse_brace_expression(void)
4165 switch(token.type) {
4167 /* gcc extension: a statement expression */
4168 return parse_statement_expression();
4172 return parse_cast();
4174 if(is_typedef_symbol(token.v.symbol)) {
4175 return parse_cast();
4179 expression_t *result = parse_expression();
4184 return create_invalid_expression();
4187 static expression_t *parse_function_keyword(void)
4192 if (current_function == NULL) {
4193 errorf(HERE, "'__func__' used outside of a function");
4196 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4197 expression->base.type = type_char_ptr;
4202 static expression_t *parse_pretty_function_keyword(void)
4204 eat(T___PRETTY_FUNCTION__);
4207 if (current_function == NULL) {
4208 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4211 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4212 expression->base.type = type_char_ptr;
4217 static designator_t *parse_designator(void)
4219 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4220 result->source_position = HERE;
4222 if(token.type != T_IDENTIFIER) {
4223 parse_error_expected("while parsing member designator",
4228 result->symbol = token.v.symbol;
4231 designator_t *last_designator = result;
4233 if(token.type == '.') {
4235 if(token.type != T_IDENTIFIER) {
4236 parse_error_expected("while parsing member designator",
4241 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4242 designator->source_position = HERE;
4243 designator->symbol = token.v.symbol;
4246 last_designator->next = designator;
4247 last_designator = designator;
4250 if(token.type == '[') {
4252 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4253 designator->source_position = HERE;
4254 designator->array_index = parse_expression();
4255 if(designator->array_index == NULL) {
4261 last_designator->next = designator;
4262 last_designator = designator;
4274 * Parse the __builtin_offsetof() expression.
4276 static expression_t *parse_offsetof(void)
4278 eat(T___builtin_offsetof);
4280 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4281 expression->base.type = type_size_t;
4284 type_t *type = parse_typename();
4286 designator_t *designator = parse_designator();
4289 expression->offsetofe.type = type;
4290 expression->offsetofe.designator = designator;
4293 memset(&path, 0, sizeof(path));
4294 path.top_type = type;
4295 path.path = NEW_ARR_F(type_path_entry_t, 0);
4297 descend_into_subtype(&path);
4299 if(!walk_designator(&path, designator, true)) {
4300 return create_invalid_expression();
4303 DEL_ARR_F(path.path);
4307 return create_invalid_expression();
4311 * Parses a _builtin_va_start() expression.
4313 static expression_t *parse_va_start(void)
4315 eat(T___builtin_va_start);
4317 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4320 expression->va_starte.ap = parse_assignment_expression();
4322 expression_t *const expr = parse_assignment_expression();
4323 if (expr->kind == EXPR_REFERENCE) {
4324 declaration_t *const decl = expr->reference.declaration;
4326 return create_invalid_expression();
4327 if (decl->parent_scope == ¤t_function->scope &&
4328 decl->next == NULL) {
4329 expression->va_starte.parameter = decl;
4334 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4336 return create_invalid_expression();
4340 * Parses a _builtin_va_arg() expression.
4342 static expression_t *parse_va_arg(void)
4344 eat(T___builtin_va_arg);
4346 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4349 expression->va_arge.ap = parse_assignment_expression();
4351 expression->base.type = parse_typename();
4356 return create_invalid_expression();
4359 static expression_t *parse_builtin_symbol(void)
4361 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4363 symbol_t *symbol = token.v.symbol;
4365 expression->builtin_symbol.symbol = symbol;
4368 type_t *type = get_builtin_symbol_type(symbol);
4369 type = automatic_type_conversion(type);
4371 expression->base.type = type;
4376 * Parses a __builtin_constant() expression.
4378 static expression_t *parse_builtin_constant(void)
4380 eat(T___builtin_constant_p);
4382 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4385 expression->builtin_constant.value = parse_assignment_expression();
4387 expression->base.type = type_int;
4391 return create_invalid_expression();
4395 * Parses a __builtin_prefetch() expression.
4397 static expression_t *parse_builtin_prefetch(void)
4399 eat(T___builtin_prefetch);
4401 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4404 expression->builtin_prefetch.adr = parse_assignment_expression();
4405 if (token.type == ',') {
4407 expression->builtin_prefetch.rw = parse_assignment_expression();
4409 if (token.type == ',') {
4411 expression->builtin_prefetch.locality = parse_assignment_expression();
4414 expression->base.type = type_void;
4418 return create_invalid_expression();
4422 * Parses a __builtin_is_*() compare expression.
4424 static expression_t *parse_compare_builtin(void)
4426 expression_t *expression;
4428 switch(token.type) {
4429 case T___builtin_isgreater:
4430 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4432 case T___builtin_isgreaterequal:
4433 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4435 case T___builtin_isless:
4436 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4438 case T___builtin_islessequal:
4439 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4441 case T___builtin_islessgreater:
4442 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4444 case T___builtin_isunordered:
4445 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4448 panic("invalid compare builtin found");
4451 expression->base.source_position = HERE;
4455 expression->binary.left = parse_assignment_expression();
4457 expression->binary.right = parse_assignment_expression();
4460 type_t *const orig_type_left = expression->binary.left->base.type;
4461 type_t *const orig_type_right = expression->binary.right->base.type;
4463 type_t *const type_left = skip_typeref(orig_type_left);
4464 type_t *const type_right = skip_typeref(orig_type_right);
4465 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4466 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4467 type_error_incompatible("invalid operands in comparison",
4468 expression->base.source_position, orig_type_left, orig_type_right);
4471 semantic_comparison(&expression->binary);
4476 return create_invalid_expression();
4480 * Parses a __builtin_expect() expression.
4482 static expression_t *parse_builtin_expect(void)
4484 eat(T___builtin_expect);
4486 expression_t *expression
4487 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4490 expression->binary.left = parse_assignment_expression();
4492 expression->binary.right = parse_constant_expression();
4495 expression->base.type = expression->binary.left->base.type;
4499 return create_invalid_expression();
4503 * Parses a MS assume() expression.
4505 static expression_t *parse_assume(void) {
4508 expression_t *expression
4509 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4512 expression->unary.value = parse_assignment_expression();
4515 expression->base.type = type_void;
4518 return create_invalid_expression();
4522 * Parses a primary expression.
4524 static expression_t *parse_primary_expression(void)
4526 switch (token.type) {
4527 case T_INTEGER: return parse_int_const();
4528 case T_CHARACTER_CONSTANT: return parse_character_constant();
4529 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4530 case T_FLOATINGPOINT: return parse_float_const();
4531 case T_STRING_LITERAL:
4532 case T_WIDE_STRING_LITERAL: return parse_string_const();
4533 case T_IDENTIFIER: return parse_reference();
4534 case T___FUNCTION__:
4535 case T___func__: return parse_function_keyword();
4536 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4537 case T___builtin_offsetof: return parse_offsetof();
4538 case T___builtin_va_start: return parse_va_start();
4539 case T___builtin_va_arg: return parse_va_arg();
4540 case T___builtin_expect: return parse_builtin_expect();
4541 case T___builtin_alloca:
4542 case T___builtin_nan:
4543 case T___builtin_nand:
4544 case T___builtin_nanf:
4545 case T___builtin_va_end: return parse_builtin_symbol();
4546 case T___builtin_isgreater:
4547 case T___builtin_isgreaterequal:
4548 case T___builtin_isless:
4549 case T___builtin_islessequal:
4550 case T___builtin_islessgreater:
4551 case T___builtin_isunordered: return parse_compare_builtin();
4552 case T___builtin_constant_p: return parse_builtin_constant();
4553 case T___builtin_prefetch: return parse_builtin_prefetch();
4554 case T_assume: return parse_assume();
4556 case '(': return parse_brace_expression();
4559 errorf(HERE, "unexpected token %K, expected an expression", &token);
4562 return create_invalid_expression();
4566 * Check if the expression has the character type and issue a warning then.
4568 static void check_for_char_index_type(const expression_t *expression) {
4569 type_t *const type = expression->base.type;
4570 const type_t *const base_type = skip_typeref(type);
4572 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4573 warning.char_subscripts) {
4574 warningf(expression->base.source_position,
4575 "array subscript has type '%T'", type);
4579 static expression_t *parse_array_expression(unsigned precedence,
4586 expression_t *inside = parse_expression();
4588 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4590 array_access_expression_t *array_access = &expression->array_access;
4592 type_t *const orig_type_left = left->base.type;
4593 type_t *const orig_type_inside = inside->base.type;
4595 type_t *const type_left = skip_typeref(orig_type_left);
4596 type_t *const type_inside = skip_typeref(orig_type_inside);
4598 type_t *return_type;
4599 if (is_type_pointer(type_left)) {
4600 return_type = type_left->pointer.points_to;
4601 array_access->array_ref = left;
4602 array_access->index = inside;
4603 check_for_char_index_type(inside);
4604 } else if (is_type_pointer(type_inside)) {
4605 return_type = type_inside->pointer.points_to;
4606 array_access->array_ref = inside;
4607 array_access->index = left;
4608 array_access->flipped = true;
4609 check_for_char_index_type(left);
4611 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4613 "array access on object with non-pointer types '%T', '%T'",
4614 orig_type_left, orig_type_inside);
4616 return_type = type_error_type;
4617 array_access->array_ref = create_invalid_expression();
4620 if(token.type != ']') {
4621 parse_error_expected("Problem while parsing array access", ']', 0);
4626 return_type = automatic_type_conversion(return_type);
4627 expression->base.type = return_type;
4632 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4634 expression_t *tp_expression = allocate_expression_zero(kind);
4635 tp_expression->base.type = type_size_t;
4637 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4639 tp_expression->typeprop.type = parse_typename();
4642 expression_t *expression = parse_sub_expression(precedence);
4643 expression->base.type = revert_automatic_type_conversion(expression);
4645 tp_expression->typeprop.type = expression->base.type;
4646 tp_expression->typeprop.tp_expression = expression;
4649 return tp_expression;
4651 return create_invalid_expression();
4654 static expression_t *parse_sizeof(unsigned precedence)
4657 return parse_typeprop(EXPR_SIZEOF, precedence);
4660 static expression_t *parse_alignof(unsigned precedence)
4663 return parse_typeprop(EXPR_SIZEOF, precedence);
4666 static expression_t *parse_select_expression(unsigned precedence,
4667 expression_t *compound)
4670 assert(token.type == '.' || token.type == T_MINUSGREATER);
4672 bool is_pointer = (token.type == T_MINUSGREATER);
4675 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4676 select->select.compound = compound;
4678 if(token.type != T_IDENTIFIER) {
4679 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4682 symbol_t *symbol = token.v.symbol;
4683 select->select.symbol = symbol;
4686 type_t *const orig_type = compound->base.type;
4687 type_t *const type = skip_typeref(orig_type);
4689 type_t *type_left = type;
4691 if (!is_type_pointer(type)) {
4692 if (is_type_valid(type)) {
4693 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4695 return create_invalid_expression();
4697 type_left = type->pointer.points_to;
4699 type_left = skip_typeref(type_left);
4701 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4702 type_left->kind != TYPE_COMPOUND_UNION) {
4703 if (is_type_valid(type_left)) {
4704 errorf(HERE, "request for member '%Y' in something not a struct or "
4705 "union, but '%T'", symbol, type_left);
4707 return create_invalid_expression();
4710 declaration_t *const declaration = type_left->compound.declaration;
4712 if(!declaration->init.is_defined) {
4713 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4715 return create_invalid_expression();
4718 declaration_t *iter = find_compound_entry(declaration, symbol);
4720 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4721 return create_invalid_expression();
4724 /* we always do the auto-type conversions; the & and sizeof parser contains
4725 * code to revert this! */
4726 type_t *expression_type = automatic_type_conversion(iter->type);
4728 select->select.compound_entry = iter;
4729 select->base.type = expression_type;
4731 if(expression_type->kind == TYPE_BITFIELD) {
4732 expression_t *extract
4733 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4734 extract->unary.value = select;
4735 extract->base.type = expression_type->bitfield.base;
4744 * Parse a call expression, ie. expression '( ... )'.
4746 * @param expression the function address
4748 static expression_t *parse_call_expression(unsigned precedence,
4749 expression_t *expression)
4752 expression_t *result = allocate_expression_zero(EXPR_CALL);
4754 call_expression_t *call = &result->call;
4755 call->function = expression;
4757 type_t *const orig_type = expression->base.type;
4758 type_t *const type = skip_typeref(orig_type);
4760 function_type_t *function_type = NULL;
4761 if (is_type_pointer(type)) {
4762 type_t *const to_type = skip_typeref(type->pointer.points_to);
4764 if (is_type_function(to_type)) {
4765 function_type = &to_type->function;
4766 call->base.type = function_type->return_type;
4770 if (function_type == NULL && is_type_valid(type)) {
4771 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4774 /* parse arguments */
4777 if(token.type != ')') {
4778 call_argument_t *last_argument = NULL;
4781 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4783 argument->expression = parse_assignment_expression();
4784 if(last_argument == NULL) {
4785 call->arguments = argument;
4787 last_argument->next = argument;
4789 last_argument = argument;
4791 if(token.type != ',')
4798 if(function_type != NULL) {
4799 function_parameter_t *parameter = function_type->parameters;
4800 call_argument_t *argument = call->arguments;
4801 for( ; parameter != NULL && argument != NULL;
4802 parameter = parameter->next, argument = argument->next) {
4803 type_t *expected_type = parameter->type;
4804 /* TODO report scope in error messages */
4805 expression_t *const arg_expr = argument->expression;
4806 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4807 if (res_type == NULL) {
4808 /* TODO improve error message */
4809 errorf(arg_expr->base.source_position,
4810 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4811 arg_expr, arg_expr->base.type, expected_type);
4813 argument->expression = create_implicit_cast(argument->expression, expected_type);
4816 /* too few parameters */
4817 if(parameter != NULL) {
4818 errorf(HERE, "too few arguments to function '%E'", expression);
4819 } else if(argument != NULL) {
4820 /* too many parameters */
4821 if(!function_type->variadic
4822 && !function_type->unspecified_parameters) {
4823 errorf(HERE, "too many arguments to function '%E'", expression);
4825 /* do default promotion */
4826 for( ; argument != NULL; argument = argument->next) {
4827 type_t *type = argument->expression->base.type;
4829 type = skip_typeref(type);
4830 if(is_type_integer(type)) {
4831 type = promote_integer(type);
4832 } else if(type == type_float) {
4836 argument->expression
4837 = create_implicit_cast(argument->expression, type);
4840 check_format(&result->call);
4843 check_format(&result->call);
4849 return create_invalid_expression();
4852 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4854 static bool same_compound_type(const type_t *type1, const type_t *type2)
4857 is_type_compound(type1) &&
4858 type1->kind == type2->kind &&
4859 type1->compound.declaration == type2->compound.declaration;
4863 * Parse a conditional expression, ie. 'expression ? ... : ...'.
4865 * @param expression the conditional expression
4867 static expression_t *parse_conditional_expression(unsigned precedence,
4868 expression_t *expression)
4872 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4874 conditional_expression_t *conditional = &result->conditional;
4875 conditional->condition = expression;
4878 type_t *const condition_type_orig = expression->base.type;
4879 type_t *const condition_type = skip_typeref(condition_type_orig);
4880 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4881 type_error("expected a scalar type in conditional condition",
4882 expression->base.source_position, condition_type_orig);
4885 expression_t *true_expression = parse_expression();
4887 expression_t *false_expression = parse_sub_expression(precedence);
4889 type_t *const orig_true_type = true_expression->base.type;
4890 type_t *const orig_false_type = false_expression->base.type;
4891 type_t *const true_type = skip_typeref(orig_true_type);
4892 type_t *const false_type = skip_typeref(orig_false_type);
4895 type_t *result_type;
4896 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4897 result_type = semantic_arithmetic(true_type, false_type);
4899 true_expression = create_implicit_cast(true_expression, result_type);
4900 false_expression = create_implicit_cast(false_expression, result_type);
4902 conditional->true_expression = true_expression;
4903 conditional->false_expression = false_expression;
4904 conditional->base.type = result_type;
4905 } else if (same_compound_type(true_type, false_type) || (
4906 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4907 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4909 /* just take 1 of the 2 types */
4910 result_type = true_type;
4911 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4912 && pointers_compatible(true_type, false_type)) {
4914 result_type = true_type;
4915 } else if (is_type_pointer(true_type)
4916 && is_null_pointer_constant(false_expression)) {
4917 result_type = true_type;
4918 } else if (is_type_pointer(false_type)
4919 && is_null_pointer_constant(true_expression)) {
4920 result_type = false_type;
4922 /* TODO: one pointer to void*, other some pointer */
4924 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4925 type_error_incompatible("while parsing conditional",
4926 expression->base.source_position, true_type,
4929 result_type = type_error_type;
4932 conditional->true_expression
4933 = create_implicit_cast(true_expression, result_type);
4934 conditional->false_expression
4935 = create_implicit_cast(false_expression, result_type);
4936 conditional->base.type = result_type;
4939 return create_invalid_expression();
4943 * Parse an extension expression.
4945 static expression_t *parse_extension(unsigned precedence)
4947 eat(T___extension__);
4949 /* TODO enable extensions */
4950 expression_t *expression = parse_sub_expression(precedence);
4951 /* TODO disable extensions */
4956 * Parse a __builtin_classify_type() expression.
4958 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4960 eat(T___builtin_classify_type);
4962 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4963 result->base.type = type_int;
4966 expression_t *expression = parse_sub_expression(precedence);
4968 result->classify_type.type_expression = expression;
4972 return create_invalid_expression();
4975 static void semantic_incdec(unary_expression_t *expression)
4977 type_t *const orig_type = expression->value->base.type;
4978 type_t *const type = skip_typeref(orig_type);
4979 /* TODO !is_type_real && !is_type_pointer */
4980 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4981 if (is_type_valid(type)) {
4982 /* TODO: improve error message */
4983 errorf(HERE, "operation needs an arithmetic or pointer type");
4988 expression->base.type = orig_type;
4991 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4993 type_t *const orig_type = expression->value->base.type;
4994 type_t *const type = skip_typeref(orig_type);
4995 if(!is_type_arithmetic(type)) {
4996 if (is_type_valid(type)) {
4997 /* TODO: improve error message */
4998 errorf(HERE, "operation needs an arithmetic type");
5003 expression->base.type = orig_type;
5006 static void semantic_unexpr_scalar(unary_expression_t *expression)
5008 type_t *const orig_type = expression->value->base.type;
5009 type_t *const type = skip_typeref(orig_type);
5010 if (!is_type_scalar(type)) {
5011 if (is_type_valid(type)) {
5012 errorf(HERE, "operand of ! must be of scalar type");
5017 expression->base.type = orig_type;
5020 static void semantic_unexpr_integer(unary_expression_t *expression)
5022 type_t *const orig_type = expression->value->base.type;
5023 type_t *const type = skip_typeref(orig_type);
5024 if (!is_type_integer(type)) {
5025 if (is_type_valid(type)) {
5026 errorf(HERE, "operand of ~ must be of integer type");
5031 expression->base.type = orig_type;
5034 static void semantic_dereference(unary_expression_t *expression)
5036 type_t *const orig_type = expression->value->base.type;
5037 type_t *const type = skip_typeref(orig_type);
5038 if(!is_type_pointer(type)) {
5039 if (is_type_valid(type)) {
5040 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5045 type_t *result_type = type->pointer.points_to;
5046 result_type = automatic_type_conversion(result_type);
5047 expression->base.type = result_type;
5051 * Check the semantic of the address taken expression.
5053 static void semantic_take_addr(unary_expression_t *expression)
5055 expression_t *value = expression->value;
5056 value->base.type = revert_automatic_type_conversion(value);
5058 type_t *orig_type = value->base.type;
5059 if(!is_type_valid(orig_type))
5062 if(value->kind == EXPR_REFERENCE) {
5063 declaration_t *const declaration = value->reference.declaration;
5064 if(declaration != NULL) {
5065 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5066 errorf(expression->base.source_position,
5067 "address of register variable '%Y' requested",
5068 declaration->symbol);
5070 declaration->address_taken = 1;
5074 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5077 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5078 static expression_t *parse_##unexpression_type(unsigned precedence) \
5082 expression_t *unary_expression \
5083 = allocate_expression_zero(unexpression_type); \
5084 unary_expression->base.source_position = HERE; \
5085 unary_expression->unary.value = parse_sub_expression(precedence); \
5087 sfunc(&unary_expression->unary); \
5089 return unary_expression; \
5092 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5093 semantic_unexpr_arithmetic)
5094 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5095 semantic_unexpr_arithmetic)
5096 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5097 semantic_unexpr_scalar)
5098 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5099 semantic_dereference)
5100 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5102 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5103 semantic_unexpr_integer)
5104 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5106 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5109 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5111 static expression_t *parse_##unexpression_type(unsigned precedence, \
5112 expression_t *left) \
5114 (void) precedence; \
5117 expression_t *unary_expression \
5118 = allocate_expression_zero(unexpression_type); \
5119 unary_expression->unary.value = left; \
5121 sfunc(&unary_expression->unary); \
5123 return unary_expression; \
5126 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5127 EXPR_UNARY_POSTFIX_INCREMENT,
5129 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5130 EXPR_UNARY_POSTFIX_DECREMENT,
5133 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5135 /* TODO: handle complex + imaginary types */
5137 /* § 6.3.1.8 Usual arithmetic conversions */
5138 if(type_left == type_long_double || type_right == type_long_double) {
5139 return type_long_double;
5140 } else if(type_left == type_double || type_right == type_double) {
5142 } else if(type_left == type_float || type_right == type_float) {
5146 type_right = promote_integer(type_right);
5147 type_left = promote_integer(type_left);
5149 if(type_left == type_right)
5152 bool signed_left = is_type_signed(type_left);
5153 bool signed_right = is_type_signed(type_right);
5154 int rank_left = get_rank(type_left);
5155 int rank_right = get_rank(type_right);
5156 if(rank_left < rank_right) {
5157 if(signed_left == signed_right || !signed_right) {
5163 if(signed_left == signed_right || !signed_left) {
5172 * Check the semantic restrictions for a binary expression.
5174 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5176 expression_t *const left = expression->left;
5177 expression_t *const right = expression->right;
5178 type_t *const orig_type_left = left->base.type;
5179 type_t *const orig_type_right = right->base.type;
5180 type_t *const type_left = skip_typeref(orig_type_left);
5181 type_t *const type_right = skip_typeref(orig_type_right);
5183 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5184 /* TODO: improve error message */
5185 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5186 errorf(HERE, "operation needs arithmetic types");
5191 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5192 expression->left = create_implicit_cast(left, arithmetic_type);
5193 expression->right = create_implicit_cast(right, arithmetic_type);
5194 expression->base.type = arithmetic_type;
5197 static void semantic_shift_op(binary_expression_t *expression)
5199 expression_t *const left = expression->left;
5200 expression_t *const right = expression->right;
5201 type_t *const orig_type_left = left->base.type;
5202 type_t *const orig_type_right = right->base.type;
5203 type_t * type_left = skip_typeref(orig_type_left);
5204 type_t * type_right = skip_typeref(orig_type_right);
5206 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5207 /* TODO: improve error message */
5208 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5209 errorf(HERE, "operation needs integer types");
5214 type_left = promote_integer(type_left);
5215 type_right = promote_integer(type_right);
5217 expression->left = create_implicit_cast(left, type_left);
5218 expression->right = create_implicit_cast(right, type_right);
5219 expression->base.type = type_left;
5222 static void semantic_add(binary_expression_t *expression)
5224 expression_t *const left = expression->left;
5225 expression_t *const right = expression->right;
5226 type_t *const orig_type_left = left->base.type;
5227 type_t *const orig_type_right = right->base.type;
5228 type_t *const type_left = skip_typeref(orig_type_left);
5229 type_t *const type_right = skip_typeref(orig_type_right);
5232 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5233 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5234 expression->left = create_implicit_cast(left, arithmetic_type);
5235 expression->right = create_implicit_cast(right, arithmetic_type);
5236 expression->base.type = arithmetic_type;
5238 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5239 expression->base.type = type_left;
5240 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5241 expression->base.type = type_right;
5242 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5243 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5247 static void semantic_sub(binary_expression_t *expression)
5249 expression_t *const left = expression->left;
5250 expression_t *const right = expression->right;
5251 type_t *const orig_type_left = left->base.type;
5252 type_t *const orig_type_right = right->base.type;
5253 type_t *const type_left = skip_typeref(orig_type_left);
5254 type_t *const type_right = skip_typeref(orig_type_right);
5257 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5258 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5259 expression->left = create_implicit_cast(left, arithmetic_type);
5260 expression->right = create_implicit_cast(right, arithmetic_type);
5261 expression->base.type = arithmetic_type;
5263 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5264 expression->base.type = type_left;
5265 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5266 if(!pointers_compatible(type_left, type_right)) {
5268 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5269 orig_type_left, orig_type_right);
5271 expression->base.type = type_ptrdiff_t;
5273 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5274 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5275 orig_type_left, orig_type_right);
5280 * Check the semantics of comparison expressions.
5282 * @param expression The expression to check.
5284 static void semantic_comparison(binary_expression_t *expression)
5286 expression_t *left = expression->left;
5287 expression_t *right = expression->right;
5288 type_t *orig_type_left = left->base.type;
5289 type_t *orig_type_right = right->base.type;
5291 type_t *type_left = skip_typeref(orig_type_left);
5292 type_t *type_right = skip_typeref(orig_type_right);
5294 /* TODO non-arithmetic types */
5295 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5296 if (warning.sign_compare &&
5297 (expression->base.kind != EXPR_BINARY_EQUAL &&
5298 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5299 (is_type_signed(type_left) != is_type_signed(type_right))) {
5300 warningf(expression->base.source_position,
5301 "comparison between signed and unsigned");
5303 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5304 expression->left = create_implicit_cast(left, arithmetic_type);
5305 expression->right = create_implicit_cast(right, arithmetic_type);
5306 expression->base.type = arithmetic_type;
5307 if (warning.float_equal &&
5308 (expression->base.kind == EXPR_BINARY_EQUAL ||
5309 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5310 is_type_float(arithmetic_type)) {
5311 warningf(expression->base.source_position,
5312 "comparing floating point with == or != is unsafe");
5314 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5315 /* TODO check compatibility */
5316 } else if (is_type_pointer(type_left)) {
5317 expression->right = create_implicit_cast(right, type_left);
5318 } else if (is_type_pointer(type_right)) {
5319 expression->left = create_implicit_cast(left, type_right);
5320 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5321 type_error_incompatible("invalid operands in comparison",
5322 expression->base.source_position,
5323 type_left, type_right);
5325 expression->base.type = type_int;
5328 static void semantic_arithmetic_assign(binary_expression_t *expression)
5330 expression_t *left = expression->left;
5331 expression_t *right = expression->right;
5332 type_t *orig_type_left = left->base.type;
5333 type_t *orig_type_right = right->base.type;
5335 type_t *type_left = skip_typeref(orig_type_left);
5336 type_t *type_right = skip_typeref(orig_type_right);
5338 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5339 /* TODO: improve error message */
5340 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5341 errorf(HERE, "operation needs arithmetic types");
5346 /* combined instructions are tricky. We can't create an implicit cast on
5347 * the left side, because we need the uncasted form for the store.
5348 * The ast2firm pass has to know that left_type must be right_type
5349 * for the arithmetic operation and create a cast by itself */
5350 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5351 expression->right = create_implicit_cast(right, arithmetic_type);
5352 expression->base.type = type_left;
5355 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5357 expression_t *const left = expression->left;
5358 expression_t *const right = expression->right;
5359 type_t *const orig_type_left = left->base.type;
5360 type_t *const orig_type_right = right->base.type;
5361 type_t *const type_left = skip_typeref(orig_type_left);
5362 type_t *const type_right = skip_typeref(orig_type_right);
5364 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5365 /* combined instructions are tricky. We can't create an implicit cast on
5366 * the left side, because we need the uncasted form for the store.
5367 * The ast2firm pass has to know that left_type must be right_type
5368 * for the arithmetic operation and create a cast by itself */
5369 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5370 expression->right = create_implicit_cast(right, arithmetic_type);
5371 expression->base.type = type_left;
5372 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5373 expression->base.type = type_left;
5374 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5375 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5380 * Check the semantic restrictions of a logical expression.
5382 static void semantic_logical_op(binary_expression_t *expression)
5384 expression_t *const left = expression->left;
5385 expression_t *const right = expression->right;
5386 type_t *const orig_type_left = left->base.type;
5387 type_t *const orig_type_right = right->base.type;
5388 type_t *const type_left = skip_typeref(orig_type_left);
5389 type_t *const type_right = skip_typeref(orig_type_right);
5391 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5392 /* TODO: improve error message */
5393 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5394 errorf(HERE, "operation needs scalar types");
5399 expression->base.type = type_int;
5403 * Checks if a compound type has constant fields.
5405 static bool has_const_fields(const compound_type_t *type)
5407 const scope_t *scope = &type->declaration->scope;
5408 const declaration_t *declaration = scope->declarations;
5410 for (; declaration != NULL; declaration = declaration->next) {
5411 if (declaration->namespc != NAMESPACE_NORMAL)
5414 const type_t *decl_type = skip_typeref(declaration->type);
5415 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5423 * Check the semantic restrictions of a binary assign expression.
5425 static void semantic_binexpr_assign(binary_expression_t *expression)
5427 expression_t *left = expression->left;
5428 type_t *orig_type_left = left->base.type;
5430 type_t *type_left = revert_automatic_type_conversion(left);
5431 type_left = skip_typeref(orig_type_left);
5433 /* must be a modifiable lvalue */
5434 if (is_type_array(type_left)) {
5435 errorf(HERE, "cannot assign to arrays ('%E')", left);
5438 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5439 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5443 if(is_type_incomplete(type_left)) {
5445 "left-hand side of assignment '%E' has incomplete type '%T'",
5446 left, orig_type_left);
5449 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5450 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5451 left, orig_type_left);
5455 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5457 if (res_type == NULL) {
5458 errorf(expression->base.source_position,
5459 "cannot assign to '%T' from '%T'",
5460 orig_type_left, expression->right->base.type);
5462 expression->right = create_implicit_cast(expression->right, res_type);
5465 expression->base.type = orig_type_left;
5469 * Determine if the outermost operation (or parts thereof) of the given
5470 * expression has no effect in order to generate a warning about this fact.
5471 * Therefore in some cases this only examines some of the operands of the
5472 * expression (see comments in the function and examples below).
5474 * f() + 23; // warning, because + has no effect
5475 * x || f(); // no warning, because x controls execution of f()
5476 * x ? y : f(); // warning, because y has no effect
5477 * (void)x; // no warning to be able to suppress the warning
5478 * This function can NOT be used for an "expression has definitely no effect"-
5480 static bool expression_has_effect(const expression_t *const expr)
5482 switch (expr->kind) {
5483 case EXPR_UNKNOWN: break;
5484 case EXPR_INVALID: return true; /* do NOT warn */
5485 case EXPR_REFERENCE: return false;
5486 case EXPR_CONST: return false;
5487 case EXPR_CHARACTER_CONSTANT: return false;
5488 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5489 case EXPR_STRING_LITERAL: return false;
5490 case EXPR_WIDE_STRING_LITERAL: return false;
5493 const call_expression_t *const call = &expr->call;
5494 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5497 switch (call->function->builtin_symbol.symbol->ID) {
5498 case T___builtin_va_end: return true;
5499 default: return false;
5503 /* Generate the warning if either the left or right hand side of a
5504 * conditional expression has no effect */
5505 case EXPR_CONDITIONAL: {
5506 const conditional_expression_t *const cond = &expr->conditional;
5508 expression_has_effect(cond->true_expression) &&
5509 expression_has_effect(cond->false_expression);
5512 case EXPR_SELECT: return false;
5513 case EXPR_ARRAY_ACCESS: return false;
5514 case EXPR_SIZEOF: return false;
5515 case EXPR_CLASSIFY_TYPE: return false;
5516 case EXPR_ALIGNOF: return false;
5518 case EXPR_FUNCTION: return false;
5519 case EXPR_PRETTY_FUNCTION: return false;
5520 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5521 case EXPR_BUILTIN_CONSTANT_P: return false;
5522 case EXPR_BUILTIN_PREFETCH: return true;
5523 case EXPR_OFFSETOF: return false;
5524 case EXPR_VA_START: return true;
5525 case EXPR_VA_ARG: return true;
5526 case EXPR_STATEMENT: return true; // TODO
5527 case EXPR_COMPOUND_LITERAL: return false;
5529 case EXPR_UNARY_NEGATE: return false;
5530 case EXPR_UNARY_PLUS: return false;
5531 case EXPR_UNARY_BITWISE_NEGATE: return false;
5532 case EXPR_UNARY_NOT: return false;
5533 case EXPR_UNARY_DEREFERENCE: return false;
5534 case EXPR_UNARY_TAKE_ADDRESS: return false;
5535 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5536 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5537 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5538 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5540 /* Treat void casts as if they have an effect in order to being able to
5541 * suppress the warning */
5542 case EXPR_UNARY_CAST: {
5543 type_t *const type = skip_typeref(expr->base.type);
5544 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5547 case EXPR_UNARY_CAST_IMPLICIT: return true;
5548 case EXPR_UNARY_ASSUME: return true;
5549 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5551 case EXPR_BINARY_ADD: return false;
5552 case EXPR_BINARY_SUB: return false;
5553 case EXPR_BINARY_MUL: return false;
5554 case EXPR_BINARY_DIV: return false;
5555 case EXPR_BINARY_MOD: return false;
5556 case EXPR_BINARY_EQUAL: return false;
5557 case EXPR_BINARY_NOTEQUAL: return false;
5558 case EXPR_BINARY_LESS: return false;
5559 case EXPR_BINARY_LESSEQUAL: return false;
5560 case EXPR_BINARY_GREATER: return false;
5561 case EXPR_BINARY_GREATEREQUAL: return false;
5562 case EXPR_BINARY_BITWISE_AND: return false;
5563 case EXPR_BINARY_BITWISE_OR: return false;
5564 case EXPR_BINARY_BITWISE_XOR: return false;
5565 case EXPR_BINARY_SHIFTLEFT: return false;
5566 case EXPR_BINARY_SHIFTRIGHT: return false;
5567 case EXPR_BINARY_ASSIGN: return true;
5568 case EXPR_BINARY_MUL_ASSIGN: return true;
5569 case EXPR_BINARY_DIV_ASSIGN: return true;
5570 case EXPR_BINARY_MOD_ASSIGN: return true;
5571 case EXPR_BINARY_ADD_ASSIGN: return true;
5572 case EXPR_BINARY_SUB_ASSIGN: return true;
5573 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5574 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5575 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5576 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5577 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5579 /* Only examine the right hand side of && and ||, because the left hand
5580 * side already has the effect of controlling the execution of the right
5582 case EXPR_BINARY_LOGICAL_AND:
5583 case EXPR_BINARY_LOGICAL_OR:
5584 /* Only examine the right hand side of a comma expression, because the left
5585 * hand side has a separate warning */
5586 case EXPR_BINARY_COMMA:
5587 return expression_has_effect(expr->binary.right);
5589 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5590 case EXPR_BINARY_ISGREATER: return false;
5591 case EXPR_BINARY_ISGREATEREQUAL: return false;
5592 case EXPR_BINARY_ISLESS: return false;
5593 case EXPR_BINARY_ISLESSEQUAL: return false;
5594 case EXPR_BINARY_ISLESSGREATER: return false;
5595 case EXPR_BINARY_ISUNORDERED: return false;
5598 panic("unexpected expression");
5601 static void semantic_comma(binary_expression_t *expression)
5603 if (warning.unused_value) {
5604 const expression_t *const left = expression->left;
5605 if (!expression_has_effect(left)) {
5606 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5609 expression->base.type = expression->right->base.type;
5612 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5613 static expression_t *parse_##binexpression_type(unsigned precedence, \
5614 expression_t *left) \
5617 source_position_t pos = HERE; \
5619 expression_t *right = parse_sub_expression(precedence + lr); \
5621 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5622 binexpr->base.source_position = pos; \
5623 binexpr->binary.left = left; \
5624 binexpr->binary.right = right; \
5625 sfunc(&binexpr->binary); \
5630 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5631 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5632 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5633 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5634 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5635 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5636 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5637 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5638 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5640 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5641 semantic_comparison, 1)
5642 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5643 semantic_comparison, 1)
5644 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5645 semantic_comparison, 1)
5646 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5647 semantic_comparison, 1)
5649 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5650 semantic_binexpr_arithmetic, 1)
5651 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5652 semantic_binexpr_arithmetic, 1)
5653 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5654 semantic_binexpr_arithmetic, 1)
5655 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5656 semantic_logical_op, 1)
5657 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5658 semantic_logical_op, 1)
5659 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5660 semantic_shift_op, 1)
5661 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5662 semantic_shift_op, 1)
5663 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5664 semantic_arithmetic_addsubb_assign, 0)
5665 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5666 semantic_arithmetic_addsubb_assign, 0)
5667 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5668 semantic_arithmetic_assign, 0)
5669 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5670 semantic_arithmetic_assign, 0)
5671 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5672 semantic_arithmetic_assign, 0)
5673 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5674 semantic_arithmetic_assign, 0)
5675 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5676 semantic_arithmetic_assign, 0)
5677 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5678 semantic_arithmetic_assign, 0)
5679 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5680 semantic_arithmetic_assign, 0)
5681 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5682 semantic_arithmetic_assign, 0)
5684 static expression_t *parse_sub_expression(unsigned precedence)
5686 if(token.type < 0) {
5687 return expected_expression_error();
5690 expression_parser_function_t *parser
5691 = &expression_parsers[token.type];
5692 source_position_t source_position = token.source_position;
5695 if(parser->parser != NULL) {
5696 left = parser->parser(parser->precedence);
5698 left = parse_primary_expression();
5700 assert(left != NULL);
5701 left->base.source_position = source_position;
5704 if(token.type < 0) {
5705 return expected_expression_error();
5708 parser = &expression_parsers[token.type];
5709 if(parser->infix_parser == NULL)
5711 if(parser->infix_precedence < precedence)
5714 left = parser->infix_parser(parser->infix_precedence, left);
5716 assert(left != NULL);
5717 assert(left->kind != EXPR_UNKNOWN);
5718 left->base.source_position = source_position;
5725 * Parse an expression.
5727 static expression_t *parse_expression(void)
5729 return parse_sub_expression(1);
5733 * Register a parser for a prefix-like operator with given precedence.
5735 * @param parser the parser function
5736 * @param token_type the token type of the prefix token
5737 * @param precedence the precedence of the operator
5739 static void register_expression_parser(parse_expression_function parser,
5740 int token_type, unsigned precedence)
5742 expression_parser_function_t *entry = &expression_parsers[token_type];
5744 if(entry->parser != NULL) {
5745 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5746 panic("trying to register multiple expression parsers for a token");
5748 entry->parser = parser;
5749 entry->precedence = precedence;
5753 * Register a parser for an infix operator with given precedence.
5755 * @param parser the parser function
5756 * @param token_type the token type of the infix operator
5757 * @param precedence the precedence of the operator
5759 static void register_infix_parser(parse_expression_infix_function parser,
5760 int token_type, unsigned precedence)
5762 expression_parser_function_t *entry = &expression_parsers[token_type];
5764 if(entry->infix_parser != NULL) {
5765 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5766 panic("trying to register multiple infix expression parsers for a "
5769 entry->infix_parser = parser;
5770 entry->infix_precedence = precedence;
5774 * Initialize the expression parsers.
5776 static void init_expression_parsers(void)
5778 memset(&expression_parsers, 0, sizeof(expression_parsers));
5780 register_infix_parser(parse_array_expression, '[', 30);
5781 register_infix_parser(parse_call_expression, '(', 30);
5782 register_infix_parser(parse_select_expression, '.', 30);
5783 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5784 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5786 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5789 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5790 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5791 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5792 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5793 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5794 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5795 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5796 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5797 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5798 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5799 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5800 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5801 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5802 T_EXCLAMATIONMARKEQUAL, 13);
5803 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5804 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5805 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5806 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5807 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5808 register_infix_parser(parse_conditional_expression, '?', 7);
5809 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5810 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5811 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5812 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5813 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5814 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5815 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5816 T_LESSLESSEQUAL, 2);
5817 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5818 T_GREATERGREATEREQUAL, 2);
5819 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5821 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5823 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5826 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5828 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
5829 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
5830 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
5831 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
5832 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
5833 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
5834 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5836 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5838 register_expression_parser(parse_sizeof, T_sizeof, 25);
5839 register_expression_parser(parse_alignof, T___alignof__, 25);
5840 register_expression_parser(parse_extension, T___extension__, 25);
5841 register_expression_parser(parse_builtin_classify_type,
5842 T___builtin_classify_type, 25);
5846 * Parse a asm statement constraints specification.
5848 static asm_constraint_t *parse_asm_constraints(void)
5850 asm_constraint_t *result = NULL;
5851 asm_constraint_t *last = NULL;
5853 while(token.type == T_STRING_LITERAL || token.type == '[') {
5854 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5855 memset(constraint, 0, sizeof(constraint[0]));
5857 if(token.type == '[') {
5859 if(token.type != T_IDENTIFIER) {
5860 parse_error_expected("while parsing asm constraint",
5864 constraint->symbol = token.v.symbol;
5869 constraint->constraints = parse_string_literals();
5871 constraint->expression = parse_expression();
5875 last->next = constraint;
5877 result = constraint;
5881 if(token.type != ',')
5892 * Parse a asm statement clobber specification.
5894 static asm_clobber_t *parse_asm_clobbers(void)
5896 asm_clobber_t *result = NULL;
5897 asm_clobber_t *last = NULL;
5899 while(token.type == T_STRING_LITERAL) {
5900 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5901 clobber->clobber = parse_string_literals();
5904 last->next = clobber;
5910 if(token.type != ',')
5919 * Parse an asm statement.
5921 static statement_t *parse_asm_statement(void)
5925 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
5926 statement->base.source_position = token.source_position;
5928 asm_statement_t *asm_statement = &statement->asms;
5930 if(token.type == T_volatile) {
5932 asm_statement->is_volatile = true;
5936 asm_statement->asm_text = parse_string_literals();
5938 if(token.type != ':')
5942 asm_statement->inputs = parse_asm_constraints();
5943 if(token.type != ':')
5947 asm_statement->outputs = parse_asm_constraints();
5948 if(token.type != ':')
5952 asm_statement->clobbers = parse_asm_clobbers();
5963 * Parse a case statement.
5965 static statement_t *parse_case_statement(void)
5969 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5971 statement->base.source_position = token.source_position;
5972 statement->case_label.expression = parse_expression();
5974 if (c_mode & _GNUC) {
5975 if (token.type == T_DOTDOTDOT) {
5977 statement->case_label.end_range = parse_expression();
5983 if (! is_constant_expression(statement->case_label.expression)) {
5984 errorf(statement->base.source_position,
5985 "case label does not reduce to an integer constant");
5987 /* TODO: check if the case label is already known */
5988 if (current_switch != NULL) {
5989 /* link all cases into the switch statement */
5990 if (current_switch->last_case == NULL) {
5991 current_switch->first_case =
5992 current_switch->last_case = &statement->case_label;
5994 current_switch->last_case->next = &statement->case_label;
5997 errorf(statement->base.source_position,
5998 "case label not within a switch statement");
6001 statement->case_label.statement = parse_statement();
6009 * Finds an existing default label of a switch statement.
6011 static case_label_statement_t *
6012 find_default_label(const switch_statement_t *statement)
6014 case_label_statement_t *label = statement->first_case;
6015 for ( ; label != NULL; label = label->next) {
6016 if (label->expression == NULL)
6023 * Parse a default statement.
6025 static statement_t *parse_default_statement(void)
6029 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6031 statement->base.source_position = token.source_position;
6034 if (current_switch != NULL) {
6035 const case_label_statement_t *def_label = find_default_label(current_switch);
6036 if (def_label != NULL) {
6037 errorf(HERE, "multiple default labels in one switch");
6038 errorf(def_label->base.source_position,
6039 "this is the first default label");
6041 /* link all cases into the switch statement */
6042 if (current_switch->last_case == NULL) {
6043 current_switch->first_case =
6044 current_switch->last_case = &statement->case_label;
6046 current_switch->last_case->next = &statement->case_label;
6050 errorf(statement->base.source_position,
6051 "'default' label not within a switch statement");
6053 statement->case_label.statement = parse_statement();
6061 * Return the declaration for a given label symbol or create a new one.
6063 static declaration_t *get_label(symbol_t *symbol)
6065 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6066 assert(current_function != NULL);
6067 /* if we found a label in the same function, then we already created the
6069 if(candidate != NULL
6070 && candidate->parent_scope == ¤t_function->scope) {
6074 /* otherwise we need to create a new one */
6075 declaration_t *const declaration = allocate_declaration_zero();
6076 declaration->namespc = NAMESPACE_LABEL;
6077 declaration->symbol = symbol;
6079 label_push(declaration);
6085 * Parse a label statement.
6087 static statement_t *parse_label_statement(void)
6089 assert(token.type == T_IDENTIFIER);
6090 symbol_t *symbol = token.v.symbol;
6093 declaration_t *label = get_label(symbol);
6095 /* if source position is already set then the label is defined twice,
6096 * otherwise it was just mentioned in a goto so far */
6097 if(label->source_position.input_name != NULL) {
6098 errorf(HERE, "duplicate label '%Y'", symbol);
6099 errorf(label->source_position, "previous definition of '%Y' was here",
6102 label->source_position = token.source_position;
6105 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6107 statement->base.source_position = token.source_position;
6108 statement->label.label = label;
6112 if(token.type == '}') {
6113 /* TODO only warn? */
6114 errorf(HERE, "label at end of compound statement");
6117 if (token.type == ';') {
6118 /* eat an empty statement here, to avoid the warning about an empty
6119 * after a label. label:; is commonly used to have a label before
6123 statement->label.statement = parse_statement();
6127 /* remember the labels's in a list for later checking */
6128 if (label_last == NULL) {
6129 label_first = &statement->label;
6131 label_last->next = &statement->label;
6133 label_last = &statement->label;
6139 * Parse an if statement.
6141 static statement_t *parse_if(void)
6145 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6146 statement->base.source_position = token.source_position;
6149 statement->ifs.condition = parse_expression();
6152 statement->ifs.true_statement = parse_statement();
6153 if(token.type == T_else) {
6155 statement->ifs.false_statement = parse_statement();
6164 * Parse a switch statement.
6166 static statement_t *parse_switch(void)
6170 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6171 statement->base.source_position = token.source_position;
6174 expression_t *const expr = parse_expression();
6175 type_t * type = skip_typeref(expr->base.type);
6176 if (is_type_integer(type)) {
6177 type = promote_integer(type);
6178 } else if (is_type_valid(type)) {
6179 errorf(expr->base.source_position,
6180 "switch quantity is not an integer, but '%T'", type);
6181 type = type_error_type;
6183 statement->switchs.expression = create_implicit_cast(expr, type);
6186 switch_statement_t *rem = current_switch;
6187 current_switch = &statement->switchs;
6188 statement->switchs.body = parse_statement();
6189 current_switch = rem;
6191 if (warning.switch_default
6192 && find_default_label(&statement->switchs) == NULL) {
6193 warningf(statement->base.source_position, "switch has no default case");
6201 static statement_t *parse_loop_body(statement_t *const loop)
6203 statement_t *const rem = current_loop;
6204 current_loop = loop;
6206 statement_t *const body = parse_statement();
6213 * Parse a while statement.
6215 static statement_t *parse_while(void)
6219 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6220 statement->base.source_position = token.source_position;
6223 statement->whiles.condition = parse_expression();
6226 statement->whiles.body = parse_loop_body(statement);
6234 * Parse a do statement.
6236 static statement_t *parse_do(void)
6240 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6242 statement->base.source_position = token.source_position;
6244 statement->do_while.body = parse_loop_body(statement);
6248 statement->do_while.condition = parse_expression();
6258 * Parse a for statement.
6260 static statement_t *parse_for(void)
6264 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6265 statement->base.source_position = token.source_position;
6267 int top = environment_top();
6268 scope_t *last_scope = scope;
6269 set_scope(&statement->fors.scope);
6273 if(token.type != ';') {
6274 if(is_declaration_specifier(&token, false)) {
6275 parse_declaration(record_declaration);
6277 expression_t *const init = parse_expression();
6278 statement->fors.initialisation = init;
6279 if (warning.unused_value && !expression_has_effect(init)) {
6280 warningf(init->base.source_position,
6281 "initialisation of 'for'-statement has no effect");
6289 if(token.type != ';') {
6290 statement->fors.condition = parse_expression();
6293 if(token.type != ')') {
6294 expression_t *const step = parse_expression();
6295 statement->fors.step = step;
6296 if (warning.unused_value && !expression_has_effect(step)) {
6297 warningf(step->base.source_position,
6298 "step of 'for'-statement has no effect");
6302 statement->fors.body = parse_loop_body(statement);
6304 assert(scope == &statement->fors.scope);
6305 set_scope(last_scope);
6306 environment_pop_to(top);
6311 assert(scope == &statement->fors.scope);
6312 set_scope(last_scope);
6313 environment_pop_to(top);
6319 * Parse a goto statement.
6321 static statement_t *parse_goto(void)
6325 if(token.type != T_IDENTIFIER) {
6326 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6330 symbol_t *symbol = token.v.symbol;
6333 declaration_t *label = get_label(symbol);
6335 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6336 statement->base.source_position = token.source_position;
6338 statement->gotos.label = label;
6340 /* remember the goto's in a list for later checking */
6341 if (goto_last == NULL) {
6342 goto_first = &statement->gotos;
6344 goto_last->next = &statement->gotos;
6346 goto_last = &statement->gotos;
6356 * Parse a continue statement.
6358 static statement_t *parse_continue(void)
6360 statement_t *statement;
6361 if (current_loop == NULL) {
6362 errorf(HERE, "continue statement not within loop");
6365 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6367 statement->base.source_position = token.source_position;
6379 * Parse a break statement.
6381 static statement_t *parse_break(void)
6383 statement_t *statement;
6384 if (current_switch == NULL && current_loop == NULL) {
6385 errorf(HERE, "break statement not within loop or switch");
6388 statement = allocate_statement_zero(STATEMENT_BREAK);
6390 statement->base.source_position = token.source_position;
6402 * Check if a given declaration represents a local variable.
6404 static bool is_local_var_declaration(const declaration_t *declaration) {
6405 switch ((storage_class_tag_t) declaration->storage_class) {
6406 case STORAGE_CLASS_AUTO:
6407 case STORAGE_CLASS_REGISTER: {
6408 const type_t *type = skip_typeref(declaration->type);
6409 if(is_type_function(type)) {
6421 * Check if a given declaration represents a variable.
6423 static bool is_var_declaration(const declaration_t *declaration) {
6424 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6427 const type_t *type = skip_typeref(declaration->type);
6428 return !is_type_function(type);
6432 * Check if a given expression represents a local variable.
6434 static bool is_local_variable(const expression_t *expression)
6436 if (expression->base.kind != EXPR_REFERENCE) {
6439 const declaration_t *declaration = expression->reference.declaration;
6440 return is_local_var_declaration(declaration);
6444 * Check if a given expression represents a local variable and
6445 * return its declaration then, else return NULL.
6447 declaration_t *expr_is_variable(const expression_t *expression)
6449 if (expression->base.kind != EXPR_REFERENCE) {
6452 declaration_t *declaration = expression->reference.declaration;
6453 if (is_var_declaration(declaration))
6459 * Parse a return statement.
6461 static statement_t *parse_return(void)
6465 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6466 statement->base.source_position = token.source_position;
6468 expression_t *return_value = NULL;
6469 if(token.type != ';') {
6470 return_value = parse_expression();
6474 const type_t *const func_type = current_function->type;
6475 assert(is_type_function(func_type));
6476 type_t *const return_type = skip_typeref(func_type->function.return_type);
6478 if(return_value != NULL) {
6479 type_t *return_value_type = skip_typeref(return_value->base.type);
6481 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6482 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6483 warningf(statement->base.source_position,
6484 "'return' with a value, in function returning void");
6485 return_value = NULL;
6487 type_t *const res_type = semantic_assign(return_type,
6488 return_value, "'return'");
6489 if (res_type == NULL) {
6490 errorf(statement->base.source_position,
6491 "cannot return something of type '%T' in function returning '%T'",
6492 return_value->base.type, return_type);
6494 return_value = create_implicit_cast(return_value, res_type);
6497 /* check for returning address of a local var */
6498 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6499 const expression_t *expression = return_value->unary.value;
6500 if (is_local_variable(expression)) {
6501 warningf(statement->base.source_position,
6502 "function returns address of local variable");
6506 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6507 warningf(statement->base.source_position,
6508 "'return' without value, in function returning non-void");
6511 statement->returns.value = return_value;
6519 * Parse a declaration statement.
6521 static statement_t *parse_declaration_statement(void)
6523 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6525 statement->base.source_position = token.source_position;
6527 declaration_t *before = last_declaration;
6528 parse_declaration(record_declaration);
6530 if(before == NULL) {
6531 statement->declaration.declarations_begin = scope->declarations;
6533 statement->declaration.declarations_begin = before->next;
6535 statement->declaration.declarations_end = last_declaration;
6541 * Parse an expression statement, ie. expr ';'.
6543 static statement_t *parse_expression_statement(void)
6545 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6547 statement->base.source_position = token.source_position;
6548 expression_t *const expr = parse_expression();
6549 statement->expression.expression = expr;
6551 if (warning.unused_value && !expression_has_effect(expr)) {
6552 warningf(expr->base.source_position, "statement has no effect");
6563 * Parse a statement.
6565 static statement_t *parse_statement(void)
6567 statement_t *statement = NULL;
6569 /* declaration or statement */
6570 switch(token.type) {
6572 statement = parse_asm_statement();
6576 statement = parse_case_statement();
6580 statement = parse_default_statement();
6584 statement = parse_compound_statement();
6588 statement = parse_if();
6592 statement = parse_switch();
6596 statement = parse_while();
6600 statement = parse_do();
6604 statement = parse_for();
6608 statement = parse_goto();
6612 statement = parse_continue();
6616 statement = parse_break();
6620 statement = parse_return();
6624 if (warning.empty_statement) {
6625 warningf(HERE, "statement is empty");
6632 if(look_ahead(1)->type == ':') {
6633 statement = parse_label_statement();
6637 if(is_typedef_symbol(token.v.symbol)) {
6638 statement = parse_declaration_statement();
6642 statement = parse_expression_statement();
6645 case T___extension__:
6646 /* this can be a prefix to a declaration or an expression statement */
6647 /* we simply eat it now and parse the rest with tail recursion */
6650 } while(token.type == T___extension__);
6651 statement = parse_statement();
6655 statement = parse_declaration_statement();
6659 statement = parse_expression_statement();
6663 assert(statement == NULL
6664 || statement->base.source_position.input_name != NULL);
6670 * Parse a compound statement.
6672 static statement_t *parse_compound_statement(void)
6674 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6676 statement->base.source_position = token.source_position;
6680 int top = environment_top();
6681 scope_t *last_scope = scope;
6682 set_scope(&statement->compound.scope);
6684 statement_t *last_statement = NULL;
6686 while(token.type != '}' && token.type != T_EOF) {
6687 statement_t *sub_statement = parse_statement();
6688 if(sub_statement == NULL)
6691 if(last_statement != NULL) {
6692 last_statement->base.next = sub_statement;
6694 statement->compound.statements = sub_statement;
6697 while(sub_statement->base.next != NULL)
6698 sub_statement = sub_statement->base.next;
6700 last_statement = sub_statement;
6703 if(token.type == '}') {
6706 errorf(statement->base.source_position,
6707 "end of file while looking for closing '}'");
6710 assert(scope == &statement->compound.scope);
6711 set_scope(last_scope);
6712 environment_pop_to(top);
6718 * Initialize builtin types.
6720 static void initialize_builtin_types(void)
6722 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6723 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6724 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6725 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6726 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6727 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6728 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6729 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6731 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6732 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6733 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6734 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6738 * Check for unused global static functions and variables
6740 static void check_unused_globals(void)
6742 if (!warning.unused_function && !warning.unused_variable)
6745 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6746 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6749 type_t *const type = decl->type;
6751 if (is_type_function(skip_typeref(type))) {
6752 if (!warning.unused_function || decl->is_inline)
6755 s = (decl->init.statement != NULL ? "defined" : "declared");
6757 if (!warning.unused_variable)
6763 warningf(decl->source_position, "'%#T' %s but not used",
6764 type, decl->symbol, s);
6769 * Parse a translation unit.
6771 static translation_unit_t *parse_translation_unit(void)
6773 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6775 assert(global_scope == NULL);
6776 global_scope = &unit->scope;
6778 assert(scope == NULL);
6779 set_scope(&unit->scope);
6781 initialize_builtin_types();
6783 while(token.type != T_EOF) {
6784 if (token.type == ';') {
6785 /* TODO error in strict mode */
6786 warningf(HERE, "stray ';' outside of function");
6789 parse_external_declaration();
6793 assert(scope == &unit->scope);
6795 last_declaration = NULL;
6797 assert(global_scope == &unit->scope);
6798 check_unused_globals();
6799 global_scope = NULL;
6807 * @return the translation unit or NULL if errors occurred.
6809 translation_unit_t *parse(void)
6811 environment_stack = NEW_ARR_F(stack_entry_t, 0);
6812 label_stack = NEW_ARR_F(stack_entry_t, 0);
6813 diagnostic_count = 0;
6817 type_set_output(stderr);
6818 ast_set_output(stderr);
6820 lookahead_bufpos = 0;
6821 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6824 translation_unit_t *unit = parse_translation_unit();
6826 DEL_ARR_F(environment_stack);
6827 DEL_ARR_F(label_stack);
6836 * Initialize the parser.
6838 void init_parser(void)
6841 /* add predefined symbols for extended-decl-modifier */
6842 sym_align = symbol_table_insert("align");
6843 sym_allocate = symbol_table_insert("allocate");
6844 sym_dllimport = symbol_table_insert("dllimport");
6845 sym_dllexport = symbol_table_insert("dllexport");
6846 sym_naked = symbol_table_insert("naked");
6847 sym_noinline = symbol_table_insert("noinline");
6848 sym_noreturn = symbol_table_insert("noreturn");
6849 sym_nothrow = symbol_table_insert("nothrow");
6850 sym_novtable = symbol_table_insert("novtable");
6851 sym_property = symbol_table_insert("property");
6852 sym_get = symbol_table_insert("get");
6853 sym_put = symbol_table_insert("put");
6854 sym_selectany = symbol_table_insert("selectany");
6855 sym_thread = symbol_table_insert("thread");
6856 sym_uuid = symbol_table_insert("uuid");
6858 init_expression_parsers();
6859 obstack_init(&temp_obst);
6861 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6862 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6866 * Terminate the parser.
6868 void exit_parser(void)
6870 obstack_free(&temp_obst, NULL);