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; /**< MS __declspec extended modifier mask */
58 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
59 symbol_t *get_property_sym; /**< the name of the get property if set. */
60 symbol_t *put_property_sym; /**< the name of the put property if set. */
65 * An environment for parsing initializers (and compound literals).
67 typedef struct parse_initializer_env_t {
68 type_t *type; /**< the type of the initializer. In case of an
69 array type with unspecified size this gets
70 adjusted to the actual size. */
71 declaration_t *declaration; /**< the declaration that is initialized if any */
72 bool must_be_constant;
73 } parse_initializer_env_t;
75 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
78 static token_t lookahead_buffer[MAX_LOOKAHEAD];
79 static int lookahead_bufpos;
80 static stack_entry_t *environment_stack = NULL;
81 static stack_entry_t *label_stack = NULL;
82 static scope_t *global_scope = NULL;
83 static scope_t *scope = NULL;
84 static declaration_t *last_declaration = NULL;
85 static declaration_t *current_function = NULL;
86 static switch_statement_t *current_switch = NULL;
87 static statement_t *current_loop = NULL;
88 static goto_statement_t *goto_first = NULL;
89 static goto_statement_t *goto_last = NULL;
90 static label_statement_t *label_first = NULL;
91 static label_statement_t *label_last = NULL;
92 static struct obstack temp_obst;
94 /* symbols for Microsoft extended-decl-modifier */
95 static const symbol_t *sym_align = NULL;
96 static const symbol_t *sym_allocate = NULL;
97 static const symbol_t *sym_dllimport = NULL;
98 static const symbol_t *sym_dllexport = NULL;
99 static const symbol_t *sym_naked = NULL;
100 static const symbol_t *sym_noinline = NULL;
101 static const symbol_t *sym_noreturn = NULL;
102 static const symbol_t *sym_nothrow = NULL;
103 static const symbol_t *sym_novtable = NULL;
104 static const symbol_t *sym_property = NULL;
105 static const symbol_t *sym_get = NULL;
106 static const symbol_t *sym_put = NULL;
107 static const symbol_t *sym_selectany = NULL;
108 static const symbol_t *sym_thread = NULL;
109 static const symbol_t *sym_uuid = NULL;
110 static const symbol_t *sym_deprecated = NULL;
112 /** The token anchor set */
113 static unsigned char token_anchor_set[T_LAST_TOKEN];
115 /** The current source position. */
116 #define HERE token.source_position
118 static type_t *type_valist;
120 static statement_t *parse_compound_statement(void);
121 static statement_t *parse_statement(void);
123 static expression_t *parse_sub_expression(unsigned precedence);
124 static expression_t *parse_expression(void);
125 static type_t *parse_typename(void);
127 static void parse_compound_type_entries(declaration_t *compound_declaration);
128 static declaration_t *parse_declarator(
129 const declaration_specifiers_t *specifiers, bool may_be_abstract);
130 static declaration_t *record_declaration(declaration_t *declaration);
132 static void semantic_comparison(binary_expression_t *expression);
134 #define STORAGE_CLASSES \
141 #define TYPE_QUALIFIERS \
148 #ifdef PROVIDE_COMPLEX
149 #define COMPLEX_SPECIFIERS \
151 #define IMAGINARY_SPECIFIERS \
154 #define COMPLEX_SPECIFIERS
155 #define IMAGINARY_SPECIFIERS
158 #define TYPE_SPECIFIERS \
173 case T___builtin_va_list: \
177 #define DECLARATION_START \
182 #define TYPENAME_START \
187 * Allocate an AST node with given size and
188 * initialize all fields with zero.
190 static void *allocate_ast_zero(size_t size)
192 void *res = allocate_ast(size);
193 memset(res, 0, size);
197 static declaration_t *allocate_declaration_zero(void)
199 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
200 declaration->type = type_error_type;
201 declaration->alignment = 0;
206 * Returns the size of a statement node.
208 * @param kind the statement kind
210 static size_t get_statement_struct_size(statement_kind_t kind)
212 static const size_t sizes[] = {
213 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
214 [STATEMENT_RETURN] = sizeof(return_statement_t),
215 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
216 [STATEMENT_IF] = sizeof(if_statement_t),
217 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
218 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
219 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
220 [STATEMENT_BREAK] = sizeof(statement_base_t),
221 [STATEMENT_GOTO] = sizeof(goto_statement_t),
222 [STATEMENT_LABEL] = sizeof(label_statement_t),
223 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
224 [STATEMENT_WHILE] = sizeof(while_statement_t),
225 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
226 [STATEMENT_FOR] = sizeof(for_statement_t),
227 [STATEMENT_ASM] = sizeof(asm_statement_t)
229 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
230 assert(sizes[kind] != 0);
235 * Allocate a statement node of given kind and initialize all
238 static statement_t *allocate_statement_zero(statement_kind_t kind)
240 size_t size = get_statement_struct_size(kind);
241 statement_t *res = allocate_ast_zero(size);
243 res->base.kind = kind;
248 * Returns the size of an expression node.
250 * @param kind the expression kind
252 static size_t get_expression_struct_size(expression_kind_t kind)
254 static const size_t sizes[] = {
255 [EXPR_INVALID] = sizeof(expression_base_t),
256 [EXPR_REFERENCE] = sizeof(reference_expression_t),
257 [EXPR_CONST] = sizeof(const_expression_t),
258 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
259 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
260 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
261 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
262 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
263 [EXPR_CALL] = sizeof(call_expression_t),
264 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
265 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
266 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
267 [EXPR_SELECT] = sizeof(select_expression_t),
268 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
269 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
270 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
271 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
272 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
273 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
274 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
275 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
276 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
277 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
278 [EXPR_VA_START] = sizeof(va_start_expression_t),
279 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
280 [EXPR_STATEMENT] = sizeof(statement_expression_t),
282 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
283 return sizes[EXPR_UNARY_FIRST];
285 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
286 return sizes[EXPR_BINARY_FIRST];
288 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
289 assert(sizes[kind] != 0);
294 * Allocate an expression node of given kind and initialize all
297 static expression_t *allocate_expression_zero(expression_kind_t kind)
299 size_t size = get_expression_struct_size(kind);
300 expression_t *res = allocate_ast_zero(size);
302 res->base.kind = kind;
303 res->base.type = type_error_type;
308 * Returns the size of a type node.
310 * @param kind the type kind
312 static size_t get_type_struct_size(type_kind_t kind)
314 static const size_t sizes[] = {
315 [TYPE_ATOMIC] = sizeof(atomic_type_t),
316 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
317 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
318 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
319 [TYPE_ENUM] = sizeof(enum_type_t),
320 [TYPE_FUNCTION] = sizeof(function_type_t),
321 [TYPE_POINTER] = sizeof(pointer_type_t),
322 [TYPE_ARRAY] = sizeof(array_type_t),
323 [TYPE_BUILTIN] = sizeof(builtin_type_t),
324 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
325 [TYPE_TYPEOF] = sizeof(typeof_type_t),
327 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
328 assert(kind <= TYPE_TYPEOF);
329 assert(sizes[kind] != 0);
334 * Allocate a type node of given kind and initialize all
337 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
339 size_t size = get_type_struct_size(kind);
340 type_t *res = obstack_alloc(type_obst, size);
341 memset(res, 0, size);
343 res->base.kind = kind;
344 res->base.source_position = source_position;
349 * Returns the size of an initializer node.
351 * @param kind the initializer kind
353 static size_t get_initializer_size(initializer_kind_t kind)
355 static const size_t sizes[] = {
356 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
357 [INITIALIZER_STRING] = sizeof(initializer_string_t),
358 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
359 [INITIALIZER_LIST] = sizeof(initializer_list_t),
360 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
362 assert(kind < sizeof(sizes) / sizeof(*sizes));
363 assert(sizes[kind] != 0);
368 * Allocate an initializer node of given kind and initialize all
371 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
373 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
380 * Free a type from the type obstack.
382 static void free_type(void *type)
384 obstack_free(type_obst, type);
388 * Returns the index of the top element of the environment stack.
390 static size_t environment_top(void)
392 return ARR_LEN(environment_stack);
396 * Returns the index of the top element of the label stack.
398 static size_t label_top(void)
400 return ARR_LEN(label_stack);
404 * Return the next token.
406 static inline void next_token(void)
408 token = lookahead_buffer[lookahead_bufpos];
409 lookahead_buffer[lookahead_bufpos] = lexer_token;
412 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
415 print_token(stderr, &token);
416 fprintf(stderr, "\n");
421 * Return the next token with a given lookahead.
423 static inline const token_t *look_ahead(int num)
425 assert(num > 0 && num <= MAX_LOOKAHEAD);
426 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
427 return &lookahead_buffer[pos];
431 * Adds a token to the token anchor set (a multi-set).
433 static void add_anchor_token(int token_type) {
434 assert(0 <= token_type && token_type < T_LAST_TOKEN);
435 ++token_anchor_set[token_type];
439 * Remove a token from the token anchor set (a multi-set).
441 static void rem_anchor_token(int token_type) {
442 assert(0 <= token_type && token_type < T_LAST_TOKEN);
443 --token_anchor_set[token_type];
446 static bool at_anchor(void) {
449 return token_anchor_set[token.type];
453 * Eat tokens until a matching token is found.
455 static void eat_until_matching_token(int type) {
456 unsigned parenthesis_count = 0;
457 unsigned brace_count = 0;
458 unsigned bracket_count = 0;
459 int end_token = type;
468 while(token.type != end_token ||
469 (parenthesis_count > 0 || brace_count > 0 || bracket_count > 0)) {
473 case '(': ++parenthesis_count; break;
474 case '{': ++brace_count; break;
475 case '[': ++bracket_count; break;
477 if(parenthesis_count > 0)
485 if(bracket_count > 0)
496 * Eat input tokens until an anchor is found.
498 static void eat_until_anchor(void) {
499 if(token.type == T_EOF)
501 while(token_anchor_set[token.type] == 0) {
502 if(token.type == '(' || token.type == '{' || token.type == '[')
503 eat_until_matching_token(token.type);
504 if(token.type == T_EOF)
510 static void eat_block(void) {
511 eat_until_matching_token('{');
512 if(token.type == '}')
516 static void eat_statement(void) {
517 eat_until_matching_token(';');
518 if(token.type == ';')
522 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
525 * Report a parse error because an expected token was not found.
527 static void parse_error_expected(const char *message, ...)
529 if(message != NULL) {
530 errorf(HERE, "%s", message);
533 va_start(ap, message);
534 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
539 * Report a type error.
541 static void type_error(const char *msg, const source_position_t source_position,
544 errorf(source_position, "%s, but found type '%T'", msg, type);
548 * Report an incompatible type.
550 static void type_error_incompatible(const char *msg,
551 const source_position_t source_position, type_t *type1, type_t *type2)
553 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
557 * Expect the the current token is the expected token.
558 * If not, generate an error, eat the current statement,
559 * and goto the end_error label.
561 #define expect(expected) \
563 if(UNLIKELY(token.type != (expected))) { \
564 parse_error_expected(NULL, (expected), 0); \
565 add_anchor_token(expected); \
566 eat_until_anchor(); \
567 rem_anchor_token(expected); \
573 static void set_scope(scope_t *new_scope)
576 scope->last_declaration = last_declaration;
580 last_declaration = new_scope->last_declaration;
584 * Search a symbol in a given namespace and returns its declaration or
585 * NULL if this symbol was not found.
587 static declaration_t *get_declaration(const symbol_t *const symbol,
588 const namespace_t namespc)
590 declaration_t *declaration = symbol->declaration;
591 for( ; declaration != NULL; declaration = declaration->symbol_next) {
592 if(declaration->namespc == namespc)
600 * pushs an environment_entry on the environment stack and links the
601 * corresponding symbol to the new entry
603 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
605 symbol_t *symbol = declaration->symbol;
606 namespace_t namespc = (namespace_t) declaration->namespc;
608 /* replace/add declaration into declaration list of the symbol */
609 declaration_t *iter = symbol->declaration;
611 symbol->declaration = declaration;
613 declaration_t *iter_last = NULL;
614 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
615 /* replace an entry? */
616 if(iter->namespc == namespc) {
617 if(iter_last == NULL) {
618 symbol->declaration = declaration;
620 iter_last->symbol_next = declaration;
622 declaration->symbol_next = iter->symbol_next;
627 assert(iter_last->symbol_next == NULL);
628 iter_last->symbol_next = declaration;
632 /* remember old declaration */
634 entry.symbol = symbol;
635 entry.old_declaration = iter;
636 entry.namespc = (unsigned short) namespc;
637 ARR_APP1(stack_entry_t, *stack_ptr, entry);
640 static void environment_push(declaration_t *declaration)
642 assert(declaration->source_position.input_name != NULL);
643 assert(declaration->parent_scope != NULL);
644 stack_push(&environment_stack, declaration);
647 static void label_push(declaration_t *declaration)
649 declaration->parent_scope = ¤t_function->scope;
650 stack_push(&label_stack, declaration);
654 * pops symbols from the environment stack until @p new_top is the top element
656 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
658 stack_entry_t *stack = *stack_ptr;
659 size_t top = ARR_LEN(stack);
662 assert(new_top <= top);
666 for(i = top; i > new_top; --i) {
667 stack_entry_t *entry = &stack[i - 1];
669 declaration_t *old_declaration = entry->old_declaration;
670 symbol_t *symbol = entry->symbol;
671 namespace_t namespc = (namespace_t)entry->namespc;
673 /* replace/remove declaration */
674 declaration_t *declaration = symbol->declaration;
675 assert(declaration != NULL);
676 if(declaration->namespc == namespc) {
677 if(old_declaration == NULL) {
678 symbol->declaration = declaration->symbol_next;
680 symbol->declaration = old_declaration;
683 declaration_t *iter_last = declaration;
684 declaration_t *iter = declaration->symbol_next;
685 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
686 /* replace an entry? */
687 if(iter->namespc == namespc) {
688 assert(iter_last != NULL);
689 iter_last->symbol_next = old_declaration;
690 if(old_declaration != NULL) {
691 old_declaration->symbol_next = iter->symbol_next;
696 assert(iter != NULL);
700 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
703 static void environment_pop_to(size_t new_top)
705 stack_pop_to(&environment_stack, new_top);
708 static void label_pop_to(size_t new_top)
710 stack_pop_to(&label_stack, new_top);
714 static int get_rank(const type_t *type)
716 assert(!is_typeref(type));
717 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
718 * and esp. footnote 108). However we can't fold constants (yet), so we
719 * can't decide whether unsigned int is possible, while int always works.
720 * (unsigned int would be preferable when possible... for stuff like
721 * struct { enum { ... } bla : 4; } ) */
722 if(type->kind == TYPE_ENUM)
723 return ATOMIC_TYPE_INT;
725 assert(type->kind == TYPE_ATOMIC);
726 return type->atomic.akind;
729 static type_t *promote_integer(type_t *type)
731 if(type->kind == TYPE_BITFIELD)
732 type = type->bitfield.base;
734 if(get_rank(type) < ATOMIC_TYPE_INT)
741 * Create a cast expression.
743 * @param expression the expression to cast
744 * @param dest_type the destination type
746 static expression_t *create_cast_expression(expression_t *expression,
749 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
751 cast->unary.value = expression;
752 cast->base.type = dest_type;
758 * Check if a given expression represents the 0 pointer constant.
760 static bool is_null_pointer_constant(const expression_t *expression)
762 /* skip void* cast */
763 if(expression->kind == EXPR_UNARY_CAST
764 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
765 expression = expression->unary.value;
768 /* TODO: not correct yet, should be any constant integer expression
769 * which evaluates to 0 */
770 if (expression->kind != EXPR_CONST)
773 type_t *const type = skip_typeref(expression->base.type);
774 if (!is_type_integer(type))
777 return expression->conste.v.int_value == 0;
781 * Create an implicit cast expression.
783 * @param expression the expression to cast
784 * @param dest_type the destination type
786 static expression_t *create_implicit_cast(expression_t *expression,
789 type_t *const source_type = expression->base.type;
791 if (source_type == dest_type)
794 return create_cast_expression(expression, dest_type);
797 /** Implements the rules from § 6.5.16.1 */
798 static type_t *semantic_assign(type_t *orig_type_left,
799 const expression_t *const right,
802 type_t *const orig_type_right = right->base.type;
803 type_t *const type_left = skip_typeref(orig_type_left);
804 type_t *const type_right = skip_typeref(orig_type_right);
806 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
807 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
808 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
809 && is_type_pointer(type_right))) {
810 return orig_type_left;
813 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
814 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
815 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
817 /* the left type has all qualifiers from the right type */
818 unsigned missing_qualifiers
819 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
820 if(missing_qualifiers != 0) {
821 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
822 return orig_type_left;
825 points_to_left = get_unqualified_type(points_to_left);
826 points_to_right = get_unqualified_type(points_to_right);
828 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
829 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
830 return orig_type_left;
833 if (!types_compatible(points_to_left, points_to_right)) {
834 warningf(right->base.source_position,
835 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
836 orig_type_left, context, right, orig_type_right);
839 return orig_type_left;
842 if ((is_type_compound(type_left) && is_type_compound(type_right))
843 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
844 type_t *const unqual_type_left = get_unqualified_type(type_left);
845 type_t *const unqual_type_right = get_unqualified_type(type_right);
846 if (types_compatible(unqual_type_left, unqual_type_right)) {
847 return orig_type_left;
851 if (!is_type_valid(type_left))
854 if (!is_type_valid(type_right))
855 return orig_type_right;
860 static expression_t *parse_constant_expression(void)
862 /* start parsing at precedence 7 (conditional expression) */
863 expression_t *result = parse_sub_expression(7);
865 if(!is_constant_expression(result)) {
866 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
872 static expression_t *parse_assignment_expression(void)
874 /* start parsing at precedence 2 (assignment expression) */
875 return parse_sub_expression(2);
878 static type_t *make_global_typedef(const char *name, type_t *type)
880 symbol_t *const symbol = symbol_table_insert(name);
882 declaration_t *const declaration = allocate_declaration_zero();
883 declaration->namespc = NAMESPACE_NORMAL;
884 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
885 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
886 declaration->type = type;
887 declaration->symbol = symbol;
888 declaration->source_position = builtin_source_position;
890 record_declaration(declaration);
892 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
893 typedef_type->typedeft.declaration = declaration;
898 static string_t parse_string_literals(void)
900 assert(token.type == T_STRING_LITERAL);
901 string_t result = token.v.string;
905 while (token.type == T_STRING_LITERAL) {
906 result = concat_strings(&result, &token.v.string);
913 static void parse_attributes(void)
917 case T___attribute__: {
925 errorf(HERE, "EOF while parsing attribute");
944 if(token.type != T_STRING_LITERAL) {
945 parse_error_expected("while parsing assembler attribute",
947 eat_until_matching_token('(');
950 parse_string_literals();
955 goto attributes_finished;
964 static designator_t *parse_designation(void)
966 designator_t *result = NULL;
967 designator_t *last = NULL;
970 designator_t *designator;
973 designator = allocate_ast_zero(sizeof(designator[0]));
974 designator->source_position = token.source_position;
976 designator->array_index = parse_constant_expression();
980 designator = allocate_ast_zero(sizeof(designator[0]));
981 designator->source_position = token.source_position;
983 if(token.type != T_IDENTIFIER) {
984 parse_error_expected("while parsing designator",
988 designator->symbol = token.v.symbol;
996 assert(designator != NULL);
998 last->next = designator;
1000 result = designator;
1008 static initializer_t *initializer_from_string(array_type_t *type,
1009 const string_t *const string)
1011 /* TODO: check len vs. size of array type */
1014 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1015 initializer->string.string = *string;
1020 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1021 wide_string_t *const string)
1023 /* TODO: check len vs. size of array type */
1026 initializer_t *const initializer =
1027 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1028 initializer->wide_string.string = *string;
1034 * Build an initializer from a given expression.
1036 static initializer_t *initializer_from_expression(type_t *orig_type,
1037 expression_t *expression)
1039 /* TODO check that expression is a constant expression */
1041 /* § 6.7.8.14/15 char array may be initialized by string literals */
1042 type_t *type = skip_typeref(orig_type);
1043 type_t *expr_type_orig = expression->base.type;
1044 type_t *expr_type = skip_typeref(expr_type_orig);
1045 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1046 array_type_t *const array_type = &type->array;
1047 type_t *const element_type = skip_typeref(array_type->element_type);
1049 if (element_type->kind == TYPE_ATOMIC) {
1050 atomic_type_kind_t akind = element_type->atomic.akind;
1051 switch (expression->kind) {
1052 case EXPR_STRING_LITERAL:
1053 if (akind == ATOMIC_TYPE_CHAR
1054 || akind == ATOMIC_TYPE_SCHAR
1055 || akind == ATOMIC_TYPE_UCHAR) {
1056 return initializer_from_string(array_type,
1057 &expression->string.value);
1060 case EXPR_WIDE_STRING_LITERAL: {
1061 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1062 if (get_unqualified_type(element_type) == bare_wchar_type) {
1063 return initializer_from_wide_string(array_type,
1064 &expression->wide_string.value);
1074 type_t *const res_type = semantic_assign(type, expression, "initializer");
1075 if (res_type == NULL)
1078 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1079 result->value.value = create_implicit_cast(expression, res_type);
1085 * Checks if a given expression can be used as an constant initializer.
1087 static bool is_initializer_constant(const expression_t *expression)
1089 return is_constant_expression(expression)
1090 || is_address_constant(expression);
1094 * Parses an scalar initializer.
1096 * § 6.7.8.11; eat {} without warning
1098 static initializer_t *parse_scalar_initializer(type_t *type,
1099 bool must_be_constant)
1101 /* there might be extra {} hierarchies */
1103 while(token.type == '{') {
1106 warningf(HERE, "extra curly braces around scalar initializer");
1111 expression_t *expression = parse_assignment_expression();
1112 if(must_be_constant && !is_initializer_constant(expression)) {
1113 errorf(expression->base.source_position,
1114 "Initialisation expression '%E' is not constant\n",
1118 initializer_t *initializer = initializer_from_expression(type, expression);
1120 if(initializer == NULL) {
1121 errorf(expression->base.source_position,
1122 "expression '%E' doesn't match expected type '%T'",
1128 bool additional_warning_displayed = false;
1130 if(token.type == ',') {
1133 if(token.type != '}') {
1134 if(!additional_warning_displayed) {
1135 warningf(HERE, "additional elements in scalar initializer");
1136 additional_warning_displayed = true;
1147 * An entry in the type path.
1149 typedef struct type_path_entry_t type_path_entry_t;
1150 struct type_path_entry_t {
1151 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1153 size_t index; /**< For array types: the current index. */
1154 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1159 * A type path expression a position inside compound or array types.
1161 typedef struct type_path_t type_path_t;
1162 struct type_path_t {
1163 type_path_entry_t *path; /**< An flexible array containing the current path. */
1164 type_t *top_type; /**< type of the element the path points */
1165 size_t max_index; /**< largest index in outermost array */
1169 * Prints a type path for debugging.
1171 static __attribute__((unused)) void debug_print_type_path(
1172 const type_path_t *path)
1174 size_t len = ARR_LEN(path->path);
1176 for(size_t i = 0; i < len; ++i) {
1177 const type_path_entry_t *entry = & path->path[i];
1179 type_t *type = skip_typeref(entry->type);
1180 if(is_type_compound(type)) {
1181 /* in gcc mode structs can have no members */
1182 if(entry->v.compound_entry == NULL) {
1186 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1187 } else if(is_type_array(type)) {
1188 fprintf(stderr, "[%u]", entry->v.index);
1190 fprintf(stderr, "-INVALID-");
1193 if(path->top_type != NULL) {
1194 fprintf(stderr, " (");
1195 print_type(path->top_type);
1196 fprintf(stderr, ")");
1201 * Return the top type path entry, ie. in a path
1202 * (type).a.b returns the b.
1204 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1206 size_t len = ARR_LEN(path->path);
1208 return &path->path[len-1];
1212 * Enlarge the type path by an (empty) element.
1214 static type_path_entry_t *append_to_type_path(type_path_t *path)
1216 size_t len = ARR_LEN(path->path);
1217 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1219 type_path_entry_t *result = & path->path[len];
1220 memset(result, 0, sizeof(result[0]));
1225 * Descending into a sub-type. Enter the scope of the current
1228 static void descend_into_subtype(type_path_t *path)
1230 type_t *orig_top_type = path->top_type;
1231 type_t *top_type = skip_typeref(orig_top_type);
1233 assert(is_type_compound(top_type) || is_type_array(top_type));
1235 type_path_entry_t *top = append_to_type_path(path);
1236 top->type = top_type;
1238 if(is_type_compound(top_type)) {
1239 declaration_t *declaration = top_type->compound.declaration;
1240 declaration_t *entry = declaration->scope.declarations;
1241 top->v.compound_entry = entry;
1244 path->top_type = entry->type;
1246 path->top_type = NULL;
1249 assert(is_type_array(top_type));
1252 path->top_type = top_type->array.element_type;
1257 * Pop an entry from the given type path, ie. returning from
1258 * (type).a.b to (type).a
1260 static void ascend_from_subtype(type_path_t *path)
1262 type_path_entry_t *top = get_type_path_top(path);
1264 path->top_type = top->type;
1266 size_t len = ARR_LEN(path->path);
1267 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1271 * Pop entries from the given type path until the given
1272 * path level is reached.
1274 static void ascend_to(type_path_t *path, size_t top_path_level)
1276 size_t len = ARR_LEN(path->path);
1278 while(len > top_path_level) {
1279 ascend_from_subtype(path);
1280 len = ARR_LEN(path->path);
1284 static bool walk_designator(type_path_t *path, const designator_t *designator,
1285 bool used_in_offsetof)
1287 for( ; designator != NULL; designator = designator->next) {
1288 type_path_entry_t *top = get_type_path_top(path);
1289 type_t *orig_type = top->type;
1291 type_t *type = skip_typeref(orig_type);
1293 if(designator->symbol != NULL) {
1294 symbol_t *symbol = designator->symbol;
1295 if(!is_type_compound(type)) {
1296 if(is_type_valid(type)) {
1297 errorf(designator->source_position,
1298 "'.%Y' designator used for non-compound type '%T'",
1304 declaration_t *declaration = type->compound.declaration;
1305 declaration_t *iter = declaration->scope.declarations;
1306 for( ; iter != NULL; iter = iter->next) {
1307 if(iter->symbol == symbol) {
1312 errorf(designator->source_position,
1313 "'%T' has no member named '%Y'", orig_type, symbol);
1316 if(used_in_offsetof) {
1317 type_t *real_type = skip_typeref(iter->type);
1318 if(real_type->kind == TYPE_BITFIELD) {
1319 errorf(designator->source_position,
1320 "offsetof designator '%Y' may not specify bitfield",
1326 top->type = orig_type;
1327 top->v.compound_entry = iter;
1328 orig_type = iter->type;
1330 expression_t *array_index = designator->array_index;
1331 assert(designator->array_index != NULL);
1333 if(!is_type_array(type)) {
1334 if(is_type_valid(type)) {
1335 errorf(designator->source_position,
1336 "[%E] designator used for non-array type '%T'",
1337 array_index, orig_type);
1341 if(!is_type_valid(array_index->base.type)) {
1345 long index = fold_constant(array_index);
1346 if(!used_in_offsetof) {
1348 errorf(designator->source_position,
1349 "array index [%E] must be positive", array_index);
1352 if(type->array.size_constant == true) {
1353 long array_size = type->array.size;
1354 if(index >= array_size) {
1355 errorf(designator->source_position,
1356 "designator [%E] (%d) exceeds array size %d",
1357 array_index, index, array_size);
1363 top->type = orig_type;
1364 top->v.index = (size_t) index;
1365 orig_type = type->array.element_type;
1367 path->top_type = orig_type;
1369 if(designator->next != NULL) {
1370 descend_into_subtype(path);
1379 static void advance_current_object(type_path_t *path, size_t top_path_level)
1381 type_path_entry_t *top = get_type_path_top(path);
1383 type_t *type = skip_typeref(top->type);
1384 if(is_type_union(type)) {
1385 /* in unions only the first element is initialized */
1386 top->v.compound_entry = NULL;
1387 } else if(is_type_struct(type)) {
1388 declaration_t *entry = top->v.compound_entry;
1390 entry = entry->next;
1391 top->v.compound_entry = entry;
1393 path->top_type = entry->type;
1397 assert(is_type_array(type));
1401 if(!type->array.size_constant || top->v.index < type->array.size) {
1406 /* we're past the last member of the current sub-aggregate, try if we
1407 * can ascend in the type hierarchy and continue with another subobject */
1408 size_t len = ARR_LEN(path->path);
1410 if(len > top_path_level) {
1411 ascend_from_subtype(path);
1412 advance_current_object(path, top_path_level);
1414 path->top_type = NULL;
1419 * skip until token is found.
1421 static void skip_until(int type) {
1422 while(token.type != type) {
1423 if(token.type == T_EOF)
1430 * skip any {...} blocks until a closing braket is reached.
1432 static void skip_initializers(void)
1434 if(token.type == '{')
1437 while(token.type != '}') {
1438 if(token.type == T_EOF)
1440 if(token.type == '{') {
1449 * Parse a part of an initialiser for a struct or union,
1451 static initializer_t *parse_sub_initializer(type_path_t *path,
1452 type_t *outer_type, size_t top_path_level,
1453 parse_initializer_env_t *env)
1455 if(token.type == '}') {
1456 /* empty initializer */
1460 type_t *orig_type = path->top_type;
1461 type_t *type = NULL;
1463 if (orig_type == NULL) {
1464 /* We are initializing an empty compound. */
1466 type = skip_typeref(orig_type);
1468 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1469 * initializers in this case. */
1470 if(!is_type_valid(type)) {
1471 skip_initializers();
1476 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1479 designator_t *designator = NULL;
1480 if(token.type == '.' || token.type == '[') {
1481 designator = parse_designation();
1483 /* reset path to toplevel, evaluate designator from there */
1484 ascend_to(path, top_path_level);
1485 if(!walk_designator(path, designator, false)) {
1486 /* can't continue after designation error */
1490 initializer_t *designator_initializer
1491 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1492 designator_initializer->designator.designator = designator;
1493 ARR_APP1(initializer_t*, initializers, designator_initializer);
1498 if(token.type == '{') {
1499 if(type != NULL && is_type_scalar(type)) {
1500 sub = parse_scalar_initializer(type, env->must_be_constant);
1504 if (env->declaration != NULL)
1505 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1506 env->declaration->symbol);
1508 errorf(HERE, "extra brace group at end of initializer");
1510 descend_into_subtype(path);
1512 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1516 ascend_from_subtype(path);
1520 goto error_parse_next;
1524 /* must be an expression */
1525 expression_t *expression = parse_assignment_expression();
1527 if(env->must_be_constant && !is_initializer_constant(expression)) {
1528 errorf(expression->base.source_position,
1529 "Initialisation expression '%E' is not constant\n",
1534 /* we are already outside, ... */
1538 /* handle { "string" } special case */
1539 if((expression->kind == EXPR_STRING_LITERAL
1540 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1541 && outer_type != NULL) {
1542 sub = initializer_from_expression(outer_type, expression);
1544 if(token.type == ',') {
1547 if(token.type != '}') {
1548 warningf(HERE, "excessive elements in initializer for type '%T'",
1551 /* TODO: eat , ... */
1556 /* descend into subtypes until expression matches type */
1558 orig_type = path->top_type;
1559 type = skip_typeref(orig_type);
1561 sub = initializer_from_expression(orig_type, expression);
1565 if(!is_type_valid(type)) {
1568 if(is_type_scalar(type)) {
1569 errorf(expression->base.source_position,
1570 "expression '%E' doesn't match expected type '%T'",
1571 expression, orig_type);
1575 descend_into_subtype(path);
1579 /* update largest index of top array */
1580 const type_path_entry_t *first = &path->path[0];
1581 type_t *first_type = first->type;
1582 first_type = skip_typeref(first_type);
1583 if(is_type_array(first_type)) {
1584 size_t index = first->v.index;
1585 if(index > path->max_index)
1586 path->max_index = index;
1590 /* append to initializers list */
1591 ARR_APP1(initializer_t*, initializers, sub);
1594 if(env->declaration != NULL)
1595 warningf(HERE, "excess elements in struct initializer for '%Y'",
1596 env->declaration->symbol);
1598 warningf(HERE, "excess elements in struct initializer");
1602 if(token.type == '}') {
1606 if(token.type == '}') {
1611 /* advance to the next declaration if we are not at the end */
1612 advance_current_object(path, top_path_level);
1613 orig_type = path->top_type;
1614 if(orig_type != NULL)
1615 type = skip_typeref(orig_type);
1621 size_t len = ARR_LEN(initializers);
1622 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1623 initializer_t *result = allocate_ast_zero(size);
1624 result->kind = INITIALIZER_LIST;
1625 result->list.len = len;
1626 memcpy(&result->list.initializers, initializers,
1627 len * sizeof(initializers[0]));
1629 DEL_ARR_F(initializers);
1630 ascend_to(path, top_path_level);
1635 skip_initializers();
1636 DEL_ARR_F(initializers);
1637 ascend_to(path, top_path_level);
1642 * Parses an initializer. Parsers either a compound literal
1643 * (env->declaration == NULL) or an initializer of a declaration.
1645 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1647 type_t *type = skip_typeref(env->type);
1648 initializer_t *result = NULL;
1651 if(is_type_scalar(type)) {
1652 result = parse_scalar_initializer(type, env->must_be_constant);
1653 } else if(token.type == '{') {
1657 memset(&path, 0, sizeof(path));
1658 path.top_type = env->type;
1659 path.path = NEW_ARR_F(type_path_entry_t, 0);
1661 descend_into_subtype(&path);
1663 result = parse_sub_initializer(&path, env->type, 1, env);
1665 max_index = path.max_index;
1666 DEL_ARR_F(path.path);
1670 /* parse_scalar_initializer() also works in this case: we simply
1671 * have an expression without {} around it */
1672 result = parse_scalar_initializer(type, env->must_be_constant);
1675 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1676 * the array type size */
1677 if(is_type_array(type) && type->array.size_expression == NULL
1678 && result != NULL) {
1680 switch (result->kind) {
1681 case INITIALIZER_LIST:
1682 size = max_index + 1;
1685 case INITIALIZER_STRING:
1686 size = result->string.string.size;
1689 case INITIALIZER_WIDE_STRING:
1690 size = result->wide_string.string.size;
1694 panic("invalid initializer type");
1697 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1698 cnst->base.type = type_size_t;
1699 cnst->conste.v.int_value = size;
1701 type_t *new_type = duplicate_type(type);
1703 new_type->array.size_expression = cnst;
1704 new_type->array.size_constant = true;
1705 new_type->array.size = size;
1706 env->type = new_type;
1714 static declaration_t *append_declaration(declaration_t *declaration);
1716 static declaration_t *parse_compound_type_specifier(bool is_struct)
1724 symbol_t *symbol = NULL;
1725 declaration_t *declaration = NULL;
1727 if (token.type == T___attribute__) {
1732 if(token.type == T_IDENTIFIER) {
1733 symbol = token.v.symbol;
1737 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1739 declaration = get_declaration(symbol, NAMESPACE_UNION);
1741 } else if(token.type != '{') {
1743 parse_error_expected("while parsing struct type specifier",
1744 T_IDENTIFIER, '{', 0);
1746 parse_error_expected("while parsing union type specifier",
1747 T_IDENTIFIER, '{', 0);
1753 if(declaration == NULL) {
1754 declaration = allocate_declaration_zero();
1755 declaration->namespc =
1756 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1757 declaration->source_position = token.source_position;
1758 declaration->symbol = symbol;
1759 declaration->parent_scope = scope;
1760 if (symbol != NULL) {
1761 environment_push(declaration);
1763 append_declaration(declaration);
1766 if(token.type == '{') {
1767 if(declaration->init.is_defined) {
1768 assert(symbol != NULL);
1769 errorf(HERE, "multiple definitions of '%s %Y'",
1770 is_struct ? "struct" : "union", symbol);
1771 declaration->scope.declarations = NULL;
1773 declaration->init.is_defined = true;
1775 parse_compound_type_entries(declaration);
1782 static void parse_enum_entries(type_t *const enum_type)
1786 if(token.type == '}') {
1788 errorf(HERE, "empty enum not allowed");
1793 if(token.type != T_IDENTIFIER) {
1794 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1799 declaration_t *const entry = allocate_declaration_zero();
1800 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1801 entry->type = enum_type;
1802 entry->symbol = token.v.symbol;
1803 entry->source_position = token.source_position;
1806 if(token.type == '=') {
1808 expression_t *value = parse_constant_expression();
1810 value = create_implicit_cast(value, enum_type);
1811 entry->init.enum_value = value;
1816 record_declaration(entry);
1818 if(token.type != ',')
1821 } while(token.type != '}');
1829 static type_t *parse_enum_specifier(void)
1833 declaration_t *declaration;
1836 if(token.type == T_IDENTIFIER) {
1837 symbol = token.v.symbol;
1840 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1841 } else if(token.type != '{') {
1842 parse_error_expected("while parsing enum type specifier",
1843 T_IDENTIFIER, '{', 0);
1850 if(declaration == NULL) {
1851 declaration = allocate_declaration_zero();
1852 declaration->namespc = NAMESPACE_ENUM;
1853 declaration->source_position = token.source_position;
1854 declaration->symbol = symbol;
1855 declaration->parent_scope = scope;
1858 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1859 type->enumt.declaration = declaration;
1861 if(token.type == '{') {
1862 if(declaration->init.is_defined) {
1863 errorf(HERE, "multiple definitions of enum %Y", symbol);
1865 if (symbol != NULL) {
1866 environment_push(declaration);
1868 append_declaration(declaration);
1869 declaration->init.is_defined = 1;
1871 parse_enum_entries(type);
1879 * if a symbol is a typedef to another type, return true
1881 static bool is_typedef_symbol(symbol_t *symbol)
1883 const declaration_t *const declaration =
1884 get_declaration(symbol, NAMESPACE_NORMAL);
1886 declaration != NULL &&
1887 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1890 static type_t *parse_typeof(void)
1898 expression_t *expression = NULL;
1901 switch(token.type) {
1902 case T___extension__:
1903 /* this can be a prefix to a typename or an expression */
1904 /* we simply eat it now. */
1907 } while(token.type == T___extension__);
1911 if(is_typedef_symbol(token.v.symbol)) {
1912 type = parse_typename();
1914 expression = parse_expression();
1915 type = expression->base.type;
1920 type = parse_typename();
1924 expression = parse_expression();
1925 type = expression->base.type;
1931 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1932 typeof_type->typeoft.expression = expression;
1933 typeof_type->typeoft.typeof_type = type;
1941 SPECIFIER_SIGNED = 1 << 0,
1942 SPECIFIER_UNSIGNED = 1 << 1,
1943 SPECIFIER_LONG = 1 << 2,
1944 SPECIFIER_INT = 1 << 3,
1945 SPECIFIER_DOUBLE = 1 << 4,
1946 SPECIFIER_CHAR = 1 << 5,
1947 SPECIFIER_SHORT = 1 << 6,
1948 SPECIFIER_LONG_LONG = 1 << 7,
1949 SPECIFIER_FLOAT = 1 << 8,
1950 SPECIFIER_BOOL = 1 << 9,
1951 SPECIFIER_VOID = 1 << 10,
1952 #ifdef PROVIDE_COMPLEX
1953 SPECIFIER_COMPLEX = 1 << 11,
1954 SPECIFIER_IMAGINARY = 1 << 12,
1958 static type_t *create_builtin_type(symbol_t *const symbol,
1959 type_t *const real_type)
1961 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1962 type->builtin.symbol = symbol;
1963 type->builtin.real_type = real_type;
1965 type_t *result = typehash_insert(type);
1966 if (type != result) {
1973 static type_t *get_typedef_type(symbol_t *symbol)
1975 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1976 if(declaration == NULL
1977 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1980 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1981 type->typedeft.declaration = declaration;
1987 * check for the allowed MS alignment values.
1989 static bool check_elignment_value(long long intvalue) {
1990 if(intvalue < 1 || intvalue > 8192) {
1991 errorf(HERE, "illegal alignment value");
1994 unsigned v = (unsigned)intvalue;
1995 for(unsigned i = 1; i <= 8192; i += i) {
1999 errorf(HERE, "alignment must be power of two");
2003 #define DET_MOD(name, tag) do { \
2004 if(*modifiers & tag) warningf(HERE, #name " used more than once"); \
2005 *modifiers |= tag; \
2008 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
2011 decl_modifiers_t *modifiers = &specifiers->decl_modifiers;
2013 while(token.type == T_IDENTIFIER) {
2014 symbol = token.v.symbol;
2015 if(symbol == sym_align) {
2018 if(token.type != T_INTEGER)
2020 if(check_elignment_value(token.v.intvalue)) {
2021 if(specifiers->alignment != 0)
2022 warningf(HERE, "align used more than once");
2023 specifiers->alignment = (unsigned char)token.v.intvalue;
2027 } else if(symbol == sym_allocate) {
2030 if(token.type != T_IDENTIFIER)
2032 (void)token.v.symbol;
2034 } else if(symbol == sym_dllimport) {
2036 DET_MOD(dllimport, DM_DLLIMPORT);
2037 } else if(symbol == sym_dllexport) {
2039 DET_MOD(dllexport, DM_DLLEXPORT);
2040 } else if(symbol == sym_thread) {
2042 DET_MOD(thread, DM_THREAD);
2043 } else if(symbol == sym_naked) {
2045 DET_MOD(naked, DM_NAKED);
2046 } else if(symbol == sym_noinline) {
2048 DET_MOD(noinline, DM_NOINLINE);
2049 } else if(symbol == sym_noreturn) {
2051 DET_MOD(noreturn, DM_NORETURN);
2052 } else if(symbol == sym_nothrow) {
2054 DET_MOD(nothrow, DM_NOTHROW);
2055 } else if(symbol == sym_novtable) {
2057 DET_MOD(novtable, DM_NOVTABLE);
2058 } else if(symbol == sym_property) {
2062 bool is_get = false;
2063 if(token.type != T_IDENTIFIER)
2065 if(token.v.symbol == sym_get) {
2067 } else if(token.v.symbol == sym_put) {
2069 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
2074 if(token.type != T_IDENTIFIER)
2077 if(specifiers->get_property_sym != NULL) {
2078 errorf(HERE, "get property name already specified");
2080 specifiers->get_property_sym = token.v.symbol;
2083 if(specifiers->put_property_sym != NULL) {
2084 errorf(HERE, "put property name already specified");
2086 specifiers->put_property_sym = token.v.symbol;
2090 if(token.type == ',') {
2097 } else if(symbol == sym_selectany) {
2099 DET_MOD(selectany, DM_SELECTANY);
2100 } else if(symbol == sym_uuid) {
2103 if(token.type != T_STRING_LITERAL)
2107 } else if(symbol == sym_deprecated) {
2109 DET_MOD(deprecated, DM_DEPRECATED);
2110 if(token.type == '(') {
2112 if(token.type == T_STRING_LITERAL) {
2113 specifiers->deprecated_string = token.v.string.begin;
2116 errorf(HERE, "string literal expected");
2121 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
2123 if(token.type == '(')
2126 if (token.type == ',')
2133 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2135 type_t *type = NULL;
2136 unsigned type_qualifiers = 0;
2137 unsigned type_specifiers = 0;
2140 specifiers->source_position = token.source_position;
2143 switch(token.type) {
2146 #define MATCH_STORAGE_CLASS(token, class) \
2148 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
2149 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2151 specifiers->declared_storage_class = class; \
2155 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2156 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2157 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2158 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2159 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2164 parse_microsoft_extended_decl_modifier(specifiers);
2169 switch (specifiers->declared_storage_class) {
2170 case STORAGE_CLASS_NONE:
2171 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
2174 case STORAGE_CLASS_EXTERN:
2175 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
2178 case STORAGE_CLASS_STATIC:
2179 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
2183 errorf(HERE, "multiple storage classes in declaration specifiers");
2189 /* type qualifiers */
2190 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2192 type_qualifiers |= qualifier; \
2196 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2197 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2198 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2200 case T___extension__:
2205 /* type specifiers */
2206 #define MATCH_SPECIFIER(token, specifier, name) \
2209 if(type_specifiers & specifier) { \
2210 errorf(HERE, "multiple " name " type specifiers given"); \
2212 type_specifiers |= specifier; \
2216 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2217 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2218 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2219 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2220 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2221 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2222 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2223 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2224 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2225 #ifdef PROVIDE_COMPLEX
2226 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2227 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2230 /* only in microsoft mode */
2231 specifiers->decl_modifiers |= DM_FORCEINLINE;
2235 specifiers->is_inline = true;
2240 if(type_specifiers & SPECIFIER_LONG_LONG) {
2241 errorf(HERE, "multiple type specifiers given");
2242 } else if(type_specifiers & SPECIFIER_LONG) {
2243 type_specifiers |= SPECIFIER_LONG_LONG;
2245 type_specifiers |= SPECIFIER_LONG;
2250 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2252 type->compound.declaration = parse_compound_type_specifier(true);
2256 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2258 type->compound.declaration = parse_compound_type_specifier(false);
2262 type = parse_enum_specifier();
2265 type = parse_typeof();
2267 case T___builtin_va_list:
2268 type = duplicate_type(type_valist);
2272 case T___attribute__:
2276 case T_IDENTIFIER: {
2277 /* only parse identifier if we haven't found a type yet */
2278 if(type != NULL || type_specifiers != 0)
2279 goto finish_specifiers;
2281 type_t *typedef_type = get_typedef_type(token.v.symbol);
2283 if(typedef_type == NULL)
2284 goto finish_specifiers;
2287 type = typedef_type;
2291 /* function specifier */
2293 goto finish_specifiers;
2300 atomic_type_kind_t atomic_type;
2302 /* match valid basic types */
2303 switch(type_specifiers) {
2304 case SPECIFIER_VOID:
2305 atomic_type = ATOMIC_TYPE_VOID;
2307 case SPECIFIER_CHAR:
2308 atomic_type = ATOMIC_TYPE_CHAR;
2310 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2311 atomic_type = ATOMIC_TYPE_SCHAR;
2313 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2314 atomic_type = ATOMIC_TYPE_UCHAR;
2316 case SPECIFIER_SHORT:
2317 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2318 case SPECIFIER_SHORT | SPECIFIER_INT:
2319 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2320 atomic_type = ATOMIC_TYPE_SHORT;
2322 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2323 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2324 atomic_type = ATOMIC_TYPE_USHORT;
2327 case SPECIFIER_SIGNED:
2328 case SPECIFIER_SIGNED | SPECIFIER_INT:
2329 atomic_type = ATOMIC_TYPE_INT;
2331 case SPECIFIER_UNSIGNED:
2332 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2333 atomic_type = ATOMIC_TYPE_UINT;
2335 case SPECIFIER_LONG:
2336 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2337 case SPECIFIER_LONG | SPECIFIER_INT:
2338 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2339 atomic_type = ATOMIC_TYPE_LONG;
2341 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2342 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2343 atomic_type = ATOMIC_TYPE_ULONG;
2345 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2346 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2347 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2348 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2350 atomic_type = ATOMIC_TYPE_LONGLONG;
2352 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2353 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2355 atomic_type = ATOMIC_TYPE_ULONGLONG;
2357 case SPECIFIER_FLOAT:
2358 atomic_type = ATOMIC_TYPE_FLOAT;
2360 case SPECIFIER_DOUBLE:
2361 atomic_type = ATOMIC_TYPE_DOUBLE;
2363 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2364 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2366 case SPECIFIER_BOOL:
2367 atomic_type = ATOMIC_TYPE_BOOL;
2369 #ifdef PROVIDE_COMPLEX
2370 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2371 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2373 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2374 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2376 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2377 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2379 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2380 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2382 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2383 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2385 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2386 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2390 /* invalid specifier combination, give an error message */
2391 if(type_specifiers == 0) {
2392 if (! strict_mode) {
2393 if (warning.implicit_int) {
2394 warningf(HERE, "no type specifiers in declaration, using 'int'");
2396 atomic_type = ATOMIC_TYPE_INT;
2399 errorf(HERE, "no type specifiers given in declaration");
2401 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2402 (type_specifiers & SPECIFIER_UNSIGNED)) {
2403 errorf(HERE, "signed and unsigned specifiers gives");
2404 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2405 errorf(HERE, "only integer types can be signed or unsigned");
2407 errorf(HERE, "multiple datatypes in declaration");
2409 atomic_type = ATOMIC_TYPE_INVALID;
2412 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2413 type->atomic.akind = atomic_type;
2416 if(type_specifiers != 0) {
2417 errorf(HERE, "multiple datatypes in declaration");
2421 type->base.qualifiers = type_qualifiers;
2423 type_t *result = typehash_insert(type);
2424 if(newtype && result != type) {
2428 specifiers->type = result;
2433 static type_qualifiers_t parse_type_qualifiers(void)
2435 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2438 switch(token.type) {
2439 /* type qualifiers */
2440 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2441 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2442 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2445 return type_qualifiers;
2450 static declaration_t *parse_identifier_list(void)
2452 declaration_t *declarations = NULL;
2453 declaration_t *last_declaration = NULL;
2455 declaration_t *const declaration = allocate_declaration_zero();
2456 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2457 declaration->source_position = token.source_position;
2458 declaration->symbol = token.v.symbol;
2461 if(last_declaration != NULL) {
2462 last_declaration->next = declaration;
2464 declarations = declaration;
2466 last_declaration = declaration;
2468 if(token.type != ',')
2471 } while(token.type == T_IDENTIFIER);
2473 return declarations;
2476 static void semantic_parameter(declaration_t *declaration)
2478 /* TODO: improve error messages */
2480 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2481 errorf(HERE, "typedef not allowed in parameter list");
2482 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2483 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2484 errorf(HERE, "parameter may only have none or register storage class");
2487 type_t *const orig_type = declaration->type;
2488 type_t * type = skip_typeref(orig_type);
2490 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2491 * into a pointer. § 6.7.5.3 (7) */
2492 if (is_type_array(type)) {
2493 type_t *const element_type = type->array.element_type;
2495 type = make_pointer_type(element_type, type->base.qualifiers);
2497 declaration->type = type;
2500 if(is_type_incomplete(type)) {
2501 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2502 orig_type, declaration->symbol);
2506 static declaration_t *parse_parameter(void)
2508 declaration_specifiers_t specifiers;
2509 memset(&specifiers, 0, sizeof(specifiers));
2511 parse_declaration_specifiers(&specifiers);
2513 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2515 semantic_parameter(declaration);
2520 static declaration_t *parse_parameters(function_type_t *type)
2522 if(token.type == T_IDENTIFIER) {
2523 symbol_t *symbol = token.v.symbol;
2524 if(!is_typedef_symbol(symbol)) {
2525 type->kr_style_parameters = true;
2526 return parse_identifier_list();
2530 if(token.type == ')') {
2531 type->unspecified_parameters = 1;
2534 if(token.type == T_void && look_ahead(1)->type == ')') {
2539 declaration_t *declarations = NULL;
2540 declaration_t *declaration;
2541 declaration_t *last_declaration = NULL;
2542 function_parameter_t *parameter;
2543 function_parameter_t *last_parameter = NULL;
2546 switch(token.type) {
2550 return declarations;
2553 case T___extension__:
2555 declaration = parse_parameter();
2557 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2558 memset(parameter, 0, sizeof(parameter[0]));
2559 parameter->type = declaration->type;
2561 if(last_parameter != NULL) {
2562 last_declaration->next = declaration;
2563 last_parameter->next = parameter;
2565 type->parameters = parameter;
2566 declarations = declaration;
2568 last_parameter = parameter;
2569 last_declaration = declaration;
2573 return declarations;
2575 if(token.type != ',')
2576 return declarations;
2586 } construct_type_kind_t;
2588 typedef struct construct_type_t construct_type_t;
2589 struct construct_type_t {
2590 construct_type_kind_t kind;
2591 construct_type_t *next;
2594 typedef struct parsed_pointer_t parsed_pointer_t;
2595 struct parsed_pointer_t {
2596 construct_type_t construct_type;
2597 type_qualifiers_t type_qualifiers;
2600 typedef struct construct_function_type_t construct_function_type_t;
2601 struct construct_function_type_t {
2602 construct_type_t construct_type;
2603 type_t *function_type;
2606 typedef struct parsed_array_t parsed_array_t;
2607 struct parsed_array_t {
2608 construct_type_t construct_type;
2609 type_qualifiers_t type_qualifiers;
2615 typedef struct construct_base_type_t construct_base_type_t;
2616 struct construct_base_type_t {
2617 construct_type_t construct_type;
2621 static construct_type_t *parse_pointer_declarator(void)
2625 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2626 memset(pointer, 0, sizeof(pointer[0]));
2627 pointer->construct_type.kind = CONSTRUCT_POINTER;
2628 pointer->type_qualifiers = parse_type_qualifiers();
2630 return (construct_type_t*) pointer;
2633 static construct_type_t *parse_array_declarator(void)
2637 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2638 memset(array, 0, sizeof(array[0]));
2639 array->construct_type.kind = CONSTRUCT_ARRAY;
2641 if(token.type == T_static) {
2642 array->is_static = true;
2646 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2647 if(type_qualifiers != 0) {
2648 if(token.type == T_static) {
2649 array->is_static = true;
2653 array->type_qualifiers = type_qualifiers;
2655 if(token.type == '*' && look_ahead(1)->type == ']') {
2656 array->is_variable = true;
2658 } else if(token.type != ']') {
2659 array->size = parse_assignment_expression();
2664 return (construct_type_t*) array;
2669 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2674 if(declaration != NULL) {
2675 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2677 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2680 declaration_t *parameters = parse_parameters(&type->function);
2681 if(declaration != NULL) {
2682 declaration->scope.declarations = parameters;
2685 construct_function_type_t *construct_function_type =
2686 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2687 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2688 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2689 construct_function_type->function_type = type;
2694 return (construct_type_t*) construct_function_type;
2697 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2698 bool may_be_abstract)
2700 /* construct a single linked list of construct_type_t's which describe
2701 * how to construct the final declarator type */
2702 construct_type_t *first = NULL;
2703 construct_type_t *last = NULL;
2706 while(token.type == '*') {
2707 construct_type_t *type = parse_pointer_declarator();
2718 /* TODO: find out if this is correct */
2721 construct_type_t *inner_types = NULL;
2723 switch(token.type) {
2725 if(declaration == NULL) {
2726 errorf(HERE, "no identifier expected in typename");
2728 declaration->symbol = token.v.symbol;
2729 declaration->source_position = token.source_position;
2735 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2741 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2742 /* avoid a loop in the outermost scope, because eat_statement doesn't
2744 if(token.type == '}' && current_function == NULL) {
2752 construct_type_t *p = last;
2755 construct_type_t *type;
2756 switch(token.type) {
2758 type = parse_function_declarator(declaration);
2761 type = parse_array_declarator();
2764 goto declarator_finished;
2767 /* insert in the middle of the list (behind p) */
2769 type->next = p->next;
2780 declarator_finished:
2783 /* append inner_types at the end of the list, we don't to set last anymore
2784 * as it's not needed anymore */
2786 assert(first == NULL);
2787 first = inner_types;
2789 last->next = inner_types;
2797 static type_t *construct_declarator_type(construct_type_t *construct_list,
2800 construct_type_t *iter = construct_list;
2801 for( ; iter != NULL; iter = iter->next) {
2802 switch(iter->kind) {
2803 case CONSTRUCT_INVALID:
2804 panic("invalid type construction found");
2805 case CONSTRUCT_FUNCTION: {
2806 construct_function_type_t *construct_function_type
2807 = (construct_function_type_t*) iter;
2809 type_t *function_type = construct_function_type->function_type;
2811 function_type->function.return_type = type;
2813 type_t *skipped_return_type = skip_typeref(type);
2814 if (is_type_function(skipped_return_type)) {
2815 errorf(HERE, "function returning function is not allowed");
2816 type = type_error_type;
2817 } else if (is_type_array(skipped_return_type)) {
2818 errorf(HERE, "function returning array is not allowed");
2819 type = type_error_type;
2821 type = function_type;
2826 case CONSTRUCT_POINTER: {
2827 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2828 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2829 pointer_type->pointer.points_to = type;
2830 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2832 type = pointer_type;
2836 case CONSTRUCT_ARRAY: {
2837 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2838 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2840 expression_t *size_expression = parsed_array->size;
2841 if(size_expression != NULL) {
2843 = create_implicit_cast(size_expression, type_size_t);
2846 array_type->base.qualifiers = parsed_array->type_qualifiers;
2847 array_type->array.element_type = type;
2848 array_type->array.is_static = parsed_array->is_static;
2849 array_type->array.is_variable = parsed_array->is_variable;
2850 array_type->array.size_expression = size_expression;
2852 if(size_expression != NULL) {
2853 if(is_constant_expression(size_expression)) {
2854 array_type->array.size_constant = true;
2855 array_type->array.size
2856 = fold_constant(size_expression);
2858 array_type->array.is_vla = true;
2862 type_t *skipped_type = skip_typeref(type);
2863 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2864 errorf(HERE, "array of void is not allowed");
2865 type = type_error_type;
2873 type_t *hashed_type = typehash_insert(type);
2874 if(hashed_type != type) {
2875 /* the function type was constructed earlier freeing it here will
2876 * destroy other types... */
2877 if(iter->kind != CONSTRUCT_FUNCTION) {
2887 static declaration_t *parse_declarator(
2888 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2890 declaration_t *const declaration = allocate_declaration_zero();
2891 declaration->declared_storage_class = specifiers->declared_storage_class;
2892 declaration->modifiers = specifiers->decl_modifiers;
2893 declaration->deprecated_string = specifiers->deprecated_string;
2894 declaration->get_property_sym = specifiers->get_property_sym;
2895 declaration->put_property_sym = specifiers->put_property_sym;
2896 declaration->is_inline = specifiers->is_inline;
2898 declaration->storage_class = specifiers->declared_storage_class;
2899 if(declaration->storage_class == STORAGE_CLASS_NONE
2900 && scope != global_scope) {
2901 declaration->storage_class = STORAGE_CLASS_AUTO;
2904 if(specifiers->alignment != 0) {
2905 /* TODO: add checks here */
2906 declaration->alignment = specifiers->alignment;
2909 construct_type_t *construct_type
2910 = parse_inner_declarator(declaration, may_be_abstract);
2911 type_t *const type = specifiers->type;
2912 declaration->type = construct_declarator_type(construct_type, type);
2914 if(construct_type != NULL) {
2915 obstack_free(&temp_obst, construct_type);
2921 static type_t *parse_abstract_declarator(type_t *base_type)
2923 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2925 type_t *result = construct_declarator_type(construct_type, base_type);
2926 if(construct_type != NULL) {
2927 obstack_free(&temp_obst, construct_type);
2933 static declaration_t *append_declaration(declaration_t* const declaration)
2935 if (last_declaration != NULL) {
2936 last_declaration->next = declaration;
2938 scope->declarations = declaration;
2940 last_declaration = declaration;
2945 * Check if the declaration of main is suspicious. main should be a
2946 * function with external linkage, returning int, taking either zero
2947 * arguments, two, or three arguments of appropriate types, ie.
2949 * int main([ int argc, char **argv [, char **env ] ]).
2951 * @param decl the declaration to check
2952 * @param type the function type of the declaration
2954 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2956 if (decl->storage_class == STORAGE_CLASS_STATIC) {
2957 warningf(decl->source_position, "'main' is normally a non-static function");
2959 if (skip_typeref(func_type->return_type) != type_int) {
2960 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2962 const function_parameter_t *parm = func_type->parameters;
2964 type_t *const first_type = parm->type;
2965 if (!types_compatible(skip_typeref(first_type), type_int)) {
2966 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2970 type_t *const second_type = parm->type;
2971 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2972 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2976 type_t *const third_type = parm->type;
2977 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2978 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2982 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2986 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2992 * Check if a symbol is the equal to "main".
2994 static bool is_sym_main(const symbol_t *const sym)
2996 return strcmp(sym->string, "main") == 0;
2999 static declaration_t *internal_record_declaration(
3000 declaration_t *const declaration,
3001 const bool is_function_definition)
3003 const symbol_t *const symbol = declaration->symbol;
3004 const namespace_t namespc = (namespace_t)declaration->namespc;
3006 type_t *const orig_type = declaration->type;
3007 type_t *const type = skip_typeref(orig_type);
3008 if (is_type_function(type) &&
3009 type->function.unspecified_parameters &&
3010 warning.strict_prototypes) {
3011 warningf(declaration->source_position,
3012 "function declaration '%#T' is not a prototype",
3013 orig_type, declaration->symbol);
3016 if (is_function_definition && warning.main && is_sym_main(symbol)) {
3017 check_type_of_main(declaration, &type->function);
3020 assert(declaration->symbol != NULL);
3021 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3023 assert(declaration != previous_declaration);
3024 if (previous_declaration != NULL) {
3025 if (previous_declaration->parent_scope == scope) {
3026 /* can happen for K&R style declarations */
3027 if(previous_declaration->type == NULL) {
3028 previous_declaration->type = declaration->type;
3031 const type_t *prev_type = skip_typeref(previous_declaration->type);
3032 if (!types_compatible(type, prev_type)) {
3033 errorf(declaration->source_position,
3034 "declaration '%#T' is incompatible with "
3035 "previous declaration '%#T'",
3036 orig_type, symbol, previous_declaration->type, symbol);
3037 errorf(previous_declaration->source_position,
3038 "previous declaration of '%Y' was here", symbol);
3040 unsigned old_storage_class = previous_declaration->storage_class;
3041 if (old_storage_class == STORAGE_CLASS_ENUM_ENTRY) {
3042 errorf(declaration->source_position, "redeclaration of enum entry '%Y'", symbol);
3043 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
3044 return previous_declaration;
3047 unsigned new_storage_class = declaration->storage_class;
3049 if(is_type_incomplete(prev_type)) {
3050 previous_declaration->type = type;
3054 /* pretend no storage class means extern for function
3055 * declarations (except if the previous declaration is neither
3056 * none nor extern) */
3057 if (is_type_function(type)) {
3058 switch (old_storage_class) {
3059 case STORAGE_CLASS_NONE:
3060 old_storage_class = STORAGE_CLASS_EXTERN;
3062 case STORAGE_CLASS_EXTERN:
3063 if (is_function_definition) {
3064 if (warning.missing_prototypes &&
3065 prev_type->function.unspecified_parameters &&
3066 !is_sym_main(symbol)) {
3067 warningf(declaration->source_position,
3068 "no previous prototype for '%#T'",
3071 } else if (new_storage_class == STORAGE_CLASS_NONE) {
3072 new_storage_class = STORAGE_CLASS_EXTERN;
3080 if (old_storage_class == STORAGE_CLASS_EXTERN &&
3081 new_storage_class == STORAGE_CLASS_EXTERN) {
3082 warn_redundant_declaration:
3083 if (warning.redundant_decls) {
3084 warningf(declaration->source_position,
3085 "redundant declaration for '%Y'", symbol);
3086 warningf(previous_declaration->source_position,
3087 "previous declaration of '%Y' was here",
3090 } else if (current_function == NULL) {
3091 if (old_storage_class != STORAGE_CLASS_STATIC &&
3092 new_storage_class == STORAGE_CLASS_STATIC) {
3093 errorf(declaration->source_position,
3094 "static declaration of '%Y' follows non-static declaration",
3096 errorf(previous_declaration->source_position,
3097 "previous declaration of '%Y' was here", symbol);
3099 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
3100 goto warn_redundant_declaration;
3102 if (new_storage_class == STORAGE_CLASS_NONE) {
3103 previous_declaration->storage_class = STORAGE_CLASS_NONE;
3104 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
3108 if (old_storage_class == new_storage_class) {
3109 errorf(declaration->source_position,
3110 "redeclaration of '%Y'", symbol);
3112 errorf(declaration->source_position,
3113 "redeclaration of '%Y' with different linkage",
3116 errorf(previous_declaration->source_position,
3117 "previous declaration of '%Y' was here", symbol);
3120 return previous_declaration;
3122 } else if (is_function_definition) {
3123 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
3124 if (warning.missing_prototypes && !is_sym_main(symbol)) {
3125 warningf(declaration->source_position,
3126 "no previous prototype for '%#T'", orig_type, symbol);
3127 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
3128 warningf(declaration->source_position,
3129 "no previous declaration for '%#T'", orig_type,
3133 } else if (warning.missing_declarations &&
3134 scope == global_scope &&
3135 !is_type_function(type) && (
3136 declaration->storage_class == STORAGE_CLASS_NONE ||
3137 declaration->storage_class == STORAGE_CLASS_THREAD
3139 warningf(declaration->source_position,
3140 "no previous declaration for '%#T'", orig_type, symbol);
3143 assert(declaration->parent_scope == NULL);
3144 assert(scope != NULL);
3146 declaration->parent_scope = scope;
3148 environment_push(declaration);
3149 return append_declaration(declaration);
3152 static declaration_t *record_declaration(declaration_t *declaration)
3154 return internal_record_declaration(declaration, false);
3157 static declaration_t *record_function_definition(declaration_t *declaration)
3159 return internal_record_declaration(declaration, true);
3162 static void parser_error_multiple_definition(declaration_t *declaration,
3163 const source_position_t source_position)
3165 errorf(source_position, "multiple definition of symbol '%Y'",
3166 declaration->symbol);
3167 errorf(declaration->source_position,
3168 "this is the location of the previous definition.");
3171 static bool is_declaration_specifier(const token_t *token,
3172 bool only_type_specifiers)
3174 switch(token->type) {
3178 return is_typedef_symbol(token->v.symbol);
3180 case T___extension__:
3183 return !only_type_specifiers;
3190 static void parse_init_declarator_rest(declaration_t *declaration)
3194 type_t *orig_type = declaration->type;
3195 type_t *type = skip_typeref(orig_type);
3197 if(declaration->init.initializer != NULL) {
3198 parser_error_multiple_definition(declaration, token.source_position);
3201 bool must_be_constant = false;
3202 if(declaration->storage_class == STORAGE_CLASS_STATIC
3203 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
3204 || declaration->parent_scope == global_scope) {
3205 must_be_constant = true;
3208 parse_initializer_env_t env;
3209 env.type = orig_type;
3210 env.must_be_constant = must_be_constant;
3211 env.declaration = declaration;
3213 initializer_t *initializer = parse_initializer(&env);
3215 if(env.type != orig_type) {
3216 orig_type = env.type;
3217 type = skip_typeref(orig_type);
3218 declaration->type = env.type;
3221 if(is_type_function(type)) {
3222 errorf(declaration->source_position,
3223 "initializers not allowed for function types at declator '%Y' (type '%T')",
3224 declaration->symbol, orig_type);
3226 declaration->init.initializer = initializer;
3230 /* parse rest of a declaration without any declarator */
3231 static void parse_anonymous_declaration_rest(
3232 const declaration_specifiers_t *specifiers,
3233 parsed_declaration_func finished_declaration)
3237 declaration_t *const declaration = allocate_declaration_zero();
3238 declaration->type = specifiers->type;
3239 declaration->declared_storage_class = specifiers->declared_storage_class;
3240 declaration->source_position = specifiers->source_position;
3241 declaration->modifiers = specifiers->decl_modifiers;
3243 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3244 warningf(declaration->source_position, "useless storage class in empty declaration");
3246 declaration->storage_class = STORAGE_CLASS_NONE;
3248 type_t *type = declaration->type;
3249 switch (type->kind) {
3250 case TYPE_COMPOUND_STRUCT:
3251 case TYPE_COMPOUND_UNION: {
3252 if (type->compound.declaration->symbol == NULL) {
3253 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3262 warningf(declaration->source_position, "empty declaration");
3266 finished_declaration(declaration);
3269 static void parse_declaration_rest(declaration_t *ndeclaration,
3270 const declaration_specifiers_t *specifiers,
3271 parsed_declaration_func finished_declaration)
3274 declaration_t *declaration = finished_declaration(ndeclaration);
3276 type_t *orig_type = declaration->type;
3277 type_t *type = skip_typeref(orig_type);
3279 if (type->kind != TYPE_FUNCTION &&
3280 declaration->is_inline &&
3281 is_type_valid(type)) {
3282 warningf(declaration->source_position,
3283 "variable '%Y' declared 'inline'\n", declaration->symbol);
3286 if(token.type == '=') {
3287 parse_init_declarator_rest(declaration);
3290 if(token.type != ',')
3294 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3302 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3304 symbol_t *symbol = declaration->symbol;
3305 if(symbol == NULL) {
3306 errorf(HERE, "anonymous declaration not valid as function parameter");
3309 namespace_t namespc = (namespace_t) declaration->namespc;
3310 if(namespc != NAMESPACE_NORMAL) {
3311 return record_declaration(declaration);
3314 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3315 if(previous_declaration == NULL ||
3316 previous_declaration->parent_scope != scope) {
3317 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3322 if(previous_declaration->type == NULL) {
3323 previous_declaration->type = declaration->type;
3324 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3325 previous_declaration->storage_class = declaration->storage_class;
3326 previous_declaration->parent_scope = scope;
3327 return previous_declaration;
3329 return record_declaration(declaration);
3333 static void parse_declaration(parsed_declaration_func finished_declaration)
3335 declaration_specifiers_t specifiers;
3336 memset(&specifiers, 0, sizeof(specifiers));
3337 parse_declaration_specifiers(&specifiers);
3339 if(token.type == ';') {
3340 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3342 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3343 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3347 static void parse_kr_declaration_list(declaration_t *declaration)
3349 type_t *type = skip_typeref(declaration->type);
3350 if(!is_type_function(type))
3353 if(!type->function.kr_style_parameters)
3356 /* push function parameters */
3357 int top = environment_top();
3358 scope_t *last_scope = scope;
3359 set_scope(&declaration->scope);
3361 declaration_t *parameter = declaration->scope.declarations;
3362 for( ; parameter != NULL; parameter = parameter->next) {
3363 assert(parameter->parent_scope == NULL);
3364 parameter->parent_scope = scope;
3365 environment_push(parameter);
3368 /* parse declaration list */
3369 while(is_declaration_specifier(&token, false)) {
3370 parse_declaration(finished_kr_declaration);
3373 /* pop function parameters */
3374 assert(scope == &declaration->scope);
3375 set_scope(last_scope);
3376 environment_pop_to(top);
3378 /* update function type */
3379 type_t *new_type = duplicate_type(type);
3380 new_type->function.kr_style_parameters = false;
3382 function_parameter_t *parameters = NULL;
3383 function_parameter_t *last_parameter = NULL;
3385 declaration_t *parameter_declaration = declaration->scope.declarations;
3386 for( ; parameter_declaration != NULL;
3387 parameter_declaration = parameter_declaration->next) {
3388 type_t *parameter_type = parameter_declaration->type;
3389 if(parameter_type == NULL) {
3391 errorf(HERE, "no type specified for function parameter '%Y'",
3392 parameter_declaration->symbol);
3394 if (warning.implicit_int) {
3395 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3396 parameter_declaration->symbol);
3398 parameter_type = type_int;
3399 parameter_declaration->type = parameter_type;
3403 semantic_parameter(parameter_declaration);
3404 parameter_type = parameter_declaration->type;
3406 function_parameter_t *function_parameter
3407 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3408 memset(function_parameter, 0, sizeof(function_parameter[0]));
3410 function_parameter->type = parameter_type;
3411 if(last_parameter != NULL) {
3412 last_parameter->next = function_parameter;
3414 parameters = function_parameter;
3416 last_parameter = function_parameter;
3418 new_type->function.parameters = parameters;
3420 type = typehash_insert(new_type);
3421 if(type != new_type) {
3422 obstack_free(type_obst, new_type);
3425 declaration->type = type;
3428 static bool first_err = true;
3431 * When called with first_err set, prints the name of the current function,
3434 static void print_in_function(void) {
3437 diagnosticf("%s: In function '%Y':\n",
3438 current_function->source_position.input_name,
3439 current_function->symbol);
3444 * Check if all labels are defined in the current function.
3445 * Check if all labels are used in the current function.
3447 static void check_labels(void)
3449 for (const goto_statement_t *goto_statement = goto_first;
3450 goto_statement != NULL;
3451 goto_statement = goto_statement->next) {
3452 declaration_t *label = goto_statement->label;
3455 if (label->source_position.input_name == NULL) {
3456 print_in_function();
3457 errorf(goto_statement->base.source_position,
3458 "label '%Y' used but not defined", label->symbol);
3461 goto_first = goto_last = NULL;
3463 if (warning.unused_label) {
3464 for (const label_statement_t *label_statement = label_first;
3465 label_statement != NULL;
3466 label_statement = label_statement->next) {
3467 const declaration_t *label = label_statement->label;
3469 if (! label->used) {
3470 print_in_function();
3471 warningf(label_statement->base.source_position,
3472 "label '%Y' defined but not used", label->symbol);
3476 label_first = label_last = NULL;
3480 * Check declarations of current_function for unused entities.
3482 static void check_declarations(void)
3484 if (warning.unused_parameter) {
3485 const scope_t *scope = ¤t_function->scope;
3487 const declaration_t *parameter = scope->declarations;
3488 for (; parameter != NULL; parameter = parameter->next) {
3489 if (! parameter->used) {
3490 print_in_function();
3491 warningf(parameter->source_position,
3492 "unused parameter '%Y'", parameter->symbol);
3496 if (warning.unused_variable) {
3500 static void parse_external_declaration(void)
3502 /* function-definitions and declarations both start with declaration
3504 declaration_specifiers_t specifiers;
3505 memset(&specifiers, 0, sizeof(specifiers));
3507 add_anchor_token(';');
3508 parse_declaration_specifiers(&specifiers);
3509 rem_anchor_token(';');
3511 /* must be a declaration */
3512 if(token.type == ';') {
3513 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3517 add_anchor_token(',');
3518 add_anchor_token('=');
3519 rem_anchor_token(';');
3521 /* declarator is common to both function-definitions and declarations */
3522 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3524 rem_anchor_token(',');
3525 rem_anchor_token('=');
3526 rem_anchor_token(';');
3528 /* must be a declaration */
3529 if(token.type == ',' || token.type == '=' || token.type == ';') {
3530 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3534 /* must be a function definition */
3535 parse_kr_declaration_list(ndeclaration);
3537 if(token.type != '{') {
3538 parse_error_expected("while parsing function definition", '{', 0);
3539 eat_until_matching_token(';');
3543 type_t *type = ndeclaration->type;
3545 /* note that we don't skip typerefs: the standard doesn't allow them here
3546 * (so we can't use is_type_function here) */
3547 if(type->kind != TYPE_FUNCTION) {
3548 if (is_type_valid(type)) {
3549 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3550 type, ndeclaration->symbol);
3556 /* § 6.7.5.3 (14) a function definition with () means no
3557 * parameters (and not unspecified parameters) */
3558 if(type->function.unspecified_parameters) {
3559 type_t *duplicate = duplicate_type(type);
3560 duplicate->function.unspecified_parameters = false;
3562 type = typehash_insert(duplicate);
3563 if(type != duplicate) {
3564 obstack_free(type_obst, duplicate);
3566 ndeclaration->type = type;
3569 declaration_t *const declaration = record_function_definition(ndeclaration);
3570 if(ndeclaration != declaration) {
3571 declaration->scope = ndeclaration->scope;
3573 type = skip_typeref(declaration->type);
3575 /* push function parameters and switch scope */
3576 int top = environment_top();
3577 scope_t *last_scope = scope;
3578 set_scope(&declaration->scope);
3580 declaration_t *parameter = declaration->scope.declarations;
3581 for( ; parameter != NULL; parameter = parameter->next) {
3582 if(parameter->parent_scope == &ndeclaration->scope) {
3583 parameter->parent_scope = scope;
3585 assert(parameter->parent_scope == NULL
3586 || parameter->parent_scope == scope);
3587 parameter->parent_scope = scope;
3588 environment_push(parameter);
3591 if(declaration->init.statement != NULL) {
3592 parser_error_multiple_definition(declaration, token.source_position);
3594 goto end_of_parse_external_declaration;
3596 /* parse function body */
3597 int label_stack_top = label_top();
3598 declaration_t *old_current_function = current_function;
3599 current_function = declaration;
3601 declaration->init.statement = parse_compound_statement();
3604 check_declarations();
3606 assert(current_function == declaration);
3607 current_function = old_current_function;
3608 label_pop_to(label_stack_top);
3611 end_of_parse_external_declaration:
3612 assert(scope == &declaration->scope);
3613 set_scope(last_scope);
3614 environment_pop_to(top);
3617 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3618 source_position_t source_position)
3620 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3621 type->bitfield.base = base;
3622 type->bitfield.size = size;
3627 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3630 declaration_t *iter = compound_declaration->scope.declarations;
3631 for( ; iter != NULL; iter = iter->next) {
3632 if(iter->namespc != NAMESPACE_NORMAL)
3635 if(iter->symbol == NULL) {
3636 type_t *type = skip_typeref(iter->type);
3637 if(is_type_compound(type)) {
3638 declaration_t *result
3639 = find_compound_entry(type->compound.declaration, symbol);
3646 if(iter->symbol == symbol) {
3654 static void parse_compound_declarators(declaration_t *struct_declaration,
3655 const declaration_specifiers_t *specifiers)
3657 declaration_t *last_declaration = struct_declaration->scope.declarations;
3658 if(last_declaration != NULL) {
3659 while(last_declaration->next != NULL) {
3660 last_declaration = last_declaration->next;
3665 declaration_t *declaration;
3667 if(token.type == ':') {
3668 source_position_t source_position = HERE;
3671 type_t *base_type = specifiers->type;
3672 expression_t *size = parse_constant_expression();
3674 if(!is_type_integer(skip_typeref(base_type))) {
3675 errorf(HERE, "bitfield base type '%T' is not an integer type",
3679 type_t *type = make_bitfield_type(base_type, size, source_position);
3681 declaration = allocate_declaration_zero();
3682 declaration->namespc = NAMESPACE_NORMAL;
3683 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3684 declaration->storage_class = STORAGE_CLASS_NONE;
3685 declaration->source_position = source_position;
3686 declaration->modifiers = specifiers->decl_modifiers;
3687 declaration->type = type;
3689 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3691 type_t *orig_type = declaration->type;
3692 type_t *type = skip_typeref(orig_type);
3694 if(token.type == ':') {
3695 source_position_t source_position = HERE;
3697 expression_t *size = parse_constant_expression();
3699 if(!is_type_integer(type)) {
3700 errorf(HERE, "bitfield base type '%T' is not an "
3701 "integer type", orig_type);
3704 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3705 declaration->type = bitfield_type;
3707 /* TODO we ignore arrays for now... what is missing is a check
3708 * that they're at the end of the struct */
3709 if(is_type_incomplete(type) && !is_type_array(type)) {
3711 "compound member '%Y' has incomplete type '%T'",
3712 declaration->symbol, orig_type);
3713 } else if(is_type_function(type)) {
3714 errorf(HERE, "compound member '%Y' must not have function "
3715 "type '%T'", declaration->symbol, orig_type);
3720 /* make sure we don't define a symbol multiple times */
3721 symbol_t *symbol = declaration->symbol;
3722 if(symbol != NULL) {
3723 declaration_t *prev_decl
3724 = find_compound_entry(struct_declaration, symbol);
3726 if(prev_decl != NULL) {
3727 assert(prev_decl->symbol == symbol);
3728 errorf(declaration->source_position,
3729 "multiple declarations of symbol '%Y'", symbol);
3730 errorf(prev_decl->source_position,
3731 "previous declaration of '%Y' was here", symbol);
3735 /* append declaration */
3736 if(last_declaration != NULL) {
3737 last_declaration->next = declaration;
3739 struct_declaration->scope.declarations = declaration;
3741 last_declaration = declaration;
3743 if(token.type != ',')
3753 static void parse_compound_type_entries(declaration_t *compound_declaration)
3757 while(token.type != '}' && token.type != T_EOF) {
3758 declaration_specifiers_t specifiers;
3759 memset(&specifiers, 0, sizeof(specifiers));
3760 parse_declaration_specifiers(&specifiers);
3762 parse_compound_declarators(compound_declaration, &specifiers);
3764 if(token.type == T_EOF) {
3765 errorf(HERE, "EOF while parsing struct");
3770 static type_t *parse_typename(void)
3772 declaration_specifiers_t specifiers;
3773 memset(&specifiers, 0, sizeof(specifiers));
3774 parse_declaration_specifiers(&specifiers);
3775 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3776 /* TODO: improve error message, user does probably not know what a
3777 * storage class is...
3779 errorf(HERE, "typename may not have a storage class");
3782 type_t *result = parse_abstract_declarator(specifiers.type);
3790 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3791 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3792 expression_t *left);
3794 typedef struct expression_parser_function_t expression_parser_function_t;
3795 struct expression_parser_function_t {
3796 unsigned precedence;
3797 parse_expression_function parser;
3798 unsigned infix_precedence;
3799 parse_expression_infix_function infix_parser;
3802 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3805 * Creates a new invalid expression.
3807 static expression_t *create_invalid_expression(void)
3809 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3810 expression->base.source_position = token.source_position;
3815 * Prints an error message if an expression was expected but not read
3817 static expression_t *expected_expression_error(void)
3819 /* skip the error message if the error token was read */
3820 if (token.type != T_ERROR) {
3821 errorf(HERE, "expected expression, got token '%K'", &token);
3825 return create_invalid_expression();
3829 * Parse a string constant.
3831 static expression_t *parse_string_const(void)
3834 if (token.type == T_STRING_LITERAL) {
3835 string_t res = token.v.string;
3837 while (token.type == T_STRING_LITERAL) {
3838 res = concat_strings(&res, &token.v.string);
3841 if (token.type != T_WIDE_STRING_LITERAL) {
3842 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3843 /* note: that we use type_char_ptr here, which is already the
3844 * automatic converted type. revert_automatic_type_conversion
3845 * will construct the array type */
3846 cnst->base.type = type_char_ptr;
3847 cnst->string.value = res;
3851 wres = concat_string_wide_string(&res, &token.v.wide_string);
3853 wres = token.v.wide_string;
3858 switch (token.type) {
3859 case T_WIDE_STRING_LITERAL:
3860 wres = concat_wide_strings(&wres, &token.v.wide_string);
3863 case T_STRING_LITERAL:
3864 wres = concat_wide_string_string(&wres, &token.v.string);
3868 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3869 cnst->base.type = type_wchar_t_ptr;
3870 cnst->wide_string.value = wres;
3879 * Parse an integer constant.
3881 static expression_t *parse_int_const(void)
3883 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3884 cnst->base.source_position = HERE;
3885 cnst->base.type = token.datatype;
3886 cnst->conste.v.int_value = token.v.intvalue;
3894 * Parse a character constant.
3896 static expression_t *parse_character_constant(void)
3898 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3900 cnst->base.source_position = HERE;
3901 cnst->base.type = token.datatype;
3902 cnst->conste.v.character = token.v.string;
3904 if (cnst->conste.v.character.size != 1) {
3905 if (warning.multichar && (c_mode & _GNUC)) {
3907 warningf(HERE, "multi-character character constant");
3909 errorf(HERE, "more than 1 characters in character constant");
3918 * Parse a wide character constant.
3920 static expression_t *parse_wide_character_constant(void)
3922 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3924 cnst->base.source_position = HERE;
3925 cnst->base.type = token.datatype;
3926 cnst->conste.v.wide_character = token.v.wide_string;
3928 if (cnst->conste.v.wide_character.size != 1) {
3929 if (warning.multichar && (c_mode & _GNUC)) {
3931 warningf(HERE, "multi-character character constant");
3933 errorf(HERE, "more than 1 characters in character constant");
3942 * Parse a float constant.
3944 static expression_t *parse_float_const(void)
3946 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3947 cnst->base.type = token.datatype;
3948 cnst->conste.v.float_value = token.v.floatvalue;
3955 static declaration_t *create_implicit_function(symbol_t *symbol,
3956 const source_position_t source_position)
3958 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
3959 ntype->function.return_type = type_int;
3960 ntype->function.unspecified_parameters = true;
3962 type_t *type = typehash_insert(ntype);
3967 declaration_t *const declaration = allocate_declaration_zero();
3968 declaration->storage_class = STORAGE_CLASS_EXTERN;
3969 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3970 declaration->type = type;
3971 declaration->symbol = symbol;
3972 declaration->source_position = source_position;
3973 declaration->parent_scope = global_scope;
3975 scope_t *old_scope = scope;
3976 set_scope(global_scope);
3978 environment_push(declaration);
3979 /* prepends the declaration to the global declarations list */
3980 declaration->next = scope->declarations;
3981 scope->declarations = declaration;
3983 assert(scope == global_scope);
3984 set_scope(old_scope);
3990 * Creates a return_type (func)(argument_type) function type if not
3993 * @param return_type the return type
3994 * @param argument_type the argument type
3996 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3998 function_parameter_t *parameter
3999 = obstack_alloc(type_obst, sizeof(parameter[0]));
4000 memset(parameter, 0, sizeof(parameter[0]));
4001 parameter->type = argument_type;
4003 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
4004 type->function.return_type = return_type;
4005 type->function.parameters = parameter;
4007 type_t *result = typehash_insert(type);
4008 if(result != type) {
4016 * Creates a function type for some function like builtins.
4018 * @param symbol the symbol describing the builtin
4020 static type_t *get_builtin_symbol_type(symbol_t *symbol)
4022 switch(symbol->ID) {
4023 case T___builtin_alloca:
4024 return make_function_1_type(type_void_ptr, type_size_t);
4025 case T___builtin_nan:
4026 return make_function_1_type(type_double, type_char_ptr);
4027 case T___builtin_nanf:
4028 return make_function_1_type(type_float, type_char_ptr);
4029 case T___builtin_nand:
4030 return make_function_1_type(type_long_double, type_char_ptr);
4031 case T___builtin_va_end:
4032 return make_function_1_type(type_void, type_valist);
4034 panic("not implemented builtin symbol found");
4039 * Performs automatic type cast as described in § 6.3.2.1.
4041 * @param orig_type the original type
4043 static type_t *automatic_type_conversion(type_t *orig_type)
4045 type_t *type = skip_typeref(orig_type);
4046 if(is_type_array(type)) {
4047 array_type_t *array_type = &type->array;
4048 type_t *element_type = array_type->element_type;
4049 unsigned qualifiers = array_type->type.qualifiers;
4051 return make_pointer_type(element_type, qualifiers);
4054 if(is_type_function(type)) {
4055 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4062 * reverts the automatic casts of array to pointer types and function
4063 * to function-pointer types as defined § 6.3.2.1
4065 type_t *revert_automatic_type_conversion(const expression_t *expression)
4067 switch (expression->kind) {
4068 case EXPR_REFERENCE: return expression->reference.declaration->type;
4069 case EXPR_SELECT: return expression->select.compound_entry->type;
4071 case EXPR_UNARY_DEREFERENCE: {
4072 const expression_t *const value = expression->unary.value;
4073 type_t *const type = skip_typeref(value->base.type);
4074 assert(is_type_pointer(type));
4075 return type->pointer.points_to;
4078 case EXPR_BUILTIN_SYMBOL:
4079 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
4081 case EXPR_ARRAY_ACCESS: {
4082 const expression_t *array_ref = expression->array_access.array_ref;
4083 type_t *type_left = skip_typeref(array_ref->base.type);
4084 if (!is_type_valid(type_left))
4086 assert(is_type_pointer(type_left));
4087 return type_left->pointer.points_to;
4090 case EXPR_STRING_LITERAL: {
4091 size_t size = expression->string.value.size;
4092 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
4095 case EXPR_WIDE_STRING_LITERAL: {
4096 size_t size = expression->wide_string.value.size;
4097 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
4100 case EXPR_COMPOUND_LITERAL:
4101 return expression->compound_literal.type;
4106 return expression->base.type;
4109 static expression_t *parse_reference(void)
4111 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
4113 reference_expression_t *ref = &expression->reference;
4114 ref->symbol = token.v.symbol;
4116 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
4118 source_position_t source_position = token.source_position;
4121 if(declaration == NULL) {
4122 if (! strict_mode && token.type == '(') {
4123 /* an implicitly defined function */
4124 if (warning.implicit_function_declaration) {
4125 warningf(HERE, "implicit declaration of function '%Y'",
4129 declaration = create_implicit_function(ref->symbol,
4132 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
4133 return create_invalid_expression();
4137 type_t *type = declaration->type;
4139 /* we always do the auto-type conversions; the & and sizeof parser contains
4140 * code to revert this! */
4141 type = automatic_type_conversion(type);
4143 ref->declaration = declaration;
4144 ref->base.type = type;
4146 /* this declaration is used */
4147 declaration->used = true;
4152 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
4156 /* TODO check if explicit cast is allowed and issue warnings/errors */
4159 static expression_t *parse_compound_literal(type_t *type)
4161 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
4163 parse_initializer_env_t env;
4165 env.declaration = NULL;
4166 env.must_be_constant = false;
4167 initializer_t *initializer = parse_initializer(&env);
4170 expression->compound_literal.initializer = initializer;
4171 expression->compound_literal.type = type;
4172 expression->base.type = automatic_type_conversion(type);
4178 * Parse a cast expression.
4180 static expression_t *parse_cast(void)
4182 source_position_t source_position = token.source_position;
4184 type_t *type = parse_typename();
4188 if(token.type == '{') {
4189 return parse_compound_literal(type);
4192 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
4193 cast->base.source_position = source_position;
4195 expression_t *value = parse_sub_expression(20);
4197 check_cast_allowed(value, type);
4199 cast->base.type = type;
4200 cast->unary.value = value;
4204 return create_invalid_expression();
4208 * Parse a statement expression.
4210 static expression_t *parse_statement_expression(void)
4212 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
4214 statement_t *statement = parse_compound_statement();
4215 expression->statement.statement = statement;
4216 expression->base.source_position = statement->base.source_position;
4218 /* find last statement and use its type */
4219 type_t *type = type_void;
4220 const statement_t *stmt = statement->compound.statements;
4222 while (stmt->base.next != NULL)
4223 stmt = stmt->base.next;
4225 if (stmt->kind == STATEMENT_EXPRESSION) {
4226 type = stmt->expression.expression->base.type;
4229 warningf(expression->base.source_position, "empty statement expression ({})");
4231 expression->base.type = type;
4237 return create_invalid_expression();
4241 * Parse a braced expression.
4243 static expression_t *parse_brace_expression(void)
4247 switch(token.type) {
4249 /* gcc extension: a statement expression */
4250 return parse_statement_expression();
4254 return parse_cast();
4256 if(is_typedef_symbol(token.v.symbol)) {
4257 return parse_cast();
4261 expression_t *result = parse_expression();
4266 return create_invalid_expression();
4269 static expression_t *parse_function_keyword(void)
4274 if (current_function == NULL) {
4275 errorf(HERE, "'__func__' used outside of a function");
4278 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4279 expression->base.type = type_char_ptr;
4284 static expression_t *parse_pretty_function_keyword(void)
4286 eat(T___PRETTY_FUNCTION__);
4289 if (current_function == NULL) {
4290 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4293 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4294 expression->base.type = type_char_ptr;
4299 static designator_t *parse_designator(void)
4301 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4302 result->source_position = HERE;
4304 if(token.type != T_IDENTIFIER) {
4305 parse_error_expected("while parsing member designator",
4309 result->symbol = token.v.symbol;
4312 designator_t *last_designator = result;
4314 if(token.type == '.') {
4316 if(token.type != T_IDENTIFIER) {
4317 parse_error_expected("while parsing member designator",
4321 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4322 designator->source_position = HERE;
4323 designator->symbol = token.v.symbol;
4326 last_designator->next = designator;
4327 last_designator = designator;
4330 if(token.type == '[') {
4332 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4333 designator->source_position = HERE;
4334 designator->array_index = parse_expression();
4336 if(designator->array_index == NULL) {
4340 last_designator->next = designator;
4341 last_designator = designator;
4353 * Parse the __builtin_offsetof() expression.
4355 static expression_t *parse_offsetof(void)
4357 eat(T___builtin_offsetof);
4359 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4360 expression->base.type = type_size_t;
4363 type_t *type = parse_typename();
4365 designator_t *designator = parse_designator();
4368 expression->offsetofe.type = type;
4369 expression->offsetofe.designator = designator;
4372 memset(&path, 0, sizeof(path));
4373 path.top_type = type;
4374 path.path = NEW_ARR_F(type_path_entry_t, 0);
4376 descend_into_subtype(&path);
4378 if(!walk_designator(&path, designator, true)) {
4379 return create_invalid_expression();
4382 DEL_ARR_F(path.path);
4386 return create_invalid_expression();
4390 * Parses a _builtin_va_start() expression.
4392 static expression_t *parse_va_start(void)
4394 eat(T___builtin_va_start);
4396 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4399 expression->va_starte.ap = parse_assignment_expression();
4401 expression_t *const expr = parse_assignment_expression();
4402 if (expr->kind == EXPR_REFERENCE) {
4403 declaration_t *const decl = expr->reference.declaration;
4405 return create_invalid_expression();
4406 if (decl->parent_scope == ¤t_function->scope &&
4407 decl->next == NULL) {
4408 expression->va_starte.parameter = decl;
4413 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4415 return create_invalid_expression();
4419 * Parses a _builtin_va_arg() expression.
4421 static expression_t *parse_va_arg(void)
4423 eat(T___builtin_va_arg);
4425 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4428 expression->va_arge.ap = parse_assignment_expression();
4430 expression->base.type = parse_typename();
4435 return create_invalid_expression();
4438 static expression_t *parse_builtin_symbol(void)
4440 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4442 symbol_t *symbol = token.v.symbol;
4444 expression->builtin_symbol.symbol = symbol;
4447 type_t *type = get_builtin_symbol_type(symbol);
4448 type = automatic_type_conversion(type);
4450 expression->base.type = type;
4455 * Parses a __builtin_constant() expression.
4457 static expression_t *parse_builtin_constant(void)
4459 eat(T___builtin_constant_p);
4461 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4464 expression->builtin_constant.value = parse_assignment_expression();
4466 expression->base.type = type_int;
4470 return create_invalid_expression();
4474 * Parses a __builtin_prefetch() expression.
4476 static expression_t *parse_builtin_prefetch(void)
4478 eat(T___builtin_prefetch);
4480 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4483 expression->builtin_prefetch.adr = parse_assignment_expression();
4484 if (token.type == ',') {
4486 expression->builtin_prefetch.rw = parse_assignment_expression();
4488 if (token.type == ',') {
4490 expression->builtin_prefetch.locality = parse_assignment_expression();
4493 expression->base.type = type_void;
4497 return create_invalid_expression();
4501 * Parses a __builtin_is_*() compare expression.
4503 static expression_t *parse_compare_builtin(void)
4505 expression_t *expression;
4507 switch(token.type) {
4508 case T___builtin_isgreater:
4509 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4511 case T___builtin_isgreaterequal:
4512 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4514 case T___builtin_isless:
4515 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4517 case T___builtin_islessequal:
4518 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4520 case T___builtin_islessgreater:
4521 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4523 case T___builtin_isunordered:
4524 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4527 panic("invalid compare builtin found");
4530 expression->base.source_position = HERE;
4534 expression->binary.left = parse_assignment_expression();
4536 expression->binary.right = parse_assignment_expression();
4539 type_t *const orig_type_left = expression->binary.left->base.type;
4540 type_t *const orig_type_right = expression->binary.right->base.type;
4542 type_t *const type_left = skip_typeref(orig_type_left);
4543 type_t *const type_right = skip_typeref(orig_type_right);
4544 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4545 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4546 type_error_incompatible("invalid operands in comparison",
4547 expression->base.source_position, orig_type_left, orig_type_right);
4550 semantic_comparison(&expression->binary);
4555 return create_invalid_expression();
4559 * Parses a __builtin_expect() expression.
4561 static expression_t *parse_builtin_expect(void)
4563 eat(T___builtin_expect);
4565 expression_t *expression
4566 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4569 expression->binary.left = parse_assignment_expression();
4571 expression->binary.right = parse_constant_expression();
4574 expression->base.type = expression->binary.left->base.type;
4578 return create_invalid_expression();
4582 * Parses a MS assume() expression.
4584 static expression_t *parse_assume(void) {
4587 expression_t *expression
4588 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4591 expression->unary.value = parse_assignment_expression();
4594 expression->base.type = type_void;
4597 return create_invalid_expression();
4601 * Parses a primary expression.
4603 static expression_t *parse_primary_expression(void)
4605 switch (token.type) {
4606 case T_INTEGER: return parse_int_const();
4607 case T_CHARACTER_CONSTANT: return parse_character_constant();
4608 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4609 case T_FLOATINGPOINT: return parse_float_const();
4610 case T_STRING_LITERAL:
4611 case T_WIDE_STRING_LITERAL: return parse_string_const();
4612 case T_IDENTIFIER: return parse_reference();
4613 case T___FUNCTION__:
4614 case T___func__: return parse_function_keyword();
4615 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4616 case T___builtin_offsetof: return parse_offsetof();
4617 case T___builtin_va_start: return parse_va_start();
4618 case T___builtin_va_arg: return parse_va_arg();
4619 case T___builtin_expect: return parse_builtin_expect();
4620 case T___builtin_alloca:
4621 case T___builtin_nan:
4622 case T___builtin_nand:
4623 case T___builtin_nanf:
4624 case T___builtin_va_end: return parse_builtin_symbol();
4625 case T___builtin_isgreater:
4626 case T___builtin_isgreaterequal:
4627 case T___builtin_isless:
4628 case T___builtin_islessequal:
4629 case T___builtin_islessgreater:
4630 case T___builtin_isunordered: return parse_compare_builtin();
4631 case T___builtin_constant_p: return parse_builtin_constant();
4632 case T___builtin_prefetch: return parse_builtin_prefetch();
4633 case T_assume: return parse_assume();
4635 case '(': return parse_brace_expression();
4638 errorf(HERE, "unexpected token %K, expected an expression", &token);
4639 return create_invalid_expression();
4643 * Check if the expression has the character type and issue a warning then.
4645 static void check_for_char_index_type(const expression_t *expression) {
4646 type_t *const type = expression->base.type;
4647 const type_t *const base_type = skip_typeref(type);
4649 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4650 warning.char_subscripts) {
4651 warningf(expression->base.source_position,
4652 "array subscript has type '%T'", type);
4656 static expression_t *parse_array_expression(unsigned precedence,
4663 expression_t *inside = parse_expression();
4665 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4667 array_access_expression_t *array_access = &expression->array_access;
4669 type_t *const orig_type_left = left->base.type;
4670 type_t *const orig_type_inside = inside->base.type;
4672 type_t *const type_left = skip_typeref(orig_type_left);
4673 type_t *const type_inside = skip_typeref(orig_type_inside);
4675 type_t *return_type;
4676 if (is_type_pointer(type_left)) {
4677 return_type = type_left->pointer.points_to;
4678 array_access->array_ref = left;
4679 array_access->index = inside;
4680 check_for_char_index_type(inside);
4681 } else if (is_type_pointer(type_inside)) {
4682 return_type = type_inside->pointer.points_to;
4683 array_access->array_ref = inside;
4684 array_access->index = left;
4685 array_access->flipped = true;
4686 check_for_char_index_type(left);
4688 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4690 "array access on object with non-pointer types '%T', '%T'",
4691 orig_type_left, orig_type_inside);
4693 return_type = type_error_type;
4694 array_access->array_ref = create_invalid_expression();
4697 if(token.type != ']') {
4698 parse_error_expected("Problem while parsing array access", ']', 0);
4703 return_type = automatic_type_conversion(return_type);
4704 expression->base.type = return_type;
4709 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4711 expression_t *tp_expression = allocate_expression_zero(kind);
4712 tp_expression->base.type = type_size_t;
4714 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4716 tp_expression->typeprop.type = parse_typename();
4719 expression_t *expression = parse_sub_expression(precedence);
4720 expression->base.type = revert_automatic_type_conversion(expression);
4722 tp_expression->typeprop.type = expression->base.type;
4723 tp_expression->typeprop.tp_expression = expression;
4726 return tp_expression;
4728 return create_invalid_expression();
4731 static expression_t *parse_sizeof(unsigned precedence)
4734 return parse_typeprop(EXPR_SIZEOF, precedence);
4737 static expression_t *parse_alignof(unsigned precedence)
4740 return parse_typeprop(EXPR_SIZEOF, precedence);
4743 static expression_t *parse_select_expression(unsigned precedence,
4744 expression_t *compound)
4747 assert(token.type == '.' || token.type == T_MINUSGREATER);
4749 bool is_pointer = (token.type == T_MINUSGREATER);
4752 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4753 select->select.compound = compound;
4755 if(token.type != T_IDENTIFIER) {
4756 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4759 symbol_t *symbol = token.v.symbol;
4760 select->select.symbol = symbol;
4763 type_t *const orig_type = compound->base.type;
4764 type_t *const type = skip_typeref(orig_type);
4766 type_t *type_left = type;
4768 if (!is_type_pointer(type)) {
4769 if (is_type_valid(type)) {
4770 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4772 return create_invalid_expression();
4774 type_left = type->pointer.points_to;
4776 type_left = skip_typeref(type_left);
4778 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4779 type_left->kind != TYPE_COMPOUND_UNION) {
4780 if (is_type_valid(type_left)) {
4781 errorf(HERE, "request for member '%Y' in something not a struct or "
4782 "union, but '%T'", symbol, type_left);
4784 return create_invalid_expression();
4787 declaration_t *const declaration = type_left->compound.declaration;
4789 if(!declaration->init.is_defined) {
4790 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4792 return create_invalid_expression();
4795 declaration_t *iter = find_compound_entry(declaration, symbol);
4797 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4798 return create_invalid_expression();
4801 /* we always do the auto-type conversions; the & and sizeof parser contains
4802 * code to revert this! */
4803 type_t *expression_type = automatic_type_conversion(iter->type);
4805 select->select.compound_entry = iter;
4806 select->base.type = expression_type;
4808 if(expression_type->kind == TYPE_BITFIELD) {
4809 expression_t *extract
4810 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4811 extract->unary.value = select;
4812 extract->base.type = expression_type->bitfield.base;
4821 * Parse a call expression, ie. expression '( ... )'.
4823 * @param expression the function address
4825 static expression_t *parse_call_expression(unsigned precedence,
4826 expression_t *expression)
4829 expression_t *result = allocate_expression_zero(EXPR_CALL);
4831 call_expression_t *call = &result->call;
4832 call->function = expression;
4834 type_t *const orig_type = expression->base.type;
4835 type_t *const type = skip_typeref(orig_type);
4837 function_type_t *function_type = NULL;
4838 if (is_type_pointer(type)) {
4839 type_t *const to_type = skip_typeref(type->pointer.points_to);
4841 if (is_type_function(to_type)) {
4842 function_type = &to_type->function;
4843 call->base.type = function_type->return_type;
4847 if (function_type == NULL && is_type_valid(type)) {
4848 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4851 /* parse arguments */
4854 if(token.type != ')') {
4855 call_argument_t *last_argument = NULL;
4858 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4860 argument->expression = parse_assignment_expression();
4861 if(last_argument == NULL) {
4862 call->arguments = argument;
4864 last_argument->next = argument;
4866 last_argument = argument;
4868 if(token.type != ',')
4875 if(function_type != NULL) {
4876 function_parameter_t *parameter = function_type->parameters;
4877 call_argument_t *argument = call->arguments;
4878 for( ; parameter != NULL && argument != NULL;
4879 parameter = parameter->next, argument = argument->next) {
4880 type_t *expected_type = parameter->type;
4881 /* TODO report scope in error messages */
4882 expression_t *const arg_expr = argument->expression;
4883 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4884 if (res_type == NULL) {
4885 /* TODO improve error message */
4886 errorf(arg_expr->base.source_position,
4887 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4888 arg_expr, arg_expr->base.type, expected_type);
4890 argument->expression = create_implicit_cast(argument->expression, expected_type);
4893 /* too few parameters */
4894 if(parameter != NULL) {
4895 errorf(HERE, "too few arguments to function '%E'", expression);
4896 } else if(argument != NULL) {
4897 /* too many parameters */
4898 if(!function_type->variadic
4899 && !function_type->unspecified_parameters) {
4900 errorf(HERE, "too many arguments to function '%E'", expression);
4902 /* do default promotion */
4903 for( ; argument != NULL; argument = argument->next) {
4904 type_t *type = argument->expression->base.type;
4906 type = skip_typeref(type);
4907 if(is_type_integer(type)) {
4908 type = promote_integer(type);
4909 } else if(type == type_float) {
4913 argument->expression
4914 = create_implicit_cast(argument->expression, type);
4917 check_format(&result->call);
4920 check_format(&result->call);
4926 return create_invalid_expression();
4929 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4931 static bool same_compound_type(const type_t *type1, const type_t *type2)
4934 is_type_compound(type1) &&
4935 type1->kind == type2->kind &&
4936 type1->compound.declaration == type2->compound.declaration;
4940 * Parse a conditional expression, ie. 'expression ? ... : ...'.
4942 * @param expression the conditional expression
4944 static expression_t *parse_conditional_expression(unsigned precedence,
4945 expression_t *expression)
4949 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4951 conditional_expression_t *conditional = &result->conditional;
4952 conditional->condition = expression;
4955 type_t *const condition_type_orig = expression->base.type;
4956 type_t *const condition_type = skip_typeref(condition_type_orig);
4957 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4958 type_error("expected a scalar type in conditional condition",
4959 expression->base.source_position, condition_type_orig);
4962 expression_t *true_expression = parse_expression();
4964 expression_t *false_expression = parse_sub_expression(precedence);
4966 type_t *const orig_true_type = true_expression->base.type;
4967 type_t *const orig_false_type = false_expression->base.type;
4968 type_t *const true_type = skip_typeref(orig_true_type);
4969 type_t *const false_type = skip_typeref(orig_false_type);
4972 type_t *result_type;
4973 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4974 result_type = semantic_arithmetic(true_type, false_type);
4976 true_expression = create_implicit_cast(true_expression, result_type);
4977 false_expression = create_implicit_cast(false_expression, result_type);
4979 conditional->true_expression = true_expression;
4980 conditional->false_expression = false_expression;
4981 conditional->base.type = result_type;
4982 } else if (same_compound_type(true_type, false_type) || (
4983 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4984 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4986 /* just take 1 of the 2 types */
4987 result_type = true_type;
4988 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4989 && pointers_compatible(true_type, false_type)) {
4991 result_type = true_type;
4992 } else if (is_type_pointer(true_type)
4993 && is_null_pointer_constant(false_expression)) {
4994 result_type = true_type;
4995 } else if (is_type_pointer(false_type)
4996 && is_null_pointer_constant(true_expression)) {
4997 result_type = false_type;
4999 /* TODO: one pointer to void*, other some pointer */
5001 if (is_type_valid(true_type) && is_type_valid(false_type)) {
5002 type_error_incompatible("while parsing conditional",
5003 expression->base.source_position, true_type,
5006 result_type = type_error_type;
5009 conditional->true_expression
5010 = create_implicit_cast(true_expression, result_type);
5011 conditional->false_expression
5012 = create_implicit_cast(false_expression, result_type);
5013 conditional->base.type = result_type;
5016 return create_invalid_expression();
5020 * Parse an extension expression.
5022 static expression_t *parse_extension(unsigned precedence)
5024 eat(T___extension__);
5026 /* TODO enable extensions */
5027 expression_t *expression = parse_sub_expression(precedence);
5028 /* TODO disable extensions */
5033 * Parse a __builtin_classify_type() expression.
5035 static expression_t *parse_builtin_classify_type(const unsigned precedence)
5037 eat(T___builtin_classify_type);
5039 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
5040 result->base.type = type_int;
5043 expression_t *expression = parse_sub_expression(precedence);
5045 result->classify_type.type_expression = expression;
5049 return create_invalid_expression();
5052 static void semantic_incdec(unary_expression_t *expression)
5054 type_t *const orig_type = expression->value->base.type;
5055 type_t *const type = skip_typeref(orig_type);
5056 /* TODO !is_type_real && !is_type_pointer */
5057 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
5058 if (is_type_valid(type)) {
5059 /* TODO: improve error message */
5060 errorf(HERE, "operation needs an arithmetic or pointer type");
5065 expression->base.type = orig_type;
5068 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
5070 type_t *const orig_type = expression->value->base.type;
5071 type_t *const type = skip_typeref(orig_type);
5072 if(!is_type_arithmetic(type)) {
5073 if (is_type_valid(type)) {
5074 /* TODO: improve error message */
5075 errorf(HERE, "operation needs an arithmetic type");
5080 expression->base.type = orig_type;
5083 static void semantic_unexpr_scalar(unary_expression_t *expression)
5085 type_t *const orig_type = expression->value->base.type;
5086 type_t *const type = skip_typeref(orig_type);
5087 if (!is_type_scalar(type)) {
5088 if (is_type_valid(type)) {
5089 errorf(HERE, "operand of ! must be of scalar type");
5094 expression->base.type = orig_type;
5097 static void semantic_unexpr_integer(unary_expression_t *expression)
5099 type_t *const orig_type = expression->value->base.type;
5100 type_t *const type = skip_typeref(orig_type);
5101 if (!is_type_integer(type)) {
5102 if (is_type_valid(type)) {
5103 errorf(HERE, "operand of ~ must be of integer type");
5108 expression->base.type = orig_type;
5111 static void semantic_dereference(unary_expression_t *expression)
5113 type_t *const orig_type = expression->value->base.type;
5114 type_t *const type = skip_typeref(orig_type);
5115 if(!is_type_pointer(type)) {
5116 if (is_type_valid(type)) {
5117 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
5122 type_t *result_type = type->pointer.points_to;
5123 result_type = automatic_type_conversion(result_type);
5124 expression->base.type = result_type;
5128 * Check the semantic of the address taken expression.
5130 static void semantic_take_addr(unary_expression_t *expression)
5132 expression_t *value = expression->value;
5133 value->base.type = revert_automatic_type_conversion(value);
5135 type_t *orig_type = value->base.type;
5136 if(!is_type_valid(orig_type))
5139 if(value->kind == EXPR_REFERENCE) {
5140 declaration_t *const declaration = value->reference.declaration;
5141 if(declaration != NULL) {
5142 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
5143 errorf(expression->base.source_position,
5144 "address of register variable '%Y' requested",
5145 declaration->symbol);
5147 declaration->address_taken = 1;
5151 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5154 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
5155 static expression_t *parse_##unexpression_type(unsigned precedence) \
5159 expression_t *unary_expression \
5160 = allocate_expression_zero(unexpression_type); \
5161 unary_expression->base.source_position = HERE; \
5162 unary_expression->unary.value = parse_sub_expression(precedence); \
5164 sfunc(&unary_expression->unary); \
5166 return unary_expression; \
5169 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
5170 semantic_unexpr_arithmetic)
5171 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
5172 semantic_unexpr_arithmetic)
5173 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
5174 semantic_unexpr_scalar)
5175 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
5176 semantic_dereference)
5177 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
5179 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
5180 semantic_unexpr_integer)
5181 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
5183 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
5186 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
5188 static expression_t *parse_##unexpression_type(unsigned precedence, \
5189 expression_t *left) \
5191 (void) precedence; \
5194 expression_t *unary_expression \
5195 = allocate_expression_zero(unexpression_type); \
5196 unary_expression->unary.value = left; \
5198 sfunc(&unary_expression->unary); \
5200 return unary_expression; \
5203 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
5204 EXPR_UNARY_POSTFIX_INCREMENT,
5206 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
5207 EXPR_UNARY_POSTFIX_DECREMENT,
5210 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
5212 /* TODO: handle complex + imaginary types */
5214 /* § 6.3.1.8 Usual arithmetic conversions */
5215 if(type_left == type_long_double || type_right == type_long_double) {
5216 return type_long_double;
5217 } else if(type_left == type_double || type_right == type_double) {
5219 } else if(type_left == type_float || type_right == type_float) {
5223 type_right = promote_integer(type_right);
5224 type_left = promote_integer(type_left);
5226 if(type_left == type_right)
5229 bool signed_left = is_type_signed(type_left);
5230 bool signed_right = is_type_signed(type_right);
5231 int rank_left = get_rank(type_left);
5232 int rank_right = get_rank(type_right);
5233 if(rank_left < rank_right) {
5234 if(signed_left == signed_right || !signed_right) {
5240 if(signed_left == signed_right || !signed_left) {
5249 * Check the semantic restrictions for a binary expression.
5251 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5253 expression_t *const left = expression->left;
5254 expression_t *const right = expression->right;
5255 type_t *const orig_type_left = left->base.type;
5256 type_t *const orig_type_right = right->base.type;
5257 type_t *const type_left = skip_typeref(orig_type_left);
5258 type_t *const type_right = skip_typeref(orig_type_right);
5260 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5261 /* TODO: improve error message */
5262 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5263 errorf(HERE, "operation needs arithmetic types");
5268 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5269 expression->left = create_implicit_cast(left, arithmetic_type);
5270 expression->right = create_implicit_cast(right, arithmetic_type);
5271 expression->base.type = arithmetic_type;
5274 static void semantic_shift_op(binary_expression_t *expression)
5276 expression_t *const left = expression->left;
5277 expression_t *const right = expression->right;
5278 type_t *const orig_type_left = left->base.type;
5279 type_t *const orig_type_right = right->base.type;
5280 type_t * type_left = skip_typeref(orig_type_left);
5281 type_t * type_right = skip_typeref(orig_type_right);
5283 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5284 /* TODO: improve error message */
5285 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5286 errorf(HERE, "operation needs integer types");
5291 type_left = promote_integer(type_left);
5292 type_right = promote_integer(type_right);
5294 expression->left = create_implicit_cast(left, type_left);
5295 expression->right = create_implicit_cast(right, type_right);
5296 expression->base.type = type_left;
5299 static void semantic_add(binary_expression_t *expression)
5301 expression_t *const left = expression->left;
5302 expression_t *const right = expression->right;
5303 type_t *const orig_type_left = left->base.type;
5304 type_t *const orig_type_right = right->base.type;
5305 type_t *const type_left = skip_typeref(orig_type_left);
5306 type_t *const type_right = skip_typeref(orig_type_right);
5309 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5310 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5311 expression->left = create_implicit_cast(left, arithmetic_type);
5312 expression->right = create_implicit_cast(right, arithmetic_type);
5313 expression->base.type = arithmetic_type;
5315 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5316 expression->base.type = type_left;
5317 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5318 expression->base.type = type_right;
5319 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5320 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5324 static void semantic_sub(binary_expression_t *expression)
5326 expression_t *const left = expression->left;
5327 expression_t *const right = expression->right;
5328 type_t *const orig_type_left = left->base.type;
5329 type_t *const orig_type_right = right->base.type;
5330 type_t *const type_left = skip_typeref(orig_type_left);
5331 type_t *const type_right = skip_typeref(orig_type_right);
5334 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5335 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5336 expression->left = create_implicit_cast(left, arithmetic_type);
5337 expression->right = create_implicit_cast(right, arithmetic_type);
5338 expression->base.type = arithmetic_type;
5340 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5341 expression->base.type = type_left;
5342 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5343 if(!pointers_compatible(type_left, type_right)) {
5345 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5346 orig_type_left, orig_type_right);
5348 expression->base.type = type_ptrdiff_t;
5350 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5351 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5352 orig_type_left, orig_type_right);
5357 * Check the semantics of comparison expressions.
5359 * @param expression The expression to check.
5361 static void semantic_comparison(binary_expression_t *expression)
5363 expression_t *left = expression->left;
5364 expression_t *right = expression->right;
5365 type_t *orig_type_left = left->base.type;
5366 type_t *orig_type_right = right->base.type;
5368 type_t *type_left = skip_typeref(orig_type_left);
5369 type_t *type_right = skip_typeref(orig_type_right);
5371 /* TODO non-arithmetic types */
5372 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5373 if (warning.sign_compare &&
5374 (expression->base.kind != EXPR_BINARY_EQUAL &&
5375 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5376 (is_type_signed(type_left) != is_type_signed(type_right))) {
5377 warningf(expression->base.source_position,
5378 "comparison between signed and unsigned");
5380 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5381 expression->left = create_implicit_cast(left, arithmetic_type);
5382 expression->right = create_implicit_cast(right, arithmetic_type);
5383 expression->base.type = arithmetic_type;
5384 if (warning.float_equal &&
5385 (expression->base.kind == EXPR_BINARY_EQUAL ||
5386 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5387 is_type_float(arithmetic_type)) {
5388 warningf(expression->base.source_position,
5389 "comparing floating point with == or != is unsafe");
5391 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5392 /* TODO check compatibility */
5393 } else if (is_type_pointer(type_left)) {
5394 expression->right = create_implicit_cast(right, type_left);
5395 } else if (is_type_pointer(type_right)) {
5396 expression->left = create_implicit_cast(left, type_right);
5397 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5398 type_error_incompatible("invalid operands in comparison",
5399 expression->base.source_position,
5400 type_left, type_right);
5402 expression->base.type = type_int;
5405 static void semantic_arithmetic_assign(binary_expression_t *expression)
5407 expression_t *left = expression->left;
5408 expression_t *right = expression->right;
5409 type_t *orig_type_left = left->base.type;
5410 type_t *orig_type_right = right->base.type;
5412 type_t *type_left = skip_typeref(orig_type_left);
5413 type_t *type_right = skip_typeref(orig_type_right);
5415 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5416 /* TODO: improve error message */
5417 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5418 errorf(HERE, "operation needs arithmetic types");
5423 /* combined instructions are tricky. We can't create an implicit cast on
5424 * the left side, because we need the uncasted form for the store.
5425 * The ast2firm pass has to know that left_type must be right_type
5426 * for the arithmetic operation and create a cast by itself */
5427 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5428 expression->right = create_implicit_cast(right, arithmetic_type);
5429 expression->base.type = type_left;
5432 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5434 expression_t *const left = expression->left;
5435 expression_t *const right = expression->right;
5436 type_t *const orig_type_left = left->base.type;
5437 type_t *const orig_type_right = right->base.type;
5438 type_t *const type_left = skip_typeref(orig_type_left);
5439 type_t *const type_right = skip_typeref(orig_type_right);
5441 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5442 /* combined instructions are tricky. We can't create an implicit cast on
5443 * the left side, because we need the uncasted form for the store.
5444 * The ast2firm pass has to know that left_type must be right_type
5445 * for the arithmetic operation and create a cast by itself */
5446 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5447 expression->right = create_implicit_cast(right, arithmetic_type);
5448 expression->base.type = type_left;
5449 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5450 expression->base.type = type_left;
5451 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5452 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5457 * Check the semantic restrictions of a logical expression.
5459 static void semantic_logical_op(binary_expression_t *expression)
5461 expression_t *const left = expression->left;
5462 expression_t *const right = expression->right;
5463 type_t *const orig_type_left = left->base.type;
5464 type_t *const orig_type_right = right->base.type;
5465 type_t *const type_left = skip_typeref(orig_type_left);
5466 type_t *const type_right = skip_typeref(orig_type_right);
5468 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5469 /* TODO: improve error message */
5470 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5471 errorf(HERE, "operation needs scalar types");
5476 expression->base.type = type_int;
5480 * Checks if a compound type has constant fields.
5482 static bool has_const_fields(const compound_type_t *type)
5484 const scope_t *scope = &type->declaration->scope;
5485 const declaration_t *declaration = scope->declarations;
5487 for (; declaration != NULL; declaration = declaration->next) {
5488 if (declaration->namespc != NAMESPACE_NORMAL)
5491 const type_t *decl_type = skip_typeref(declaration->type);
5492 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5500 * Check the semantic restrictions of a binary assign expression.
5502 static void semantic_binexpr_assign(binary_expression_t *expression)
5504 expression_t *left = expression->left;
5505 type_t *orig_type_left = left->base.type;
5507 type_t *type_left = revert_automatic_type_conversion(left);
5508 type_left = skip_typeref(orig_type_left);
5510 /* must be a modifiable lvalue */
5511 if (is_type_array(type_left)) {
5512 errorf(HERE, "cannot assign to arrays ('%E')", left);
5515 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5516 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5520 if(is_type_incomplete(type_left)) {
5522 "left-hand side of assignment '%E' has incomplete type '%T'",
5523 left, orig_type_left);
5526 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5527 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5528 left, orig_type_left);
5532 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5534 if (res_type == NULL) {
5535 errorf(expression->base.source_position,
5536 "cannot assign to '%T' from '%T'",
5537 orig_type_left, expression->right->base.type);
5539 expression->right = create_implicit_cast(expression->right, res_type);
5542 expression->base.type = orig_type_left;
5546 * Determine if the outermost operation (or parts thereof) of the given
5547 * expression has no effect in order to generate a warning about this fact.
5548 * Therefore in some cases this only examines some of the operands of the
5549 * expression (see comments in the function and examples below).
5551 * f() + 23; // warning, because + has no effect
5552 * x || f(); // no warning, because x controls execution of f()
5553 * x ? y : f(); // warning, because y has no effect
5554 * (void)x; // no warning to be able to suppress the warning
5555 * This function can NOT be used for an "expression has definitely no effect"-
5557 static bool expression_has_effect(const expression_t *const expr)
5559 switch (expr->kind) {
5560 case EXPR_UNKNOWN: break;
5561 case EXPR_INVALID: return true; /* do NOT warn */
5562 case EXPR_REFERENCE: return false;
5563 case EXPR_CONST: return false;
5564 case EXPR_CHARACTER_CONSTANT: return false;
5565 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5566 case EXPR_STRING_LITERAL: return false;
5567 case EXPR_WIDE_STRING_LITERAL: return false;
5570 const call_expression_t *const call = &expr->call;
5571 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5574 switch (call->function->builtin_symbol.symbol->ID) {
5575 case T___builtin_va_end: return true;
5576 default: return false;
5580 /* Generate the warning if either the left or right hand side of a
5581 * conditional expression has no effect */
5582 case EXPR_CONDITIONAL: {
5583 const conditional_expression_t *const cond = &expr->conditional;
5585 expression_has_effect(cond->true_expression) &&
5586 expression_has_effect(cond->false_expression);
5589 case EXPR_SELECT: return false;
5590 case EXPR_ARRAY_ACCESS: return false;
5591 case EXPR_SIZEOF: return false;
5592 case EXPR_CLASSIFY_TYPE: return false;
5593 case EXPR_ALIGNOF: return false;
5595 case EXPR_FUNCTION: return false;
5596 case EXPR_PRETTY_FUNCTION: return false;
5597 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5598 case EXPR_BUILTIN_CONSTANT_P: return false;
5599 case EXPR_BUILTIN_PREFETCH: return true;
5600 case EXPR_OFFSETOF: return false;
5601 case EXPR_VA_START: return true;
5602 case EXPR_VA_ARG: return true;
5603 case EXPR_STATEMENT: return true; // TODO
5604 case EXPR_COMPOUND_LITERAL: return false;
5606 case EXPR_UNARY_NEGATE: return false;
5607 case EXPR_UNARY_PLUS: return false;
5608 case EXPR_UNARY_BITWISE_NEGATE: return false;
5609 case EXPR_UNARY_NOT: return false;
5610 case EXPR_UNARY_DEREFERENCE: return false;
5611 case EXPR_UNARY_TAKE_ADDRESS: return false;
5612 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5613 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5614 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5615 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5617 /* Treat void casts as if they have an effect in order to being able to
5618 * suppress the warning */
5619 case EXPR_UNARY_CAST: {
5620 type_t *const type = skip_typeref(expr->base.type);
5621 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5624 case EXPR_UNARY_CAST_IMPLICIT: return true;
5625 case EXPR_UNARY_ASSUME: return true;
5626 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5628 case EXPR_BINARY_ADD: return false;
5629 case EXPR_BINARY_SUB: return false;
5630 case EXPR_BINARY_MUL: return false;
5631 case EXPR_BINARY_DIV: return false;
5632 case EXPR_BINARY_MOD: return false;
5633 case EXPR_BINARY_EQUAL: return false;
5634 case EXPR_BINARY_NOTEQUAL: return false;
5635 case EXPR_BINARY_LESS: return false;
5636 case EXPR_BINARY_LESSEQUAL: return false;
5637 case EXPR_BINARY_GREATER: return false;
5638 case EXPR_BINARY_GREATEREQUAL: return false;
5639 case EXPR_BINARY_BITWISE_AND: return false;
5640 case EXPR_BINARY_BITWISE_OR: return false;
5641 case EXPR_BINARY_BITWISE_XOR: return false;
5642 case EXPR_BINARY_SHIFTLEFT: return false;
5643 case EXPR_BINARY_SHIFTRIGHT: return false;
5644 case EXPR_BINARY_ASSIGN: return true;
5645 case EXPR_BINARY_MUL_ASSIGN: return true;
5646 case EXPR_BINARY_DIV_ASSIGN: return true;
5647 case EXPR_BINARY_MOD_ASSIGN: return true;
5648 case EXPR_BINARY_ADD_ASSIGN: return true;
5649 case EXPR_BINARY_SUB_ASSIGN: return true;
5650 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5651 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5652 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5653 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5654 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5656 /* Only examine the right hand side of && and ||, because the left hand
5657 * side already has the effect of controlling the execution of the right
5659 case EXPR_BINARY_LOGICAL_AND:
5660 case EXPR_BINARY_LOGICAL_OR:
5661 /* Only examine the right hand side of a comma expression, because the left
5662 * hand side has a separate warning */
5663 case EXPR_BINARY_COMMA:
5664 return expression_has_effect(expr->binary.right);
5666 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5667 case EXPR_BINARY_ISGREATER: return false;
5668 case EXPR_BINARY_ISGREATEREQUAL: return false;
5669 case EXPR_BINARY_ISLESS: return false;
5670 case EXPR_BINARY_ISLESSEQUAL: return false;
5671 case EXPR_BINARY_ISLESSGREATER: return false;
5672 case EXPR_BINARY_ISUNORDERED: return false;
5675 panic("unexpected expression");
5678 static void semantic_comma(binary_expression_t *expression)
5680 if (warning.unused_value) {
5681 const expression_t *const left = expression->left;
5682 if (!expression_has_effect(left)) {
5683 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5686 expression->base.type = expression->right->base.type;
5689 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5690 static expression_t *parse_##binexpression_type(unsigned precedence, \
5691 expression_t *left) \
5694 source_position_t pos = HERE; \
5696 expression_t *right = parse_sub_expression(precedence + lr); \
5698 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5699 binexpr->base.source_position = pos; \
5700 binexpr->binary.left = left; \
5701 binexpr->binary.right = right; \
5702 sfunc(&binexpr->binary); \
5707 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5708 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5709 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5710 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5711 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5712 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5713 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5714 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5715 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5717 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5718 semantic_comparison, 1)
5719 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5720 semantic_comparison, 1)
5721 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5722 semantic_comparison, 1)
5723 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5724 semantic_comparison, 1)
5726 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5727 semantic_binexpr_arithmetic, 1)
5728 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5729 semantic_binexpr_arithmetic, 1)
5730 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5731 semantic_binexpr_arithmetic, 1)
5732 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5733 semantic_logical_op, 1)
5734 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5735 semantic_logical_op, 1)
5736 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5737 semantic_shift_op, 1)
5738 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5739 semantic_shift_op, 1)
5740 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5741 semantic_arithmetic_addsubb_assign, 0)
5742 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5743 semantic_arithmetic_addsubb_assign, 0)
5744 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5745 semantic_arithmetic_assign, 0)
5746 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5747 semantic_arithmetic_assign, 0)
5748 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5749 semantic_arithmetic_assign, 0)
5750 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5751 semantic_arithmetic_assign, 0)
5752 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5753 semantic_arithmetic_assign, 0)
5754 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5755 semantic_arithmetic_assign, 0)
5756 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5757 semantic_arithmetic_assign, 0)
5758 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5759 semantic_arithmetic_assign, 0)
5761 static expression_t *parse_sub_expression(unsigned precedence)
5763 if(token.type < 0) {
5764 return expected_expression_error();
5767 expression_parser_function_t *parser
5768 = &expression_parsers[token.type];
5769 source_position_t source_position = token.source_position;
5772 if(parser->parser != NULL) {
5773 left = parser->parser(parser->precedence);
5775 left = parse_primary_expression();
5777 assert(left != NULL);
5778 left->base.source_position = source_position;
5781 if(token.type < 0) {
5782 return expected_expression_error();
5785 parser = &expression_parsers[token.type];
5786 if(parser->infix_parser == NULL)
5788 if(parser->infix_precedence < precedence)
5791 left = parser->infix_parser(parser->infix_precedence, left);
5793 assert(left != NULL);
5794 assert(left->kind != EXPR_UNKNOWN);
5795 left->base.source_position = source_position;
5802 * Parse an expression.
5804 static expression_t *parse_expression(void)
5806 return parse_sub_expression(1);
5810 * Register a parser for a prefix-like operator with given precedence.
5812 * @param parser the parser function
5813 * @param token_type the token type of the prefix token
5814 * @param precedence the precedence of the operator
5816 static void register_expression_parser(parse_expression_function parser,
5817 int token_type, unsigned precedence)
5819 expression_parser_function_t *entry = &expression_parsers[token_type];
5821 if(entry->parser != NULL) {
5822 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5823 panic("trying to register multiple expression parsers for a token");
5825 entry->parser = parser;
5826 entry->precedence = precedence;
5830 * Register a parser for an infix operator with given precedence.
5832 * @param parser the parser function
5833 * @param token_type the token type of the infix operator
5834 * @param precedence the precedence of the operator
5836 static void register_infix_parser(parse_expression_infix_function parser,
5837 int token_type, unsigned precedence)
5839 expression_parser_function_t *entry = &expression_parsers[token_type];
5841 if(entry->infix_parser != NULL) {
5842 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5843 panic("trying to register multiple infix expression parsers for a "
5846 entry->infix_parser = parser;
5847 entry->infix_precedence = precedence;
5851 * Initialize the expression parsers.
5853 static void init_expression_parsers(void)
5855 memset(&expression_parsers, 0, sizeof(expression_parsers));
5857 register_infix_parser(parse_array_expression, '[', 30);
5858 register_infix_parser(parse_call_expression, '(', 30);
5859 register_infix_parser(parse_select_expression, '.', 30);
5860 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5861 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5863 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5866 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5867 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5868 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5869 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5870 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5871 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5872 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5873 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5874 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5875 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5876 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5877 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5878 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5879 T_EXCLAMATIONMARKEQUAL, 13);
5880 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5881 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5882 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5883 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5884 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5885 register_infix_parser(parse_conditional_expression, '?', 7);
5886 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5887 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5888 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5889 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5890 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5891 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5892 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5893 T_LESSLESSEQUAL, 2);
5894 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5895 T_GREATERGREATEREQUAL, 2);
5896 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5898 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5900 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5903 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5905 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
5906 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
5907 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
5908 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
5909 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
5910 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
5911 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5913 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5915 register_expression_parser(parse_sizeof, T_sizeof, 25);
5916 register_expression_parser(parse_alignof, T___alignof__, 25);
5917 register_expression_parser(parse_extension, T___extension__, 25);
5918 register_expression_parser(parse_builtin_classify_type,
5919 T___builtin_classify_type, 25);
5923 * Parse a asm statement constraints specification.
5925 static asm_constraint_t *parse_asm_constraints(void)
5927 asm_constraint_t *result = NULL;
5928 asm_constraint_t *last = NULL;
5930 while(token.type == T_STRING_LITERAL || token.type == '[') {
5931 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5932 memset(constraint, 0, sizeof(constraint[0]));
5934 if(token.type == '[') {
5936 if(token.type != T_IDENTIFIER) {
5937 parse_error_expected("while parsing asm constraint",
5941 constraint->symbol = token.v.symbol;
5946 constraint->constraints = parse_string_literals();
5948 constraint->expression = parse_expression();
5952 last->next = constraint;
5954 result = constraint;
5958 if(token.type != ',')
5969 * Parse a asm statement clobber specification.
5971 static asm_clobber_t *parse_asm_clobbers(void)
5973 asm_clobber_t *result = NULL;
5974 asm_clobber_t *last = NULL;
5976 while(token.type == T_STRING_LITERAL) {
5977 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5978 clobber->clobber = parse_string_literals();
5981 last->next = clobber;
5987 if(token.type != ',')
5996 * Parse an asm statement.
5998 static statement_t *parse_asm_statement(void)
6002 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
6003 statement->base.source_position = token.source_position;
6005 asm_statement_t *asm_statement = &statement->asms;
6007 if(token.type == T_volatile) {
6009 asm_statement->is_volatile = true;
6013 asm_statement->asm_text = parse_string_literals();
6015 if(token.type != ':')
6019 asm_statement->inputs = parse_asm_constraints();
6020 if(token.type != ':')
6024 asm_statement->outputs = parse_asm_constraints();
6025 if(token.type != ':')
6029 asm_statement->clobbers = parse_asm_clobbers();
6040 * Parse a case statement.
6042 static statement_t *parse_case_statement(void)
6046 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6048 statement->base.source_position = token.source_position;
6049 statement->case_label.expression = parse_expression();
6051 if (c_mode & _GNUC) {
6052 if (token.type == T_DOTDOTDOT) {
6054 statement->case_label.end_range = parse_expression();
6060 if (! is_constant_expression(statement->case_label.expression)) {
6061 errorf(statement->base.source_position,
6062 "case label does not reduce to an integer constant");
6064 /* TODO: check if the case label is already known */
6065 if (current_switch != NULL) {
6066 /* link all cases into the switch statement */
6067 if (current_switch->last_case == NULL) {
6068 current_switch->first_case =
6069 current_switch->last_case = &statement->case_label;
6071 current_switch->last_case->next = &statement->case_label;
6074 errorf(statement->base.source_position,
6075 "case label not within a switch statement");
6078 statement->case_label.statement = parse_statement();
6086 * Finds an existing default label of a switch statement.
6088 static case_label_statement_t *
6089 find_default_label(const switch_statement_t *statement)
6091 case_label_statement_t *label = statement->first_case;
6092 for ( ; label != NULL; label = label->next) {
6093 if (label->expression == NULL)
6100 * Parse a default statement.
6102 static statement_t *parse_default_statement(void)
6106 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
6108 statement->base.source_position = token.source_position;
6111 if (current_switch != NULL) {
6112 const case_label_statement_t *def_label = find_default_label(current_switch);
6113 if (def_label != NULL) {
6114 errorf(HERE, "multiple default labels in one switch");
6115 errorf(def_label->base.source_position,
6116 "this is the first default label");
6118 /* link all cases into the switch statement */
6119 if (current_switch->last_case == NULL) {
6120 current_switch->first_case =
6121 current_switch->last_case = &statement->case_label;
6123 current_switch->last_case->next = &statement->case_label;
6127 errorf(statement->base.source_position,
6128 "'default' label not within a switch statement");
6130 statement->case_label.statement = parse_statement();
6138 * Return the declaration for a given label symbol or create a new one.
6140 static declaration_t *get_label(symbol_t *symbol)
6142 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
6143 assert(current_function != NULL);
6144 /* if we found a label in the same function, then we already created the
6146 if(candidate != NULL
6147 && candidate->parent_scope == ¤t_function->scope) {
6151 /* otherwise we need to create a new one */
6152 declaration_t *const declaration = allocate_declaration_zero();
6153 declaration->namespc = NAMESPACE_LABEL;
6154 declaration->symbol = symbol;
6156 label_push(declaration);
6162 * Parse a label statement.
6164 static statement_t *parse_label_statement(void)
6166 assert(token.type == T_IDENTIFIER);
6167 symbol_t *symbol = token.v.symbol;
6170 declaration_t *label = get_label(symbol);
6172 /* if source position is already set then the label is defined twice,
6173 * otherwise it was just mentioned in a goto so far */
6174 if(label->source_position.input_name != NULL) {
6175 errorf(HERE, "duplicate label '%Y'", symbol);
6176 errorf(label->source_position, "previous definition of '%Y' was here",
6179 label->source_position = token.source_position;
6182 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
6184 statement->base.source_position = token.source_position;
6185 statement->label.label = label;
6189 if(token.type == '}') {
6190 /* TODO only warn? */
6191 errorf(HERE, "label at end of compound statement");
6194 if (token.type == ';') {
6195 /* eat an empty statement here, to avoid the warning about an empty
6196 * after a label. label:; is commonly used to have a label before
6200 statement->label.statement = parse_statement();
6204 /* remember the labels's in a list for later checking */
6205 if (label_last == NULL) {
6206 label_first = &statement->label;
6208 label_last->next = &statement->label;
6210 label_last = &statement->label;
6216 * Parse an if statement.
6218 static statement_t *parse_if(void)
6222 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
6223 statement->base.source_position = token.source_position;
6226 statement->ifs.condition = parse_expression();
6229 add_anchor_token(T_else);
6230 statement->ifs.true_statement = parse_statement();
6231 rem_anchor_token(T_else);
6233 if(token.type == T_else) {
6235 statement->ifs.false_statement = parse_statement();
6244 * Parse a switch statement.
6246 static statement_t *parse_switch(void)
6250 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6251 statement->base.source_position = token.source_position;
6254 expression_t *const expr = parse_expression();
6255 type_t * type = skip_typeref(expr->base.type);
6256 if (is_type_integer(type)) {
6257 type = promote_integer(type);
6258 } else if (is_type_valid(type)) {
6259 errorf(expr->base.source_position,
6260 "switch quantity is not an integer, but '%T'", type);
6261 type = type_error_type;
6263 statement->switchs.expression = create_implicit_cast(expr, type);
6266 switch_statement_t *rem = current_switch;
6267 current_switch = &statement->switchs;
6268 statement->switchs.body = parse_statement();
6269 current_switch = rem;
6271 if (warning.switch_default
6272 && find_default_label(&statement->switchs) == NULL) {
6273 warningf(statement->base.source_position, "switch has no default case");
6281 static statement_t *parse_loop_body(statement_t *const loop)
6283 statement_t *const rem = current_loop;
6284 current_loop = loop;
6286 statement_t *const body = parse_statement();
6293 * Parse a while statement.
6295 static statement_t *parse_while(void)
6299 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6300 statement->base.source_position = token.source_position;
6303 statement->whiles.condition = parse_expression();
6306 statement->whiles.body = parse_loop_body(statement);
6314 * Parse a do statement.
6316 static statement_t *parse_do(void)
6320 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6322 statement->base.source_position = token.source_position;
6324 add_anchor_token(T_while);
6325 statement->do_while.body = parse_loop_body(statement);
6326 rem_anchor_token(T_while);
6330 statement->do_while.condition = parse_expression();
6340 * Parse a for statement.
6342 static statement_t *parse_for(void)
6346 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6347 statement->base.source_position = token.source_position;
6349 int top = environment_top();
6350 scope_t *last_scope = scope;
6351 set_scope(&statement->fors.scope);
6355 if(token.type != ';') {
6356 if(is_declaration_specifier(&token, false)) {
6357 parse_declaration(record_declaration);
6359 expression_t *const init = parse_expression();
6360 statement->fors.initialisation = init;
6361 if (warning.unused_value && !expression_has_effect(init)) {
6362 warningf(init->base.source_position,
6363 "initialisation of 'for'-statement has no effect");
6371 if(token.type != ';') {
6372 statement->fors.condition = parse_expression();
6375 if(token.type != ')') {
6376 expression_t *const step = parse_expression();
6377 statement->fors.step = step;
6378 if (warning.unused_value && !expression_has_effect(step)) {
6379 warningf(step->base.source_position,
6380 "step of 'for'-statement has no effect");
6384 statement->fors.body = parse_loop_body(statement);
6386 assert(scope == &statement->fors.scope);
6387 set_scope(last_scope);
6388 environment_pop_to(top);
6393 assert(scope == &statement->fors.scope);
6394 set_scope(last_scope);
6395 environment_pop_to(top);
6401 * Parse a goto statement.
6403 static statement_t *parse_goto(void)
6407 if(token.type != T_IDENTIFIER) {
6408 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6412 symbol_t *symbol = token.v.symbol;
6415 declaration_t *label = get_label(symbol);
6417 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6418 statement->base.source_position = token.source_position;
6420 statement->gotos.label = label;
6422 /* remember the goto's in a list for later checking */
6423 if (goto_last == NULL) {
6424 goto_first = &statement->gotos;
6426 goto_last->next = &statement->gotos;
6428 goto_last = &statement->gotos;
6438 * Parse a continue statement.
6440 static statement_t *parse_continue(void)
6442 statement_t *statement;
6443 if (current_loop == NULL) {
6444 errorf(HERE, "continue statement not within loop");
6447 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6449 statement->base.source_position = token.source_position;
6461 * Parse a break statement.
6463 static statement_t *parse_break(void)
6465 statement_t *statement;
6466 if (current_switch == NULL && current_loop == NULL) {
6467 errorf(HERE, "break statement not within loop or switch");
6470 statement = allocate_statement_zero(STATEMENT_BREAK);
6472 statement->base.source_position = token.source_position;
6484 * Check if a given declaration represents a local variable.
6486 static bool is_local_var_declaration(const declaration_t *declaration) {
6487 switch ((storage_class_tag_t) declaration->storage_class) {
6488 case STORAGE_CLASS_AUTO:
6489 case STORAGE_CLASS_REGISTER: {
6490 const type_t *type = skip_typeref(declaration->type);
6491 if(is_type_function(type)) {
6503 * Check if a given declaration represents a variable.
6505 static bool is_var_declaration(const declaration_t *declaration) {
6506 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6509 const type_t *type = skip_typeref(declaration->type);
6510 return !is_type_function(type);
6514 * Check if a given expression represents a local variable.
6516 static bool is_local_variable(const expression_t *expression)
6518 if (expression->base.kind != EXPR_REFERENCE) {
6521 const declaration_t *declaration = expression->reference.declaration;
6522 return is_local_var_declaration(declaration);
6526 * Check if a given expression represents a local variable and
6527 * return its declaration then, else return NULL.
6529 declaration_t *expr_is_variable(const expression_t *expression)
6531 if (expression->base.kind != EXPR_REFERENCE) {
6534 declaration_t *declaration = expression->reference.declaration;
6535 if (is_var_declaration(declaration))
6541 * Parse a return statement.
6543 static statement_t *parse_return(void)
6547 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6548 statement->base.source_position = token.source_position;
6550 expression_t *return_value = NULL;
6551 if(token.type != ';') {
6552 return_value = parse_expression();
6556 const type_t *const func_type = current_function->type;
6557 assert(is_type_function(func_type));
6558 type_t *const return_type = skip_typeref(func_type->function.return_type);
6560 if(return_value != NULL) {
6561 type_t *return_value_type = skip_typeref(return_value->base.type);
6563 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6564 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6565 warningf(statement->base.source_position,
6566 "'return' with a value, in function returning void");
6567 return_value = NULL;
6569 type_t *const res_type = semantic_assign(return_type,
6570 return_value, "'return'");
6571 if (res_type == NULL) {
6572 errorf(statement->base.source_position,
6573 "cannot return something of type '%T' in function returning '%T'",
6574 return_value->base.type, return_type);
6576 return_value = create_implicit_cast(return_value, res_type);
6579 /* check for returning address of a local var */
6580 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6581 const expression_t *expression = return_value->unary.value;
6582 if (is_local_variable(expression)) {
6583 warningf(statement->base.source_position,
6584 "function returns address of local variable");
6588 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6589 warningf(statement->base.source_position,
6590 "'return' without value, in function returning non-void");
6593 statement->returns.value = return_value;
6601 * Parse a declaration statement.
6603 static statement_t *parse_declaration_statement(void)
6605 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6607 statement->base.source_position = token.source_position;
6609 declaration_t *before = last_declaration;
6610 parse_declaration(record_declaration);
6612 if(before == NULL) {
6613 statement->declaration.declarations_begin = scope->declarations;
6615 statement->declaration.declarations_begin = before->next;
6617 statement->declaration.declarations_end = last_declaration;
6623 * Parse an expression statement, ie. expr ';'.
6625 static statement_t *parse_expression_statement(void)
6627 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6629 statement->base.source_position = token.source_position;
6630 expression_t *const expr = parse_expression();
6631 statement->expression.expression = expr;
6633 if (warning.unused_value && !expression_has_effect(expr)) {
6634 warningf(expr->base.source_position, "statement has no effect");
6645 * Parse a statement.
6647 static statement_t *parse_statement(void)
6649 statement_t *statement = NULL;
6651 /* declaration or statement */
6652 switch(token.type) {
6654 statement = parse_asm_statement();
6658 statement = parse_case_statement();
6662 statement = parse_default_statement();
6666 statement = parse_compound_statement();
6670 statement = parse_if();
6674 statement = parse_switch();
6678 statement = parse_while();
6682 statement = parse_do();
6686 statement = parse_for();
6690 statement = parse_goto();
6694 statement = parse_continue();
6698 statement = parse_break();
6702 statement = parse_return();
6706 if (warning.empty_statement) {
6707 warningf(HERE, "statement is empty");
6714 if(look_ahead(1)->type == ':') {
6715 statement = parse_label_statement();
6719 if(is_typedef_symbol(token.v.symbol)) {
6720 statement = parse_declaration_statement();
6724 statement = parse_expression_statement();
6727 case T___extension__:
6728 /* this can be a prefix to a declaration or an expression statement */
6729 /* we simply eat it now and parse the rest with tail recursion */
6732 } while(token.type == T___extension__);
6733 statement = parse_statement();
6737 statement = parse_declaration_statement();
6741 statement = parse_expression_statement();
6745 assert(statement == NULL
6746 || statement->base.source_position.input_name != NULL);
6752 * Parse a compound statement.
6754 static statement_t *parse_compound_statement(void)
6756 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6758 statement->base.source_position = token.source_position;
6762 int top = environment_top();
6763 scope_t *last_scope = scope;
6764 set_scope(&statement->compound.scope);
6766 statement_t *last_statement = NULL;
6768 while(token.type != '}' && token.type != T_EOF) {
6769 statement_t *sub_statement = parse_statement();
6770 if(sub_statement == NULL) {
6771 /* an error occurred. if we are at an anchor, return */
6777 if(last_statement != NULL) {
6778 last_statement->base.next = sub_statement;
6780 statement->compound.statements = sub_statement;
6783 while(sub_statement->base.next != NULL)
6784 sub_statement = sub_statement->base.next;
6786 last_statement = sub_statement;
6789 if(token.type == '}') {
6792 errorf(statement->base.source_position,
6793 "end of file while looking for closing '}'");
6797 assert(scope == &statement->compound.scope);
6798 set_scope(last_scope);
6799 environment_pop_to(top);
6805 * Initialize builtin types.
6807 static void initialize_builtin_types(void)
6809 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6810 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6811 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6812 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6813 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6814 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6815 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6816 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6818 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6819 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6820 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6821 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6825 * Check for unused global static functions and variables
6827 static void check_unused_globals(void)
6829 if (!warning.unused_function && !warning.unused_variable)
6832 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6833 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6836 type_t *const type = decl->type;
6838 if (is_type_function(skip_typeref(type))) {
6839 if (!warning.unused_function || decl->is_inline)
6842 s = (decl->init.statement != NULL ? "defined" : "declared");
6844 if (!warning.unused_variable)
6850 warningf(decl->source_position, "'%#T' %s but not used",
6851 type, decl->symbol, s);
6856 * Parse a translation unit.
6858 static translation_unit_t *parse_translation_unit(void)
6860 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6862 assert(global_scope == NULL);
6863 global_scope = &unit->scope;
6865 assert(scope == NULL);
6866 set_scope(&unit->scope);
6868 initialize_builtin_types();
6870 while(token.type != T_EOF) {
6871 if (token.type == ';') {
6872 /* TODO error in strict mode */
6873 warningf(HERE, "stray ';' outside of function");
6876 parse_external_declaration();
6880 assert(scope == &unit->scope);
6882 last_declaration = NULL;
6884 assert(global_scope == &unit->scope);
6885 check_unused_globals();
6886 global_scope = NULL;
6894 * @return the translation unit or NULL if errors occurred.
6896 translation_unit_t *parse(void)
6898 environment_stack = NEW_ARR_F(stack_entry_t, 0);
6899 label_stack = NEW_ARR_F(stack_entry_t, 0);
6900 diagnostic_count = 0;
6904 type_set_output(stderr);
6905 ast_set_output(stderr);
6907 lookahead_bufpos = 0;
6908 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6911 translation_unit_t *unit = parse_translation_unit();
6913 DEL_ARR_F(environment_stack);
6914 DEL_ARR_F(label_stack);
6923 * Initialize the parser.
6925 void init_parser(void)
6928 /* add predefined symbols for extended-decl-modifier */
6929 sym_align = symbol_table_insert("align");
6930 sym_allocate = symbol_table_insert("allocate");
6931 sym_dllimport = symbol_table_insert("dllimport");
6932 sym_dllexport = symbol_table_insert("dllexport");
6933 sym_naked = symbol_table_insert("naked");
6934 sym_noinline = symbol_table_insert("noinline");
6935 sym_noreturn = symbol_table_insert("noreturn");
6936 sym_nothrow = symbol_table_insert("nothrow");
6937 sym_novtable = symbol_table_insert("novtable");
6938 sym_property = symbol_table_insert("property");
6939 sym_get = symbol_table_insert("get");
6940 sym_put = symbol_table_insert("put");
6941 sym_selectany = symbol_table_insert("selectany");
6942 sym_thread = symbol_table_insert("thread");
6943 sym_uuid = symbol_table_insert("uuid");
6944 sym_deprecated = symbol_table_insert("deprecated");
6946 memset(token_anchor_set, 0, sizeof(token_anchor_set));
6948 init_expression_parsers();
6949 obstack_init(&temp_obst);
6951 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6952 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6956 * Terminate the parser.
6958 void exit_parser(void)
6960 obstack_free(&temp_obst, NULL);