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;
56 decl_modifiers_t decl_modifiers;
61 * An environment for parsing initializers (and compound literals).
63 typedef struct parse_initializer_env_t {
64 type_t *type; /**< the type of the initializer. In case of an
65 array type with unspecified size this gets
66 adjusted to the actual size. */
67 declaration_t *declaration; /**< the declaration that is initialized if any */
68 bool must_be_constant;
69 } parse_initializer_env_t;
71 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
74 static token_t lookahead_buffer[MAX_LOOKAHEAD];
75 static int lookahead_bufpos;
76 static stack_entry_t *environment_stack = NULL;
77 static stack_entry_t *label_stack = NULL;
78 static scope_t *global_scope = NULL;
79 static scope_t *scope = NULL;
80 static declaration_t *last_declaration = NULL;
81 static declaration_t *current_function = NULL;
82 static switch_statement_t *current_switch = NULL;
83 static statement_t *current_loop = NULL;
84 static goto_statement_t *goto_first = NULL;
85 static goto_statement_t *goto_last = NULL;
86 static label_statement_t *label_first = NULL;
87 static label_statement_t *label_last = NULL;
88 static struct obstack temp_obst;
90 /** The current source position. */
91 #define HERE token.source_position
93 static type_t *type_valist;
95 static statement_t *parse_compound_statement(void);
96 static statement_t *parse_statement(void);
98 static expression_t *parse_sub_expression(unsigned precedence);
99 static expression_t *parse_expression(void);
100 static type_t *parse_typename(void);
102 static void parse_compound_type_entries(declaration_t *compound_declaration);
103 static declaration_t *parse_declarator(
104 const declaration_specifiers_t *specifiers, bool may_be_abstract);
105 static declaration_t *record_declaration(declaration_t *declaration);
107 static void semantic_comparison(binary_expression_t *expression);
109 #define STORAGE_CLASSES \
116 #define TYPE_QUALIFIERS \
123 #ifdef PROVIDE_COMPLEX
124 #define COMPLEX_SPECIFIERS \
126 #define IMAGINARY_SPECIFIERS \
129 #define COMPLEX_SPECIFIERS
130 #define IMAGINARY_SPECIFIERS
133 #define TYPE_SPECIFIERS \
148 case T___builtin_va_list: \
152 #define DECLARATION_START \
157 #define TYPENAME_START \
162 * Allocate an AST node with given size and
163 * initialize all fields with zero.
165 static void *allocate_ast_zero(size_t size)
167 void *res = allocate_ast(size);
168 memset(res, 0, size);
172 static declaration_t *allocate_declaration_zero(void)
174 declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
175 declaration->type = type_error_type;
180 * Returns the size of a statement node.
182 * @param kind the statement kind
184 static size_t get_statement_struct_size(statement_kind_t kind)
186 static const size_t sizes[] = {
187 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
188 [STATEMENT_RETURN] = sizeof(return_statement_t),
189 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
190 [STATEMENT_IF] = sizeof(if_statement_t),
191 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
192 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
193 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
194 [STATEMENT_BREAK] = sizeof(statement_base_t),
195 [STATEMENT_GOTO] = sizeof(goto_statement_t),
196 [STATEMENT_LABEL] = sizeof(label_statement_t),
197 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
198 [STATEMENT_WHILE] = sizeof(while_statement_t),
199 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
200 [STATEMENT_FOR] = sizeof(for_statement_t),
201 [STATEMENT_ASM] = sizeof(asm_statement_t)
203 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
204 assert(sizes[kind] != 0);
209 * Allocate a statement node of given kind and initialize all
212 static statement_t *allocate_statement_zero(statement_kind_t kind)
214 size_t size = get_statement_struct_size(kind);
215 statement_t *res = allocate_ast_zero(size);
217 res->base.kind = kind;
222 * Returns the size of an expression node.
224 * @param kind the expression kind
226 static size_t get_expression_struct_size(expression_kind_t kind)
228 static const size_t sizes[] = {
229 [EXPR_INVALID] = sizeof(expression_base_t),
230 [EXPR_REFERENCE] = sizeof(reference_expression_t),
231 [EXPR_CONST] = sizeof(const_expression_t),
232 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
233 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
234 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
235 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
236 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
237 [EXPR_CALL] = sizeof(call_expression_t),
238 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
239 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
240 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
241 [EXPR_SELECT] = sizeof(select_expression_t),
242 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
243 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
244 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
245 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
246 [EXPR_FUNCTION] = sizeof(string_literal_expression_t),
247 [EXPR_PRETTY_FUNCTION] = sizeof(string_literal_expression_t),
248 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
249 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
250 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
251 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
252 [EXPR_VA_START] = sizeof(va_start_expression_t),
253 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
254 [EXPR_STATEMENT] = sizeof(statement_expression_t),
256 if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
257 return sizes[EXPR_UNARY_FIRST];
259 if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
260 return sizes[EXPR_BINARY_FIRST];
262 assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
263 assert(sizes[kind] != 0);
268 * Allocate an expression node of given kind and initialize all
271 static expression_t *allocate_expression_zero(expression_kind_t kind)
273 size_t size = get_expression_struct_size(kind);
274 expression_t *res = allocate_ast_zero(size);
276 res->base.kind = kind;
277 res->base.type = type_error_type;
282 * Returns the size of a type node.
284 * @param kind the type kind
286 static size_t get_type_struct_size(type_kind_t kind)
288 static const size_t sizes[] = {
289 [TYPE_ATOMIC] = sizeof(atomic_type_t),
290 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
291 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
292 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
293 [TYPE_ENUM] = sizeof(enum_type_t),
294 [TYPE_FUNCTION] = sizeof(function_type_t),
295 [TYPE_POINTER] = sizeof(pointer_type_t),
296 [TYPE_ARRAY] = sizeof(array_type_t),
297 [TYPE_BUILTIN] = sizeof(builtin_type_t),
298 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
299 [TYPE_TYPEOF] = sizeof(typeof_type_t),
301 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
302 assert(kind <= TYPE_TYPEOF);
303 assert(sizes[kind] != 0);
308 * Allocate a type node of given kind and initialize all
311 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
313 size_t size = get_type_struct_size(kind);
314 type_t *res = obstack_alloc(type_obst, size);
315 memset(res, 0, size);
317 res->base.kind = kind;
318 res->base.source_position = source_position;
323 * Returns the size of an initializer node.
325 * @param kind the initializer kind
327 static size_t get_initializer_size(initializer_kind_t kind)
329 static const size_t sizes[] = {
330 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
331 [INITIALIZER_STRING] = sizeof(initializer_string_t),
332 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
333 [INITIALIZER_LIST] = sizeof(initializer_list_t),
334 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
336 assert(kind < sizeof(sizes) / sizeof(*sizes));
337 assert(sizes[kind] != 0);
342 * Allocate an initializer node of given kind and initialize all
345 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
347 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
354 * Free a type from the type obstack.
356 static void free_type(void *type)
358 obstack_free(type_obst, type);
362 * Returns the index of the top element of the environment stack.
364 static size_t environment_top(void)
366 return ARR_LEN(environment_stack);
370 * Returns the index of the top element of the label stack.
372 static size_t label_top(void)
374 return ARR_LEN(label_stack);
379 * Return the next token.
381 static inline void next_token(void)
383 token = lookahead_buffer[lookahead_bufpos];
384 lookahead_buffer[lookahead_bufpos] = lexer_token;
387 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
390 print_token(stderr, &token);
391 fprintf(stderr, "\n");
396 * Return the next token with a given lookahead.
398 static inline const token_t *look_ahead(int num)
400 assert(num > 0 && num <= MAX_LOOKAHEAD);
401 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
402 return &lookahead_buffer[pos];
405 #define eat(token_type) do { assert(token.type == token_type); next_token(); } while(0)
408 * Report a parse error because an expected token was not found.
410 static void parse_error_expected(const char *message, ...)
412 if(message != NULL) {
413 errorf(HERE, "%s", message);
416 va_start(ap, message);
417 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
422 * Report a type error.
424 static void type_error(const char *msg, const source_position_t source_position,
427 errorf(source_position, "%s, but found type '%T'", msg, type);
431 * Report an incompatible type.
433 static void type_error_incompatible(const char *msg,
434 const source_position_t source_position, type_t *type1, type_t *type2)
436 errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
440 * Eat an complete block, ie. '{ ... }'.
442 static void eat_block(void)
444 if(token.type == '{')
447 while(token.type != '}') {
448 if(token.type == T_EOF)
450 if(token.type == '{') {
460 * Eat a statement until an ';' token.
462 static void eat_statement(void)
464 while(token.type != ';') {
465 if(token.type == T_EOF)
467 if(token.type == '}')
469 if(token.type == '{') {
479 * Eat a parenthesed term, ie. '( ... )'.
481 static void eat_paren(void)
483 if(token.type == '(')
486 while(token.type != ')') {
487 if(token.type == T_EOF)
489 if(token.type == ')' || token.type == ';' || token.type == '}') {
492 if(token.type == ')') {
496 if(token.type == '(') {
500 if(token.type == '{') {
509 * Expect the the current token is the expected token.
510 * If not, generate an error, eat the current statement,
511 * and goto the end_error label.
513 #define expect(expected) \
515 if(UNLIKELY(token.type != (expected))) { \
516 parse_error_expected(NULL, (expected), 0); \
523 #define expect_block(expected) \
525 if(UNLIKELY(token.type != (expected))) { \
526 parse_error_expected(NULL, (expected), 0); \
533 static void set_scope(scope_t *new_scope)
536 scope->last_declaration = last_declaration;
540 last_declaration = new_scope->last_declaration;
544 * Search a symbol in a given namespace and returns its declaration or
545 * NULL if this symbol was not found.
547 static declaration_t *get_declaration(const symbol_t *const symbol,
548 const namespace_t namespc)
550 declaration_t *declaration = symbol->declaration;
551 for( ; declaration != NULL; declaration = declaration->symbol_next) {
552 if(declaration->namespc == namespc)
560 * pushs an environment_entry on the environment stack and links the
561 * corresponding symbol to the new entry
563 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
565 symbol_t *symbol = declaration->symbol;
566 namespace_t namespc = (namespace_t) declaration->namespc;
568 /* replace/add declaration into declaration list of the symbol */
569 declaration_t *iter = symbol->declaration;
571 symbol->declaration = declaration;
573 declaration_t *iter_last = NULL;
574 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
575 /* replace an entry? */
576 if(iter->namespc == namespc) {
577 if(iter_last == NULL) {
578 symbol->declaration = declaration;
580 iter_last->symbol_next = declaration;
582 declaration->symbol_next = iter->symbol_next;
587 assert(iter_last->symbol_next == NULL);
588 iter_last->symbol_next = declaration;
592 /* remember old declaration */
594 entry.symbol = symbol;
595 entry.old_declaration = iter;
596 entry.namespc = (unsigned short) namespc;
597 ARR_APP1(stack_entry_t, *stack_ptr, entry);
600 static void environment_push(declaration_t *declaration)
602 assert(declaration->source_position.input_name != NULL);
603 assert(declaration->parent_scope != NULL);
604 stack_push(&environment_stack, declaration);
607 static void label_push(declaration_t *declaration)
609 declaration->parent_scope = ¤t_function->scope;
610 stack_push(&label_stack, declaration);
614 * pops symbols from the environment stack until @p new_top is the top element
616 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
618 stack_entry_t *stack = *stack_ptr;
619 size_t top = ARR_LEN(stack);
622 assert(new_top <= top);
626 for(i = top; i > new_top; --i) {
627 stack_entry_t *entry = &stack[i - 1];
629 declaration_t *old_declaration = entry->old_declaration;
630 symbol_t *symbol = entry->symbol;
631 namespace_t namespc = (namespace_t)entry->namespc;
633 /* replace/remove declaration */
634 declaration_t *declaration = symbol->declaration;
635 assert(declaration != NULL);
636 if(declaration->namespc == namespc) {
637 if(old_declaration == NULL) {
638 symbol->declaration = declaration->symbol_next;
640 symbol->declaration = old_declaration;
643 declaration_t *iter_last = declaration;
644 declaration_t *iter = declaration->symbol_next;
645 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
646 /* replace an entry? */
647 if(iter->namespc == namespc) {
648 assert(iter_last != NULL);
649 iter_last->symbol_next = old_declaration;
650 if(old_declaration != NULL) {
651 old_declaration->symbol_next = iter->symbol_next;
656 assert(iter != NULL);
660 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
663 static void environment_pop_to(size_t new_top)
665 stack_pop_to(&environment_stack, new_top);
668 static void label_pop_to(size_t new_top)
670 stack_pop_to(&label_stack, new_top);
674 static int get_rank(const type_t *type)
676 assert(!is_typeref(type));
677 /* The C-standard allows promoting to int or unsigned int (see § 7.2.2
678 * and esp. footnote 108). However we can't fold constants (yet), so we
679 * can't decide whether unsigned int is possible, while int always works.
680 * (unsigned int would be preferable when possible... for stuff like
681 * struct { enum { ... } bla : 4; } ) */
682 if(type->kind == TYPE_ENUM)
683 return ATOMIC_TYPE_INT;
685 assert(type->kind == TYPE_ATOMIC);
686 return type->atomic.akind;
689 static type_t *promote_integer(type_t *type)
691 if(type->kind == TYPE_BITFIELD)
692 type = type->bitfield.base;
694 if(get_rank(type) < ATOMIC_TYPE_INT)
701 * Create a cast expression.
703 * @param expression the expression to cast
704 * @param dest_type the destination type
706 static expression_t *create_cast_expression(expression_t *expression,
709 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
711 cast->unary.value = expression;
712 cast->base.type = dest_type;
718 * Check if a given expression represents the 0 pointer constant.
720 static bool is_null_pointer_constant(const expression_t *expression)
722 /* skip void* cast */
723 if(expression->kind == EXPR_UNARY_CAST
724 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
725 expression = expression->unary.value;
728 /* TODO: not correct yet, should be any constant integer expression
729 * which evaluates to 0 */
730 if (expression->kind != EXPR_CONST)
733 type_t *const type = skip_typeref(expression->base.type);
734 if (!is_type_integer(type))
737 return expression->conste.v.int_value == 0;
741 * Create an implicit cast expression.
743 * @param expression the expression to cast
744 * @param dest_type the destination type
746 static expression_t *create_implicit_cast(expression_t *expression,
749 type_t *const source_type = expression->base.type;
751 if (source_type == dest_type)
754 return create_cast_expression(expression, dest_type);
757 /** Implements the rules from § 6.5.16.1 */
758 static type_t *semantic_assign(type_t *orig_type_left,
759 const expression_t *const right,
762 type_t *const orig_type_right = right->base.type;
763 type_t *const type_left = skip_typeref(orig_type_left);
764 type_t *const type_right = skip_typeref(orig_type_right);
766 if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
767 (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
768 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
769 && is_type_pointer(type_right))) {
770 return orig_type_left;
773 if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
774 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
775 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
777 /* the left type has all qualifiers from the right type */
778 unsigned missing_qualifiers
779 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
780 if(missing_qualifiers != 0) {
781 errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
782 return orig_type_left;
785 points_to_left = get_unqualified_type(points_to_left);
786 points_to_right = get_unqualified_type(points_to_right);
788 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
789 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
790 return orig_type_left;
793 if (!types_compatible(points_to_left, points_to_right)) {
794 warningf(right->base.source_position,
795 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
796 orig_type_left, context, right, orig_type_right);
799 return orig_type_left;
802 if ((is_type_compound(type_left) && is_type_compound(type_right))
803 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
804 type_t *const unqual_type_left = get_unqualified_type(type_left);
805 type_t *const unqual_type_right = get_unqualified_type(type_right);
806 if (types_compatible(unqual_type_left, unqual_type_right)) {
807 return orig_type_left;
811 if (!is_type_valid(type_left))
814 if (!is_type_valid(type_right))
815 return orig_type_right;
820 static expression_t *parse_constant_expression(void)
822 /* start parsing at precedence 7 (conditional expression) */
823 expression_t *result = parse_sub_expression(7);
825 if(!is_constant_expression(result)) {
826 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
832 static expression_t *parse_assignment_expression(void)
834 /* start parsing at precedence 2 (assignment expression) */
835 return parse_sub_expression(2);
838 static type_t *make_global_typedef(const char *name, type_t *type)
840 symbol_t *const symbol = symbol_table_insert(name);
842 declaration_t *const declaration = allocate_declaration_zero();
843 declaration->namespc = NAMESPACE_NORMAL;
844 declaration->storage_class = STORAGE_CLASS_TYPEDEF;
845 declaration->declared_storage_class = STORAGE_CLASS_TYPEDEF;
846 declaration->type = type;
847 declaration->symbol = symbol;
848 declaration->source_position = builtin_source_position;
850 record_declaration(declaration);
852 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
853 typedef_type->typedeft.declaration = declaration;
858 static string_t parse_string_literals(void)
860 assert(token.type == T_STRING_LITERAL);
861 string_t result = token.v.string;
865 while (token.type == T_STRING_LITERAL) {
866 result = concat_strings(&result, &token.v.string);
873 static void parse_attributes(void)
877 case T___attribute__: {
885 errorf(HERE, "EOF while parsing attribute");
904 if(token.type != T_STRING_LITERAL) {
905 parse_error_expected("while parsing assembler attribute",
910 parse_string_literals();
915 goto attributes_finished;
924 static designator_t *parse_designation(void)
926 designator_t *result = NULL;
927 designator_t *last = NULL;
930 designator_t *designator;
933 designator = allocate_ast_zero(sizeof(designator[0]));
934 designator->source_position = token.source_position;
936 designator->array_index = parse_constant_expression();
940 designator = allocate_ast_zero(sizeof(designator[0]));
941 designator->source_position = token.source_position;
943 if(token.type != T_IDENTIFIER) {
944 parse_error_expected("while parsing designator",
948 designator->symbol = token.v.symbol;
956 assert(designator != NULL);
958 last->next = designator;
968 static initializer_t *initializer_from_string(array_type_t *type,
969 const string_t *const string)
971 /* TODO: check len vs. size of array type */
974 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
975 initializer->string.string = *string;
980 static initializer_t *initializer_from_wide_string(array_type_t *const type,
981 wide_string_t *const string)
983 /* TODO: check len vs. size of array type */
986 initializer_t *const initializer =
987 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
988 initializer->wide_string.string = *string;
994 * Build an initializer from a given expression.
996 static initializer_t *initializer_from_expression(type_t *orig_type,
997 expression_t *expression)
999 /* TODO check that expression is a constant expression */
1001 /* § 6.7.8.14/15 char array may be initialized by string literals */
1002 type_t *type = skip_typeref(orig_type);
1003 type_t *expr_type_orig = expression->base.type;
1004 type_t *expr_type = skip_typeref(expr_type_orig);
1005 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1006 array_type_t *const array_type = &type->array;
1007 type_t *const element_type = skip_typeref(array_type->element_type);
1009 if (element_type->kind == TYPE_ATOMIC) {
1010 atomic_type_kind_t akind = element_type->atomic.akind;
1011 switch (expression->kind) {
1012 case EXPR_STRING_LITERAL:
1013 if (akind == ATOMIC_TYPE_CHAR
1014 || akind == ATOMIC_TYPE_SCHAR
1015 || akind == ATOMIC_TYPE_UCHAR) {
1016 return initializer_from_string(array_type,
1017 &expression->string.value);
1020 case EXPR_WIDE_STRING_LITERAL: {
1021 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1022 if (get_unqualified_type(element_type) == bare_wchar_type) {
1023 return initializer_from_wide_string(array_type,
1024 &expression->wide_string.value);
1034 type_t *const res_type = semantic_assign(type, expression, "initializer");
1035 if (res_type == NULL)
1038 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1039 result->value.value = create_implicit_cast(expression, res_type);
1045 * Checks if a given expression can be used as an constant initializer.
1047 static bool is_initializer_constant(const expression_t *expression)
1049 return is_constant_expression(expression)
1050 || is_address_constant(expression);
1054 * Parses an scalar initializer.
1056 * § 6.7.8.11; eat {} without warning
1058 static initializer_t *parse_scalar_initializer(type_t *type,
1059 bool must_be_constant)
1061 /* there might be extra {} hierarchies */
1063 while(token.type == '{') {
1066 warningf(HERE, "extra curly braces around scalar initializer");
1071 expression_t *expression = parse_assignment_expression();
1072 if(must_be_constant && !is_initializer_constant(expression)) {
1073 errorf(expression->base.source_position,
1074 "Initialisation expression '%E' is not constant\n",
1078 initializer_t *initializer = initializer_from_expression(type, expression);
1080 if(initializer == NULL) {
1081 errorf(expression->base.source_position,
1082 "expression '%E' doesn't match expected type '%T'",
1088 bool additional_warning_displayed = false;
1090 if(token.type == ',') {
1093 if(token.type != '}') {
1094 if(!additional_warning_displayed) {
1095 warningf(HERE, "additional elements in scalar initializer");
1096 additional_warning_displayed = true;
1107 * An entry in the type path.
1109 typedef struct type_path_entry_t type_path_entry_t;
1110 struct type_path_entry_t {
1111 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1113 size_t index; /**< For array types: the current index. */
1114 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1119 * A type path expression a position inside compound or array types.
1121 typedef struct type_path_t type_path_t;
1122 struct type_path_t {
1123 type_path_entry_t *path; /**< An flexible array containing the current path. */
1124 type_t *top_type; /**< type of the element the path points */
1125 size_t max_index; /**< largest index in outermost array */
1129 * Prints a type path for debugging.
1131 static __attribute__((unused)) void debug_print_type_path(
1132 const type_path_t *path)
1134 size_t len = ARR_LEN(path->path);
1136 for(size_t i = 0; i < len; ++i) {
1137 const type_path_entry_t *entry = & path->path[i];
1139 type_t *type = skip_typeref(entry->type);
1140 if(is_type_compound(type)) {
1141 /* in gcc mode structs can have no members */
1142 if(entry->v.compound_entry == NULL) {
1146 fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1147 } else if(is_type_array(type)) {
1148 fprintf(stderr, "[%u]", entry->v.index);
1150 fprintf(stderr, "-INVALID-");
1153 if(path->top_type != NULL) {
1154 fprintf(stderr, " (");
1155 print_type(path->top_type);
1156 fprintf(stderr, ")");
1161 * Return the top type path entry, ie. in a path
1162 * (type).a.b returns the b.
1164 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1166 size_t len = ARR_LEN(path->path);
1168 return &path->path[len-1];
1172 * Enlarge the type path by an (empty) element.
1174 static type_path_entry_t *append_to_type_path(type_path_t *path)
1176 size_t len = ARR_LEN(path->path);
1177 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1179 type_path_entry_t *result = & path->path[len];
1180 memset(result, 0, sizeof(result[0]));
1185 * Descending into a sub-type. Enter the scope of the current
1188 static void descend_into_subtype(type_path_t *path)
1190 type_t *orig_top_type = path->top_type;
1191 type_t *top_type = skip_typeref(orig_top_type);
1193 assert(is_type_compound(top_type) || is_type_array(top_type));
1195 type_path_entry_t *top = append_to_type_path(path);
1196 top->type = top_type;
1198 if(is_type_compound(top_type)) {
1199 declaration_t *declaration = top_type->compound.declaration;
1200 declaration_t *entry = declaration->scope.declarations;
1201 top->v.compound_entry = entry;
1204 path->top_type = entry->type;
1206 path->top_type = NULL;
1209 assert(is_type_array(top_type));
1212 path->top_type = top_type->array.element_type;
1217 * Pop an entry from the given type path, ie. returning from
1218 * (type).a.b to (type).a
1220 static void ascend_from_subtype(type_path_t *path)
1222 type_path_entry_t *top = get_type_path_top(path);
1224 path->top_type = top->type;
1226 size_t len = ARR_LEN(path->path);
1227 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1231 * Pop entries from the given type path until the given
1232 * path level is reached.
1234 static void ascend_to(type_path_t *path, size_t top_path_level)
1236 size_t len = ARR_LEN(path->path);
1238 while(len > top_path_level) {
1239 ascend_from_subtype(path);
1240 len = ARR_LEN(path->path);
1244 static bool walk_designator(type_path_t *path, const designator_t *designator,
1245 bool used_in_offsetof)
1247 for( ; designator != NULL; designator = designator->next) {
1248 type_path_entry_t *top = get_type_path_top(path);
1249 type_t *orig_type = top->type;
1251 type_t *type = skip_typeref(orig_type);
1253 if(designator->symbol != NULL) {
1254 symbol_t *symbol = designator->symbol;
1255 if(!is_type_compound(type)) {
1256 if(is_type_valid(type)) {
1257 errorf(designator->source_position,
1258 "'.%Y' designator used for non-compound type '%T'",
1264 declaration_t *declaration = type->compound.declaration;
1265 declaration_t *iter = declaration->scope.declarations;
1266 for( ; iter != NULL; iter = iter->next) {
1267 if(iter->symbol == symbol) {
1272 errorf(designator->source_position,
1273 "'%T' has no member named '%Y'", orig_type, symbol);
1276 if(used_in_offsetof) {
1277 type_t *real_type = skip_typeref(iter->type);
1278 if(real_type->kind == TYPE_BITFIELD) {
1279 errorf(designator->source_position,
1280 "offsetof designator '%Y' may not specify bitfield",
1286 top->type = orig_type;
1287 top->v.compound_entry = iter;
1288 orig_type = iter->type;
1290 expression_t *array_index = designator->array_index;
1291 assert(designator->array_index != NULL);
1293 if(!is_type_array(type)) {
1294 if(is_type_valid(type)) {
1295 errorf(designator->source_position,
1296 "[%E] designator used for non-array type '%T'",
1297 array_index, orig_type);
1301 if(!is_type_valid(array_index->base.type)) {
1305 long index = fold_constant(array_index);
1306 if(!used_in_offsetof) {
1308 errorf(designator->source_position,
1309 "array index [%E] must be positive", array_index);
1312 if(type->array.size_constant == true) {
1313 long array_size = type->array.size;
1314 if(index >= array_size) {
1315 errorf(designator->source_position,
1316 "designator [%E] (%d) exceeds array size %d",
1317 array_index, index, array_size);
1323 top->type = orig_type;
1324 top->v.index = (size_t) index;
1325 orig_type = type->array.element_type;
1327 path->top_type = orig_type;
1329 if(designator->next != NULL) {
1330 descend_into_subtype(path);
1339 static void advance_current_object(type_path_t *path, size_t top_path_level)
1341 type_path_entry_t *top = get_type_path_top(path);
1343 type_t *type = skip_typeref(top->type);
1344 if(is_type_union(type)) {
1345 /* in unions only the first element is initialized */
1346 top->v.compound_entry = NULL;
1347 } else if(is_type_struct(type)) {
1348 declaration_t *entry = top->v.compound_entry;
1350 entry = entry->next;
1351 top->v.compound_entry = entry;
1353 path->top_type = entry->type;
1357 assert(is_type_array(type));
1361 if(!type->array.size_constant || top->v.index < type->array.size) {
1366 /* we're past the last member of the current sub-aggregate, try if we
1367 * can ascend in the type hierarchy and continue with another subobject */
1368 size_t len = ARR_LEN(path->path);
1370 if(len > top_path_level) {
1371 ascend_from_subtype(path);
1372 advance_current_object(path, top_path_level);
1374 path->top_type = NULL;
1379 * skip any {...} blocks until a closing braket is reached.
1381 static void skip_initializers(void)
1383 if(token.type == '{')
1386 while(token.type != '}') {
1387 if(token.type == T_EOF)
1389 if(token.type == '{') {
1398 * Parse a part of an initialiser for a struct or union,
1400 static initializer_t *parse_sub_initializer(type_path_t *path,
1401 type_t *outer_type, size_t top_path_level,
1402 parse_initializer_env_t *env)
1404 if(token.type == '}') {
1405 /* empty initializer */
1409 type_t *orig_type = path->top_type;
1410 type_t *type = NULL;
1412 if (orig_type == NULL) {
1413 /* We are initializing an empty compound. */
1415 type = skip_typeref(orig_type);
1417 /* we can't do usefull stuff if we didn't even parse the type. Skip the
1418 * initializers in this case. */
1419 if(!is_type_valid(type)) {
1420 skip_initializers();
1425 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1428 designator_t *designator = NULL;
1429 if(token.type == '.' || token.type == '[') {
1430 designator = parse_designation();
1432 /* reset path to toplevel, evaluate designator from there */
1433 ascend_to(path, top_path_level);
1434 if(!walk_designator(path, designator, false)) {
1435 /* can't continue after designation error */
1439 initializer_t *designator_initializer
1440 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1441 designator_initializer->designator.designator = designator;
1442 ARR_APP1(initializer_t*, initializers, designator_initializer);
1447 if(token.type == '{') {
1448 if(type != NULL && is_type_scalar(type)) {
1449 sub = parse_scalar_initializer(type, env->must_be_constant);
1453 if (env->declaration != NULL)
1454 errorf(HERE, "extra brace group at end of initializer for '%Y'",
1455 env->declaration->symbol);
1457 errorf(HERE, "extra brace group at end of initializer");
1459 descend_into_subtype(path);
1461 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1465 ascend_from_subtype(path);
1469 goto error_parse_next;
1473 /* must be an expression */
1474 expression_t *expression = parse_assignment_expression();
1476 if(env->must_be_constant && !is_initializer_constant(expression)) {
1477 errorf(expression->base.source_position,
1478 "Initialisation expression '%E' is not constant\n",
1483 /* we are already outside, ... */
1487 /* handle { "string" } special case */
1488 if((expression->kind == EXPR_STRING_LITERAL
1489 || expression->kind == EXPR_WIDE_STRING_LITERAL)
1490 && outer_type != NULL) {
1491 sub = initializer_from_expression(outer_type, expression);
1493 if(token.type == ',') {
1496 if(token.type != '}') {
1497 warningf(HERE, "excessive elements in initializer for type '%T'",
1500 /* TODO: eat , ... */
1505 /* descend into subtypes until expression matches type */
1507 orig_type = path->top_type;
1508 type = skip_typeref(orig_type);
1510 sub = initializer_from_expression(orig_type, expression);
1514 if(!is_type_valid(type)) {
1517 if(is_type_scalar(type)) {
1518 errorf(expression->base.source_position,
1519 "expression '%E' doesn't match expected type '%T'",
1520 expression, orig_type);
1524 descend_into_subtype(path);
1528 /* update largest index of top array */
1529 const type_path_entry_t *first = &path->path[0];
1530 type_t *first_type = first->type;
1531 first_type = skip_typeref(first_type);
1532 if(is_type_array(first_type)) {
1533 size_t index = first->v.index;
1534 if(index > path->max_index)
1535 path->max_index = index;
1539 /* append to initializers list */
1540 ARR_APP1(initializer_t*, initializers, sub);
1543 if(env->declaration != NULL)
1544 warningf(HERE, "excess elements in struct initializer for '%Y'",
1545 env->declaration->symbol);
1547 warningf(HERE, "excess elements in struct initializer");
1551 if(token.type == '}') {
1555 if(token.type == '}') {
1560 /* advance to the next declaration if we are not at the end */
1561 advance_current_object(path, top_path_level);
1562 orig_type = path->top_type;
1563 if(orig_type != NULL)
1564 type = skip_typeref(orig_type);
1570 size_t len = ARR_LEN(initializers);
1571 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1572 initializer_t *result = allocate_ast_zero(size);
1573 result->kind = INITIALIZER_LIST;
1574 result->list.len = len;
1575 memcpy(&result->list.initializers, initializers,
1576 len * sizeof(initializers[0]));
1578 DEL_ARR_F(initializers);
1579 ascend_to(path, top_path_level);
1584 skip_initializers();
1585 DEL_ARR_F(initializers);
1586 ascend_to(path, top_path_level);
1591 * Parses an initializer. Parsers either a compound literal
1592 * (env->declaration == NULL) or an initializer of a declaration.
1594 static initializer_t *parse_initializer(parse_initializer_env_t *env)
1596 type_t *type = skip_typeref(env->type);
1597 initializer_t *result = NULL;
1600 if(is_type_scalar(type)) {
1601 result = parse_scalar_initializer(type, env->must_be_constant);
1602 } else if(token.type == '{') {
1606 memset(&path, 0, sizeof(path));
1607 path.top_type = env->type;
1608 path.path = NEW_ARR_F(type_path_entry_t, 0);
1610 descend_into_subtype(&path);
1612 result = parse_sub_initializer(&path, env->type, 1, env);
1614 max_index = path.max_index;
1615 DEL_ARR_F(path.path);
1619 /* parse_scalar_initializer() also works in this case: we simply
1620 * have an expression without {} around it */
1621 result = parse_scalar_initializer(type, env->must_be_constant);
1624 /* § 6.7.5 (22) array initializers for arrays with unknown size determine
1625 * the array type size */
1626 if(is_type_array(type) && type->array.size_expression == NULL
1627 && result != NULL) {
1629 switch (result->kind) {
1630 case INITIALIZER_LIST:
1631 size = max_index + 1;
1634 case INITIALIZER_STRING:
1635 size = result->string.string.size;
1638 case INITIALIZER_WIDE_STRING:
1639 size = result->wide_string.string.size;
1643 panic("invalid initializer type");
1646 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
1647 cnst->base.type = type_size_t;
1648 cnst->conste.v.int_value = size;
1650 type_t *new_type = duplicate_type(type);
1652 new_type->array.size_expression = cnst;
1653 new_type->array.size_constant = true;
1654 new_type->array.size = size;
1655 env->type = new_type;
1663 static declaration_t *append_declaration(declaration_t *declaration);
1665 static declaration_t *parse_compound_type_specifier(bool is_struct)
1673 symbol_t *symbol = NULL;
1674 declaration_t *declaration = NULL;
1676 if (token.type == T___attribute__) {
1681 if(token.type == T_IDENTIFIER) {
1682 symbol = token.v.symbol;
1686 declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1688 declaration = get_declaration(symbol, NAMESPACE_UNION);
1690 } else if(token.type != '{') {
1692 parse_error_expected("while parsing struct type specifier",
1693 T_IDENTIFIER, '{', 0);
1695 parse_error_expected("while parsing union type specifier",
1696 T_IDENTIFIER, '{', 0);
1702 if(declaration == NULL) {
1703 declaration = allocate_declaration_zero();
1704 declaration->namespc =
1705 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1706 declaration->source_position = token.source_position;
1707 declaration->symbol = symbol;
1708 declaration->parent_scope = scope;
1709 if (symbol != NULL) {
1710 environment_push(declaration);
1712 append_declaration(declaration);
1715 if(token.type == '{') {
1716 if(declaration->init.is_defined) {
1717 assert(symbol != NULL);
1718 errorf(HERE, "multiple definitions of '%s %Y'",
1719 is_struct ? "struct" : "union", symbol);
1720 declaration->scope.declarations = NULL;
1722 declaration->init.is_defined = true;
1724 parse_compound_type_entries(declaration);
1731 static void parse_enum_entries(type_t *const enum_type)
1735 if(token.type == '}') {
1737 errorf(HERE, "empty enum not allowed");
1742 if(token.type != T_IDENTIFIER) {
1743 parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1748 declaration_t *const entry = allocate_declaration_zero();
1749 entry->storage_class = STORAGE_CLASS_ENUM_ENTRY;
1750 entry->type = enum_type;
1751 entry->symbol = token.v.symbol;
1752 entry->source_position = token.source_position;
1755 if(token.type == '=') {
1757 expression_t *value = parse_constant_expression();
1759 value = create_implicit_cast(value, enum_type);
1760 entry->init.enum_value = value;
1765 record_declaration(entry);
1767 if(token.type != ',')
1770 } while(token.type != '}');
1778 static type_t *parse_enum_specifier(void)
1782 declaration_t *declaration;
1785 if(token.type == T_IDENTIFIER) {
1786 symbol = token.v.symbol;
1789 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1790 } else if(token.type != '{') {
1791 parse_error_expected("while parsing enum type specifier",
1792 T_IDENTIFIER, '{', 0);
1799 if(declaration == NULL) {
1800 declaration = allocate_declaration_zero();
1801 declaration->namespc = NAMESPACE_ENUM;
1802 declaration->source_position = token.source_position;
1803 declaration->symbol = symbol;
1804 declaration->parent_scope = scope;
1807 type_t *const type = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1808 type->enumt.declaration = declaration;
1810 if(token.type == '{') {
1811 if(declaration->init.is_defined) {
1812 errorf(HERE, "multiple definitions of enum %Y", symbol);
1814 if (symbol != NULL) {
1815 environment_push(declaration);
1817 append_declaration(declaration);
1818 declaration->init.is_defined = 1;
1820 parse_enum_entries(type);
1828 * if a symbol is a typedef to another type, return true
1830 static bool is_typedef_symbol(symbol_t *symbol)
1832 const declaration_t *const declaration =
1833 get_declaration(symbol, NAMESPACE_NORMAL);
1835 declaration != NULL &&
1836 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1839 static type_t *parse_typeof(void)
1847 expression_t *expression = NULL;
1850 switch(token.type) {
1851 case T___extension__:
1852 /* this can be a prefix to a typename or an expression */
1853 /* we simply eat it now. */
1856 } while(token.type == T___extension__);
1860 if(is_typedef_symbol(token.v.symbol)) {
1861 type = parse_typename();
1863 expression = parse_expression();
1864 type = expression->base.type;
1869 type = parse_typename();
1873 expression = parse_expression();
1874 type = expression->base.type;
1880 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1881 typeof_type->typeoft.expression = expression;
1882 typeof_type->typeoft.typeof_type = type;
1890 SPECIFIER_SIGNED = 1 << 0,
1891 SPECIFIER_UNSIGNED = 1 << 1,
1892 SPECIFIER_LONG = 1 << 2,
1893 SPECIFIER_INT = 1 << 3,
1894 SPECIFIER_DOUBLE = 1 << 4,
1895 SPECIFIER_CHAR = 1 << 5,
1896 SPECIFIER_SHORT = 1 << 6,
1897 SPECIFIER_LONG_LONG = 1 << 7,
1898 SPECIFIER_FLOAT = 1 << 8,
1899 SPECIFIER_BOOL = 1 << 9,
1900 SPECIFIER_VOID = 1 << 10,
1901 #ifdef PROVIDE_COMPLEX
1902 SPECIFIER_COMPLEX = 1 << 11,
1903 SPECIFIER_IMAGINARY = 1 << 12,
1907 static type_t *create_builtin_type(symbol_t *const symbol,
1908 type_t *const real_type)
1910 type_t *type = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1911 type->builtin.symbol = symbol;
1912 type->builtin.real_type = real_type;
1914 type_t *result = typehash_insert(type);
1915 if (type != result) {
1922 static type_t *get_typedef_type(symbol_t *symbol)
1924 declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1925 if(declaration == NULL
1926 || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1929 type_t *type = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1930 type->typedeft.declaration = declaration;
1935 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1937 type_t *type = NULL;
1938 unsigned type_qualifiers = 0;
1939 unsigned type_specifiers = 0;
1942 specifiers->source_position = token.source_position;
1945 switch(token.type) {
1948 #define MATCH_STORAGE_CLASS(token, class) \
1950 if(specifiers->declared_storage_class != STORAGE_CLASS_NONE) { \
1951 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1953 specifiers->declared_storage_class = class; \
1957 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
1958 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
1959 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
1960 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
1961 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1964 switch (specifiers->declared_storage_class) {
1965 case STORAGE_CLASS_NONE:
1966 specifiers->declared_storage_class = STORAGE_CLASS_THREAD;
1969 case STORAGE_CLASS_EXTERN:
1970 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_EXTERN;
1973 case STORAGE_CLASS_STATIC:
1974 specifiers->declared_storage_class = STORAGE_CLASS_THREAD_STATIC;
1978 errorf(HERE, "multiple storage classes in declaration specifiers");
1984 /* type qualifiers */
1985 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
1987 type_qualifiers |= qualifier; \
1991 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
1992 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1993 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1995 case T___extension__:
2000 /* type specifiers */
2001 #define MATCH_SPECIFIER(token, specifier, name) \
2004 if(type_specifiers & specifier) { \
2005 errorf(HERE, "multiple " name " type specifiers given"); \
2007 type_specifiers |= specifier; \
2011 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void")
2012 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char")
2013 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short")
2014 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int")
2015 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float")
2016 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double")
2017 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed")
2018 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned")
2019 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool")
2020 #ifdef PROVIDE_COMPLEX
2021 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex")
2022 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
2025 /* only in microsoft mode */
2026 specifiers->decl_modifiers |= DM_FORCEINLINE;
2030 specifiers->is_inline = true;
2035 if(type_specifiers & SPECIFIER_LONG_LONG) {
2036 errorf(HERE, "multiple type specifiers given");
2037 } else if(type_specifiers & SPECIFIER_LONG) {
2038 type_specifiers |= SPECIFIER_LONG_LONG;
2040 type_specifiers |= SPECIFIER_LONG;
2045 type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
2047 type->compound.declaration = parse_compound_type_specifier(true);
2051 type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
2053 type->compound.declaration = parse_compound_type_specifier(false);
2057 type = parse_enum_specifier();
2060 type = parse_typeof();
2062 case T___builtin_va_list:
2063 type = duplicate_type(type_valist);
2067 case T___attribute__:
2071 case T_IDENTIFIER: {
2072 /* only parse identifier if we haven't found a type yet */
2073 if(type != NULL || type_specifiers != 0)
2074 goto finish_specifiers;
2076 type_t *typedef_type = get_typedef_type(token.v.symbol);
2078 if(typedef_type == NULL)
2079 goto finish_specifiers;
2082 type = typedef_type;
2086 /* function specifier */
2088 goto finish_specifiers;
2095 atomic_type_kind_t atomic_type;
2097 /* match valid basic types */
2098 switch(type_specifiers) {
2099 case SPECIFIER_VOID:
2100 atomic_type = ATOMIC_TYPE_VOID;
2102 case SPECIFIER_CHAR:
2103 atomic_type = ATOMIC_TYPE_CHAR;
2105 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2106 atomic_type = ATOMIC_TYPE_SCHAR;
2108 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2109 atomic_type = ATOMIC_TYPE_UCHAR;
2111 case SPECIFIER_SHORT:
2112 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2113 case SPECIFIER_SHORT | SPECIFIER_INT:
2114 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2115 atomic_type = ATOMIC_TYPE_SHORT;
2117 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2118 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2119 atomic_type = ATOMIC_TYPE_USHORT;
2122 case SPECIFIER_SIGNED:
2123 case SPECIFIER_SIGNED | SPECIFIER_INT:
2124 atomic_type = ATOMIC_TYPE_INT;
2126 case SPECIFIER_UNSIGNED:
2127 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2128 atomic_type = ATOMIC_TYPE_UINT;
2130 case SPECIFIER_LONG:
2131 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2132 case SPECIFIER_LONG | SPECIFIER_INT:
2133 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2134 atomic_type = ATOMIC_TYPE_LONG;
2136 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2137 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2138 atomic_type = ATOMIC_TYPE_ULONG;
2140 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2141 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2142 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2143 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2145 atomic_type = ATOMIC_TYPE_LONGLONG;
2147 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2148 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2150 atomic_type = ATOMIC_TYPE_ULONGLONG;
2152 case SPECIFIER_FLOAT:
2153 atomic_type = ATOMIC_TYPE_FLOAT;
2155 case SPECIFIER_DOUBLE:
2156 atomic_type = ATOMIC_TYPE_DOUBLE;
2158 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2159 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2161 case SPECIFIER_BOOL:
2162 atomic_type = ATOMIC_TYPE_BOOL;
2164 #ifdef PROVIDE_COMPLEX
2165 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2166 atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2168 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2169 atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2171 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2172 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2174 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2175 atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2177 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2178 atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2180 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2181 atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2185 /* invalid specifier combination, give an error message */
2186 if(type_specifiers == 0) {
2187 if (! strict_mode) {
2188 if (warning.implicit_int) {
2189 warningf(HERE, "no type specifiers in declaration, using 'int'");
2191 atomic_type = ATOMIC_TYPE_INT;
2194 errorf(HERE, "no type specifiers given in declaration");
2196 } else if((type_specifiers & SPECIFIER_SIGNED) &&
2197 (type_specifiers & SPECIFIER_UNSIGNED)) {
2198 errorf(HERE, "signed and unsigned specifiers gives");
2199 } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2200 errorf(HERE, "only integer types can be signed or unsigned");
2202 errorf(HERE, "multiple datatypes in declaration");
2204 atomic_type = ATOMIC_TYPE_INVALID;
2207 type = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2208 type->atomic.akind = atomic_type;
2211 if(type_specifiers != 0) {
2212 errorf(HERE, "multiple datatypes in declaration");
2216 type->base.qualifiers = type_qualifiers;
2218 type_t *result = typehash_insert(type);
2219 if(newtype && result != type) {
2223 specifiers->type = result;
2226 static type_qualifiers_t parse_type_qualifiers(void)
2228 type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2231 switch(token.type) {
2232 /* type qualifiers */
2233 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2234 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2235 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2238 return type_qualifiers;
2243 static declaration_t *parse_identifier_list(void)
2245 declaration_t *declarations = NULL;
2246 declaration_t *last_declaration = NULL;
2248 declaration_t *const declaration = allocate_declaration_zero();
2249 declaration->type = NULL; /* a K&R parameter list has no types, yet */
2250 declaration->source_position = token.source_position;
2251 declaration->symbol = token.v.symbol;
2254 if(last_declaration != NULL) {
2255 last_declaration->next = declaration;
2257 declarations = declaration;
2259 last_declaration = declaration;
2261 if(token.type != ',')
2264 } while(token.type == T_IDENTIFIER);
2266 return declarations;
2269 static void semantic_parameter(declaration_t *declaration)
2271 /* TODO: improve error messages */
2273 if(declaration->declared_storage_class == STORAGE_CLASS_TYPEDEF) {
2274 errorf(HERE, "typedef not allowed in parameter list");
2275 } else if(declaration->declared_storage_class != STORAGE_CLASS_NONE
2276 && declaration->declared_storage_class != STORAGE_CLASS_REGISTER) {
2277 errorf(HERE, "parameter may only have none or register storage class");
2280 type_t *const orig_type = declaration->type;
2281 type_t * type = skip_typeref(orig_type);
2283 /* Array as last part of a parameter type is just syntactic sugar. Turn it
2284 * into a pointer. § 6.7.5.3 (7) */
2285 if (is_type_array(type)) {
2286 type_t *const element_type = type->array.element_type;
2288 type = make_pointer_type(element_type, type->base.qualifiers);
2290 declaration->type = type;
2293 if(is_type_incomplete(type)) {
2294 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2295 orig_type, declaration->symbol);
2299 static declaration_t *parse_parameter(void)
2301 declaration_specifiers_t specifiers;
2302 memset(&specifiers, 0, sizeof(specifiers));
2304 parse_declaration_specifiers(&specifiers);
2306 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2308 semantic_parameter(declaration);
2313 static declaration_t *parse_parameters(function_type_t *type)
2315 if(token.type == T_IDENTIFIER) {
2316 symbol_t *symbol = token.v.symbol;
2317 if(!is_typedef_symbol(symbol)) {
2318 type->kr_style_parameters = true;
2319 return parse_identifier_list();
2323 if(token.type == ')') {
2324 type->unspecified_parameters = 1;
2327 if(token.type == T_void && look_ahead(1)->type == ')') {
2332 declaration_t *declarations = NULL;
2333 declaration_t *declaration;
2334 declaration_t *last_declaration = NULL;
2335 function_parameter_t *parameter;
2336 function_parameter_t *last_parameter = NULL;
2339 switch(token.type) {
2343 return declarations;
2346 case T___extension__:
2348 declaration = parse_parameter();
2350 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
2351 memset(parameter, 0, sizeof(parameter[0]));
2352 parameter->type = declaration->type;
2354 if(last_parameter != NULL) {
2355 last_declaration->next = declaration;
2356 last_parameter->next = parameter;
2358 type->parameters = parameter;
2359 declarations = declaration;
2361 last_parameter = parameter;
2362 last_declaration = declaration;
2366 return declarations;
2368 if(token.type != ',')
2369 return declarations;
2379 } construct_type_kind_t;
2381 typedef struct construct_type_t construct_type_t;
2382 struct construct_type_t {
2383 construct_type_kind_t kind;
2384 construct_type_t *next;
2387 typedef struct parsed_pointer_t parsed_pointer_t;
2388 struct parsed_pointer_t {
2389 construct_type_t construct_type;
2390 type_qualifiers_t type_qualifiers;
2393 typedef struct construct_function_type_t construct_function_type_t;
2394 struct construct_function_type_t {
2395 construct_type_t construct_type;
2396 type_t *function_type;
2399 typedef struct parsed_array_t parsed_array_t;
2400 struct parsed_array_t {
2401 construct_type_t construct_type;
2402 type_qualifiers_t type_qualifiers;
2408 typedef struct construct_base_type_t construct_base_type_t;
2409 struct construct_base_type_t {
2410 construct_type_t construct_type;
2414 static construct_type_t *parse_pointer_declarator(void)
2418 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2419 memset(pointer, 0, sizeof(pointer[0]));
2420 pointer->construct_type.kind = CONSTRUCT_POINTER;
2421 pointer->type_qualifiers = parse_type_qualifiers();
2423 return (construct_type_t*) pointer;
2426 static construct_type_t *parse_array_declarator(void)
2430 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2431 memset(array, 0, sizeof(array[0]));
2432 array->construct_type.kind = CONSTRUCT_ARRAY;
2434 if(token.type == T_static) {
2435 array->is_static = true;
2439 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2440 if(type_qualifiers != 0) {
2441 if(token.type == T_static) {
2442 array->is_static = true;
2446 array->type_qualifiers = type_qualifiers;
2448 if(token.type == '*' && look_ahead(1)->type == ']') {
2449 array->is_variable = true;
2451 } else if(token.type != ']') {
2452 array->size = parse_assignment_expression();
2457 return (construct_type_t*) array;
2462 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2467 if(declaration != NULL) {
2468 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2470 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2473 declaration_t *parameters = parse_parameters(&type->function);
2474 if(declaration != NULL) {
2475 declaration->scope.declarations = parameters;
2478 construct_function_type_t *construct_function_type =
2479 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2480 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2481 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2482 construct_function_type->function_type = type;
2486 return (construct_type_t*) construct_function_type;
2491 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2492 bool may_be_abstract)
2494 /* construct a single linked list of construct_type_t's which describe
2495 * how to construct the final declarator type */
2496 construct_type_t *first = NULL;
2497 construct_type_t *last = NULL;
2500 while(token.type == '*') {
2501 construct_type_t *type = parse_pointer_declarator();
2512 /* TODO: find out if this is correct */
2515 construct_type_t *inner_types = NULL;
2517 switch(token.type) {
2519 if(declaration == NULL) {
2520 errorf(HERE, "no identifier expected in typename");
2522 declaration->symbol = token.v.symbol;
2523 declaration->source_position = token.source_position;
2529 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2535 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2536 /* avoid a loop in the outermost scope, because eat_statement doesn't
2538 if(token.type == '}' && current_function == NULL) {
2546 construct_type_t *p = last;
2549 construct_type_t *type;
2550 switch(token.type) {
2552 type = parse_function_declarator(declaration);
2555 type = parse_array_declarator();
2558 goto declarator_finished;
2561 /* insert in the middle of the list (behind p) */
2563 type->next = p->next;
2574 declarator_finished:
2577 /* append inner_types at the end of the list, we don't to set last anymore
2578 * as it's not needed anymore */
2580 assert(first == NULL);
2581 first = inner_types;
2583 last->next = inner_types;
2591 static type_t *construct_declarator_type(construct_type_t *construct_list,
2594 construct_type_t *iter = construct_list;
2595 for( ; iter != NULL; iter = iter->next) {
2596 switch(iter->kind) {
2597 case CONSTRUCT_INVALID:
2598 panic("invalid type construction found");
2599 case CONSTRUCT_FUNCTION: {
2600 construct_function_type_t *construct_function_type
2601 = (construct_function_type_t*) iter;
2603 type_t *function_type = construct_function_type->function_type;
2605 function_type->function.return_type = type;
2607 type_t *skipped_return_type = skip_typeref(type);
2608 if (is_type_function(skipped_return_type)) {
2609 errorf(HERE, "function returning function is not allowed");
2610 type = type_error_type;
2611 } else if (is_type_array(skipped_return_type)) {
2612 errorf(HERE, "function returning array is not allowed");
2613 type = type_error_type;
2615 type = function_type;
2620 case CONSTRUCT_POINTER: {
2621 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2622 type_t *pointer_type = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2623 pointer_type->pointer.points_to = type;
2624 pointer_type->base.qualifiers = parsed_pointer->type_qualifiers;
2626 type = pointer_type;
2630 case CONSTRUCT_ARRAY: {
2631 parsed_array_t *parsed_array = (parsed_array_t*) iter;
2632 type_t *array_type = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2634 expression_t *size_expression = parsed_array->size;
2635 if(size_expression != NULL) {
2637 = create_implicit_cast(size_expression, type_size_t);
2640 array_type->base.qualifiers = parsed_array->type_qualifiers;
2641 array_type->array.element_type = type;
2642 array_type->array.is_static = parsed_array->is_static;
2643 array_type->array.is_variable = parsed_array->is_variable;
2644 array_type->array.size_expression = size_expression;
2646 if(size_expression != NULL) {
2647 if(is_constant_expression(size_expression)) {
2648 array_type->array.size_constant = true;
2649 array_type->array.size
2650 = fold_constant(size_expression);
2652 array_type->array.is_vla = true;
2656 type_t *skipped_type = skip_typeref(type);
2657 if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2658 errorf(HERE, "array of void is not allowed");
2659 type = type_error_type;
2667 type_t *hashed_type = typehash_insert(type);
2668 if(hashed_type != type) {
2669 /* the function type was constructed earlier freeing it here will
2670 * destroy other types... */
2671 if(iter->kind != CONSTRUCT_FUNCTION) {
2681 static declaration_t *parse_declarator(
2682 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2684 declaration_t *const declaration = allocate_declaration_zero();
2685 declaration->declared_storage_class = specifiers->declared_storage_class;
2686 declaration->modifiers = specifiers->decl_modifiers;
2687 declaration->is_inline = specifiers->is_inline;
2689 declaration->storage_class = specifiers->declared_storage_class;
2690 if(declaration->storage_class == STORAGE_CLASS_NONE
2691 && scope != global_scope) {
2692 declaration->storage_class = STORAGE_CLASS_AUTO;
2695 construct_type_t *construct_type
2696 = parse_inner_declarator(declaration, may_be_abstract);
2697 type_t *const type = specifiers->type;
2698 declaration->type = construct_declarator_type(construct_type, type);
2700 if(construct_type != NULL) {
2701 obstack_free(&temp_obst, construct_type);
2707 static type_t *parse_abstract_declarator(type_t *base_type)
2709 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2711 type_t *result = construct_declarator_type(construct_type, base_type);
2712 if(construct_type != NULL) {
2713 obstack_free(&temp_obst, construct_type);
2719 static declaration_t *append_declaration(declaration_t* const declaration)
2721 if (last_declaration != NULL) {
2722 last_declaration->next = declaration;
2724 scope->declarations = declaration;
2726 last_declaration = declaration;
2731 * Check if the declaration of main is suspicious. main should be a
2732 * function with external linkage, returning int, taking either zero
2733 * arguments, two, or three arguments of appropriate types, ie.
2735 * int main([ int argc, char **argv [, char **env ] ]).
2737 * @param decl the declaration to check
2738 * @param type the function type of the declaration
2740 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2742 if (decl->storage_class == STORAGE_CLASS_STATIC) {
2743 warningf(decl->source_position, "'main' is normally a non-static function");
2745 if (skip_typeref(func_type->return_type) != type_int) {
2746 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2748 const function_parameter_t *parm = func_type->parameters;
2750 type_t *const first_type = parm->type;
2751 if (!types_compatible(skip_typeref(first_type), type_int)) {
2752 warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2756 type_t *const second_type = parm->type;
2757 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2758 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2762 type_t *const third_type = parm->type;
2763 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2764 warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2768 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2772 warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2778 * Check if a symbol is the equal to "main".
2780 static bool is_sym_main(const symbol_t *const sym)
2782 return strcmp(sym->string, "main") == 0;
2785 static declaration_t *internal_record_declaration(
2786 declaration_t *const declaration,
2787 const bool is_function_definition)
2789 const symbol_t *const symbol = declaration->symbol;
2790 const namespace_t namespc = (namespace_t)declaration->namespc;
2792 type_t *const orig_type = declaration->type;
2793 type_t *const type = skip_typeref(orig_type);
2794 if (is_type_function(type) &&
2795 type->function.unspecified_parameters &&
2796 warning.strict_prototypes) {
2797 warningf(declaration->source_position,
2798 "function declaration '%#T' is not a prototype",
2799 orig_type, declaration->symbol);
2802 if (is_function_definition && warning.main && is_sym_main(symbol)) {
2803 check_type_of_main(declaration, &type->function);
2806 assert(declaration->symbol != NULL);
2807 declaration_t *previous_declaration = get_declaration(symbol, namespc);
2809 assert(declaration != previous_declaration);
2810 if (previous_declaration != NULL) {
2811 if (previous_declaration->parent_scope == scope) {
2812 /* can happen for K&R style declarations */
2813 if(previous_declaration->type == NULL) {
2814 previous_declaration->type = declaration->type;
2817 const type_t *prev_type = skip_typeref(previous_declaration->type);
2818 if (!types_compatible(type, prev_type)) {
2819 errorf(declaration->source_position,
2820 "declaration '%#T' is incompatible with "
2821 "previous declaration '%#T'",
2822 orig_type, symbol, previous_declaration->type, symbol);
2823 errorf(previous_declaration->source_position,
2824 "previous declaration of '%Y' was here", symbol);
2826 unsigned old_storage_class
2827 = previous_declaration->storage_class;
2828 unsigned new_storage_class = declaration->storage_class;
2830 if(is_type_incomplete(prev_type)) {
2831 previous_declaration->type = type;
2835 /* pretend no storage class means extern for function
2836 * declarations (except if the previous declaration is neither
2837 * none nor extern) */
2838 if (is_type_function(type)) {
2839 switch (old_storage_class) {
2840 case STORAGE_CLASS_NONE:
2841 old_storage_class = STORAGE_CLASS_EXTERN;
2843 case STORAGE_CLASS_EXTERN:
2844 if (is_function_definition) {
2845 if (warning.missing_prototypes &&
2846 prev_type->function.unspecified_parameters &&
2847 !is_sym_main(symbol)) {
2848 warningf(declaration->source_position,
2849 "no previous prototype for '%#T'",
2852 } else if (new_storage_class == STORAGE_CLASS_NONE) {
2853 new_storage_class = STORAGE_CLASS_EXTERN;
2861 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2862 new_storage_class == STORAGE_CLASS_EXTERN) {
2863 warn_redundant_declaration:
2864 if (warning.redundant_decls) {
2865 warningf(declaration->source_position,
2866 "redundant declaration for '%Y'", symbol);
2867 warningf(previous_declaration->source_position,
2868 "previous declaration of '%Y' was here",
2871 } else if (current_function == NULL) {
2872 if (old_storage_class != STORAGE_CLASS_STATIC &&
2873 new_storage_class == STORAGE_CLASS_STATIC) {
2874 errorf(declaration->source_position,
2875 "static declaration of '%Y' follows non-static declaration",
2877 errorf(previous_declaration->source_position,
2878 "previous declaration of '%Y' was here", symbol);
2880 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2881 goto warn_redundant_declaration;
2883 if (new_storage_class == STORAGE_CLASS_NONE) {
2884 previous_declaration->storage_class = STORAGE_CLASS_NONE;
2885 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
2889 if (old_storage_class == new_storage_class) {
2890 errorf(declaration->source_position,
2891 "redeclaration of '%Y'", symbol);
2893 errorf(declaration->source_position,
2894 "redeclaration of '%Y' with different linkage",
2897 errorf(previous_declaration->source_position,
2898 "previous declaration of '%Y' was here", symbol);
2901 return previous_declaration;
2903 } else if (is_function_definition) {
2904 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
2905 if (warning.missing_prototypes && !is_sym_main(symbol)) {
2906 warningf(declaration->source_position,
2907 "no previous prototype for '%#T'", orig_type, symbol);
2908 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
2909 warningf(declaration->source_position,
2910 "no previous declaration for '%#T'", orig_type,
2914 } else if (warning.missing_declarations &&
2915 scope == global_scope &&
2916 !is_type_function(type) && (
2917 declaration->storage_class == STORAGE_CLASS_NONE ||
2918 declaration->storage_class == STORAGE_CLASS_THREAD
2920 warningf(declaration->source_position,
2921 "no previous declaration for '%#T'", orig_type, symbol);
2924 assert(declaration->parent_scope == NULL);
2925 assert(scope != NULL);
2927 declaration->parent_scope = scope;
2929 environment_push(declaration);
2930 return append_declaration(declaration);
2933 static declaration_t *record_declaration(declaration_t *declaration)
2935 return internal_record_declaration(declaration, false);
2938 static declaration_t *record_function_definition(declaration_t *declaration)
2940 return internal_record_declaration(declaration, true);
2943 static void parser_error_multiple_definition(declaration_t *declaration,
2944 const source_position_t source_position)
2946 errorf(source_position, "multiple definition of symbol '%Y'",
2947 declaration->symbol);
2948 errorf(declaration->source_position,
2949 "this is the location of the previous definition.");
2952 static bool is_declaration_specifier(const token_t *token,
2953 bool only_type_specifiers)
2955 switch(token->type) {
2959 return is_typedef_symbol(token->v.symbol);
2961 case T___extension__:
2964 return !only_type_specifiers;
2971 static void parse_init_declarator_rest(declaration_t *declaration)
2975 type_t *orig_type = declaration->type;
2976 type_t *type = skip_typeref(orig_type);
2978 if(declaration->init.initializer != NULL) {
2979 parser_error_multiple_definition(declaration, token.source_position);
2982 bool must_be_constant = false;
2983 if(declaration->storage_class == STORAGE_CLASS_STATIC
2984 || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
2985 || declaration->parent_scope == global_scope) {
2986 must_be_constant = true;
2989 parse_initializer_env_t env;
2990 env.type = orig_type;
2991 env.must_be_constant = must_be_constant;
2992 env.declaration = declaration;
2994 initializer_t *initializer = parse_initializer(&env);
2996 if(env.type != orig_type) {
2997 orig_type = env.type;
2998 type = skip_typeref(orig_type);
2999 declaration->type = env.type;
3002 if(is_type_function(type)) {
3003 errorf(declaration->source_position,
3004 "initializers not allowed for function types at declator '%Y' (type '%T')",
3005 declaration->symbol, orig_type);
3007 declaration->init.initializer = initializer;
3011 /* parse rest of a declaration without any declarator */
3012 static void parse_anonymous_declaration_rest(
3013 const declaration_specifiers_t *specifiers,
3014 parsed_declaration_func finished_declaration)
3018 declaration_t *const declaration = allocate_declaration_zero();
3019 declaration->type = specifiers->type;
3020 declaration->declared_storage_class = specifiers->declared_storage_class;
3021 declaration->source_position = specifiers->source_position;
3023 if (declaration->declared_storage_class != STORAGE_CLASS_NONE) {
3024 warningf(declaration->source_position, "useless storage class in empty declaration");
3026 declaration->storage_class = STORAGE_CLASS_NONE;
3028 type_t *type = declaration->type;
3029 switch (type->kind) {
3030 case TYPE_COMPOUND_STRUCT:
3031 case TYPE_COMPOUND_UNION: {
3032 if (type->compound.declaration->symbol == NULL) {
3033 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
3042 warningf(declaration->source_position, "empty declaration");
3046 finished_declaration(declaration);
3049 static void parse_declaration_rest(declaration_t *ndeclaration,
3050 const declaration_specifiers_t *specifiers,
3051 parsed_declaration_func finished_declaration)
3054 declaration_t *declaration = finished_declaration(ndeclaration);
3056 type_t *orig_type = declaration->type;
3057 type_t *type = skip_typeref(orig_type);
3059 if (type->kind != TYPE_FUNCTION &&
3060 declaration->is_inline &&
3061 is_type_valid(type)) {
3062 warningf(declaration->source_position,
3063 "variable '%Y' declared 'inline'\n", declaration->symbol);
3066 if(token.type == '=') {
3067 parse_init_declarator_rest(declaration);
3070 if(token.type != ',')
3074 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
3082 static declaration_t *finished_kr_declaration(declaration_t *declaration)
3084 symbol_t *symbol = declaration->symbol;
3085 if(symbol == NULL) {
3086 errorf(HERE, "anonymous declaration not valid as function parameter");
3089 namespace_t namespc = (namespace_t) declaration->namespc;
3090 if(namespc != NAMESPACE_NORMAL) {
3091 return record_declaration(declaration);
3094 declaration_t *previous_declaration = get_declaration(symbol, namespc);
3095 if(previous_declaration == NULL ||
3096 previous_declaration->parent_scope != scope) {
3097 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
3102 if(previous_declaration->type == NULL) {
3103 previous_declaration->type = declaration->type;
3104 previous_declaration->declared_storage_class = declaration->declared_storage_class;
3105 previous_declaration->storage_class = declaration->storage_class;
3106 previous_declaration->parent_scope = scope;
3107 return previous_declaration;
3109 return record_declaration(declaration);
3113 static void parse_declaration(parsed_declaration_func finished_declaration)
3115 declaration_specifiers_t specifiers;
3116 memset(&specifiers, 0, sizeof(specifiers));
3117 parse_declaration_specifiers(&specifiers);
3119 if(token.type == ';') {
3120 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3122 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3123 parse_declaration_rest(declaration, &specifiers, finished_declaration);
3127 static void parse_kr_declaration_list(declaration_t *declaration)
3129 type_t *type = skip_typeref(declaration->type);
3130 if(!is_type_function(type))
3133 if(!type->function.kr_style_parameters)
3136 /* push function parameters */
3137 int top = environment_top();
3138 scope_t *last_scope = scope;
3139 set_scope(&declaration->scope);
3141 declaration_t *parameter = declaration->scope.declarations;
3142 for( ; parameter != NULL; parameter = parameter->next) {
3143 assert(parameter->parent_scope == NULL);
3144 parameter->parent_scope = scope;
3145 environment_push(parameter);
3148 /* parse declaration list */
3149 while(is_declaration_specifier(&token, false)) {
3150 parse_declaration(finished_kr_declaration);
3153 /* pop function parameters */
3154 assert(scope == &declaration->scope);
3155 set_scope(last_scope);
3156 environment_pop_to(top);
3158 /* update function type */
3159 type_t *new_type = duplicate_type(type);
3160 new_type->function.kr_style_parameters = false;
3162 function_parameter_t *parameters = NULL;
3163 function_parameter_t *last_parameter = NULL;
3165 declaration_t *parameter_declaration = declaration->scope.declarations;
3166 for( ; parameter_declaration != NULL;
3167 parameter_declaration = parameter_declaration->next) {
3168 type_t *parameter_type = parameter_declaration->type;
3169 if(parameter_type == NULL) {
3171 errorf(HERE, "no type specified for function parameter '%Y'",
3172 parameter_declaration->symbol);
3174 if (warning.implicit_int) {
3175 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3176 parameter_declaration->symbol);
3178 parameter_type = type_int;
3179 parameter_declaration->type = parameter_type;
3183 semantic_parameter(parameter_declaration);
3184 parameter_type = parameter_declaration->type;
3186 function_parameter_t *function_parameter
3187 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3188 memset(function_parameter, 0, sizeof(function_parameter[0]));
3190 function_parameter->type = parameter_type;
3191 if(last_parameter != NULL) {
3192 last_parameter->next = function_parameter;
3194 parameters = function_parameter;
3196 last_parameter = function_parameter;
3198 new_type->function.parameters = parameters;
3200 type = typehash_insert(new_type);
3201 if(type != new_type) {
3202 obstack_free(type_obst, new_type);
3205 declaration->type = type;
3208 static bool first_err = true;
3211 * When called with first_err set, prints the name of the current function,
3214 static void print_in_function(void) {
3217 diagnosticf("%s: In function '%Y':\n",
3218 current_function->source_position.input_name,
3219 current_function->symbol);
3224 * Check if all labels are defined in the current function.
3225 * Check if all labels are used in the current function.
3227 static void check_labels(void)
3229 for (const goto_statement_t *goto_statement = goto_first;
3230 goto_statement != NULL;
3231 goto_statement = goto_statement->next) {
3232 declaration_t *label = goto_statement->label;
3235 if (label->source_position.input_name == NULL) {
3236 print_in_function();
3237 errorf(goto_statement->base.source_position,
3238 "label '%Y' used but not defined", label->symbol);
3241 goto_first = goto_last = NULL;
3243 if (warning.unused_label) {
3244 for (const label_statement_t *label_statement = label_first;
3245 label_statement != NULL;
3246 label_statement = label_statement->next) {
3247 const declaration_t *label = label_statement->label;
3249 if (! label->used) {
3250 print_in_function();
3251 warningf(label_statement->base.source_position,
3252 "label '%Y' defined but not used", label->symbol);
3256 label_first = label_last = NULL;
3260 * Check declarations of current_function for unused entities.
3262 static void check_declarations(void)
3264 if (warning.unused_parameter) {
3265 const scope_t *scope = ¤t_function->scope;
3267 const declaration_t *parameter = scope->declarations;
3268 for (; parameter != NULL; parameter = parameter->next) {
3269 if (! parameter->used) {
3270 print_in_function();
3271 warningf(parameter->source_position,
3272 "unused parameter '%Y'", parameter->symbol);
3276 if (warning.unused_variable) {
3280 static void parse_external_declaration(void)
3282 /* function-definitions and declarations both start with declaration
3284 declaration_specifiers_t specifiers;
3285 memset(&specifiers, 0, sizeof(specifiers));
3286 parse_declaration_specifiers(&specifiers);
3288 /* must be a declaration */
3289 if(token.type == ';') {
3290 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3294 /* declarator is common to both function-definitions and declarations */
3295 declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3297 /* must be a declaration */
3298 if(token.type == ',' || token.type == '=' || token.type == ';') {
3299 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3303 /* must be a function definition */
3304 parse_kr_declaration_list(ndeclaration);
3306 if(token.type != '{') {
3307 parse_error_expected("while parsing function definition", '{', 0);
3312 type_t *type = ndeclaration->type;
3314 /* note that we don't skip typerefs: the standard doesn't allow them here
3315 * (so we can't use is_type_function here) */
3316 if(type->kind != TYPE_FUNCTION) {
3317 if (is_type_valid(type)) {
3318 errorf(HERE, "declarator '%#T' has a body but is not a function type",
3319 type, ndeclaration->symbol);
3325 /* § 6.7.5.3 (14) a function definition with () means no
3326 * parameters (and not unspecified parameters) */
3327 if(type->function.unspecified_parameters) {
3328 type_t *duplicate = duplicate_type(type);
3329 duplicate->function.unspecified_parameters = false;
3331 type = typehash_insert(duplicate);
3332 if(type != duplicate) {
3333 obstack_free(type_obst, duplicate);
3335 ndeclaration->type = type;
3338 declaration_t *const declaration = record_function_definition(ndeclaration);
3339 if(ndeclaration != declaration) {
3340 declaration->scope = ndeclaration->scope;
3342 type = skip_typeref(declaration->type);
3344 /* push function parameters and switch scope */
3345 int top = environment_top();
3346 scope_t *last_scope = scope;
3347 set_scope(&declaration->scope);
3349 declaration_t *parameter = declaration->scope.declarations;
3350 for( ; parameter != NULL; parameter = parameter->next) {
3351 if(parameter->parent_scope == &ndeclaration->scope) {
3352 parameter->parent_scope = scope;
3354 assert(parameter->parent_scope == NULL
3355 || parameter->parent_scope == scope);
3356 parameter->parent_scope = scope;
3357 environment_push(parameter);
3360 if(declaration->init.statement != NULL) {
3361 parser_error_multiple_definition(declaration, token.source_position);
3363 goto end_of_parse_external_declaration;
3365 /* parse function body */
3366 int label_stack_top = label_top();
3367 declaration_t *old_current_function = current_function;
3368 current_function = declaration;
3370 declaration->init.statement = parse_compound_statement();
3373 check_declarations();
3375 assert(current_function == declaration);
3376 current_function = old_current_function;
3377 label_pop_to(label_stack_top);
3380 end_of_parse_external_declaration:
3381 assert(scope == &declaration->scope);
3382 set_scope(last_scope);
3383 environment_pop_to(top);
3386 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3387 source_position_t source_position)
3389 type_t *type = allocate_type_zero(TYPE_BITFIELD, source_position);
3390 type->bitfield.base = base;
3391 type->bitfield.size = size;
3396 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3399 declaration_t *iter = compound_declaration->scope.declarations;
3400 for( ; iter != NULL; iter = iter->next) {
3401 if(iter->namespc != NAMESPACE_NORMAL)
3404 if(iter->symbol == NULL) {
3405 type_t *type = skip_typeref(iter->type);
3406 if(is_type_compound(type)) {
3407 declaration_t *result
3408 = find_compound_entry(type->compound.declaration, symbol);
3415 if(iter->symbol == symbol) {
3423 static void parse_compound_declarators(declaration_t *struct_declaration,
3424 const declaration_specifiers_t *specifiers)
3426 declaration_t *last_declaration = struct_declaration->scope.declarations;
3427 if(last_declaration != NULL) {
3428 while(last_declaration->next != NULL) {
3429 last_declaration = last_declaration->next;
3434 declaration_t *declaration;
3436 if(token.type == ':') {
3437 source_position_t source_position = HERE;
3440 type_t *base_type = specifiers->type;
3441 expression_t *size = parse_constant_expression();
3443 if(!is_type_integer(skip_typeref(base_type))) {
3444 errorf(HERE, "bitfield base type '%T' is not an integer type",
3448 type_t *type = make_bitfield_type(base_type, size, source_position);
3450 declaration = allocate_declaration_zero();
3451 declaration->namespc = NAMESPACE_NORMAL;
3452 declaration->declared_storage_class = STORAGE_CLASS_NONE;
3453 declaration->storage_class = STORAGE_CLASS_NONE;
3454 declaration->source_position = source_position;
3455 declaration->modifiers = specifiers->decl_modifiers;
3456 declaration->type = type;
3458 declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3460 type_t *orig_type = declaration->type;
3461 type_t *type = skip_typeref(orig_type);
3463 if(token.type == ':') {
3464 source_position_t source_position = HERE;
3466 expression_t *size = parse_constant_expression();
3468 if(!is_type_integer(type)) {
3469 errorf(HERE, "bitfield base type '%T' is not an "
3470 "integer type", orig_type);
3473 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3474 declaration->type = bitfield_type;
3476 /* TODO we ignore arrays for now... what is missing is a check
3477 * that they're at the end of the struct */
3478 if(is_type_incomplete(type) && !is_type_array(type)) {
3480 "compound member '%Y' has incomplete type '%T'",
3481 declaration->symbol, orig_type);
3482 } else if(is_type_function(type)) {
3483 errorf(HERE, "compound member '%Y' must not have function "
3484 "type '%T'", declaration->symbol, orig_type);
3489 /* make sure we don't define a symbol multiple times */
3490 symbol_t *symbol = declaration->symbol;
3491 if(symbol != NULL) {
3492 declaration_t *prev_decl
3493 = find_compound_entry(struct_declaration, symbol);
3495 if(prev_decl != NULL) {
3496 assert(prev_decl->symbol == symbol);
3497 errorf(declaration->source_position,
3498 "multiple declarations of symbol '%Y'", symbol);
3499 errorf(prev_decl->source_position,
3500 "previous declaration of '%Y' was here", symbol);
3504 /* append declaration */
3505 if(last_declaration != NULL) {
3506 last_declaration->next = declaration;
3508 struct_declaration->scope.declarations = declaration;
3510 last_declaration = declaration;
3512 if(token.type != ',')
3522 static void parse_compound_type_entries(declaration_t *compound_declaration)
3526 while(token.type != '}' && token.type != T_EOF) {
3527 declaration_specifiers_t specifiers;
3528 memset(&specifiers, 0, sizeof(specifiers));
3529 parse_declaration_specifiers(&specifiers);
3531 parse_compound_declarators(compound_declaration, &specifiers);
3533 if(token.type == T_EOF) {
3534 errorf(HERE, "EOF while parsing struct");
3539 static type_t *parse_typename(void)
3541 declaration_specifiers_t specifiers;
3542 memset(&specifiers, 0, sizeof(specifiers));
3543 parse_declaration_specifiers(&specifiers);
3544 if(specifiers.declared_storage_class != STORAGE_CLASS_NONE) {
3545 /* TODO: improve error message, user does probably not know what a
3546 * storage class is...
3548 errorf(HERE, "typename may not have a storage class");
3551 type_t *result = parse_abstract_declarator(specifiers.type);
3559 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3560 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3561 expression_t *left);
3563 typedef struct expression_parser_function_t expression_parser_function_t;
3564 struct expression_parser_function_t {
3565 unsigned precedence;
3566 parse_expression_function parser;
3567 unsigned infix_precedence;
3568 parse_expression_infix_function infix_parser;
3571 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3574 * Creates a new invalid expression.
3576 static expression_t *create_invalid_expression(void)
3578 expression_t *expression = allocate_expression_zero(EXPR_INVALID);
3579 expression->base.source_position = token.source_position;
3584 * Prints an error message if an expression was expected but not read
3586 static expression_t *expected_expression_error(void)
3588 /* skip the error message if the error token was read */
3589 if (token.type != T_ERROR) {
3590 errorf(HERE, "expected expression, got token '%K'", &token);
3594 return create_invalid_expression();
3598 * Parse a string constant.
3600 static expression_t *parse_string_const(void)
3603 if (token.type == T_STRING_LITERAL) {
3604 string_t res = token.v.string;
3606 while (token.type == T_STRING_LITERAL) {
3607 res = concat_strings(&res, &token.v.string);
3610 if (token.type != T_WIDE_STRING_LITERAL) {
3611 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3612 /* note: that we use type_char_ptr here, which is already the
3613 * automatic converted type. revert_automatic_type_conversion
3614 * will construct the array type */
3615 cnst->base.type = type_char_ptr;
3616 cnst->string.value = res;
3620 wres = concat_string_wide_string(&res, &token.v.wide_string);
3622 wres = token.v.wide_string;
3627 switch (token.type) {
3628 case T_WIDE_STRING_LITERAL:
3629 wres = concat_wide_strings(&wres, &token.v.wide_string);
3632 case T_STRING_LITERAL:
3633 wres = concat_wide_string_string(&wres, &token.v.string);
3637 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3638 cnst->base.type = type_wchar_t_ptr;
3639 cnst->wide_string.value = wres;
3648 * Parse an integer constant.
3650 static expression_t *parse_int_const(void)
3652 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3653 cnst->base.source_position = HERE;
3654 cnst->base.type = token.datatype;
3655 cnst->conste.v.int_value = token.v.intvalue;
3663 * Parse a character constant.
3665 static expression_t *parse_character_constant(void)
3667 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
3669 cnst->base.source_position = HERE;
3670 cnst->base.type = token.datatype;
3671 cnst->conste.v.character = token.v.string;
3673 if (cnst->conste.v.character.size != 1) {
3674 if (warning.multichar && (c_mode & _GNUC)) {
3676 warningf(HERE, "multi-character character constant");
3678 errorf(HERE, "more than 1 characters in character constant");
3687 * Parse a wide character constant.
3689 static expression_t *parse_wide_character_constant(void)
3691 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
3693 cnst->base.source_position = HERE;
3694 cnst->base.type = token.datatype;
3695 cnst->conste.v.wide_character = token.v.wide_string;
3697 if (cnst->conste.v.wide_character.size != 1) {
3698 if (warning.multichar && (c_mode & _GNUC)) {
3700 warningf(HERE, "multi-character character constant");
3702 errorf(HERE, "more than 1 characters in character constant");
3711 * Parse a float constant.
3713 static expression_t *parse_float_const(void)
3715 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
3716 cnst->base.type = token.datatype;
3717 cnst->conste.v.float_value = token.v.floatvalue;
3724 static declaration_t *create_implicit_function(symbol_t *symbol,
3725 const source_position_t source_position)
3727 type_t *ntype = allocate_type_zero(TYPE_FUNCTION, source_position);
3728 ntype->function.return_type = type_int;
3729 ntype->function.unspecified_parameters = true;
3731 type_t *type = typehash_insert(ntype);
3736 declaration_t *const declaration = allocate_declaration_zero();
3737 declaration->storage_class = STORAGE_CLASS_EXTERN;
3738 declaration->declared_storage_class = STORAGE_CLASS_EXTERN;
3739 declaration->type = type;
3740 declaration->symbol = symbol;
3741 declaration->source_position = source_position;
3742 declaration->parent_scope = global_scope;
3744 scope_t *old_scope = scope;
3745 set_scope(global_scope);
3747 environment_push(declaration);
3748 /* prepends the declaration to the global declarations list */
3749 declaration->next = scope->declarations;
3750 scope->declarations = declaration;
3752 assert(scope == global_scope);
3753 set_scope(old_scope);
3759 * Creates a return_type (func)(argument_type) function type if not
3762 * @param return_type the return type
3763 * @param argument_type the argument type
3765 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3767 function_parameter_t *parameter
3768 = obstack_alloc(type_obst, sizeof(parameter[0]));
3769 memset(parameter, 0, sizeof(parameter[0]));
3770 parameter->type = argument_type;
3772 type_t *type = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3773 type->function.return_type = return_type;
3774 type->function.parameters = parameter;
3776 type_t *result = typehash_insert(type);
3777 if(result != type) {
3785 * Creates a function type for some function like builtins.
3787 * @param symbol the symbol describing the builtin
3789 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3791 switch(symbol->ID) {
3792 case T___builtin_alloca:
3793 return make_function_1_type(type_void_ptr, type_size_t);
3794 case T___builtin_nan:
3795 return make_function_1_type(type_double, type_char_ptr);
3796 case T___builtin_nanf:
3797 return make_function_1_type(type_float, type_char_ptr);
3798 case T___builtin_nand:
3799 return make_function_1_type(type_long_double, type_char_ptr);
3800 case T___builtin_va_end:
3801 return make_function_1_type(type_void, type_valist);
3803 panic("not implemented builtin symbol found");
3808 * Performs automatic type cast as described in § 6.3.2.1.
3810 * @param orig_type the original type
3812 static type_t *automatic_type_conversion(type_t *orig_type)
3814 type_t *type = skip_typeref(orig_type);
3815 if(is_type_array(type)) {
3816 array_type_t *array_type = &type->array;
3817 type_t *element_type = array_type->element_type;
3818 unsigned qualifiers = array_type->type.qualifiers;
3820 return make_pointer_type(element_type, qualifiers);
3823 if(is_type_function(type)) {
3824 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3831 * reverts the automatic casts of array to pointer types and function
3832 * to function-pointer types as defined § 6.3.2.1
3834 type_t *revert_automatic_type_conversion(const expression_t *expression)
3836 switch (expression->kind) {
3837 case EXPR_REFERENCE: return expression->reference.declaration->type;
3838 case EXPR_SELECT: return expression->select.compound_entry->type;
3840 case EXPR_UNARY_DEREFERENCE: {
3841 const expression_t *const value = expression->unary.value;
3842 type_t *const type = skip_typeref(value->base.type);
3843 assert(is_type_pointer(type));
3844 return type->pointer.points_to;
3847 case EXPR_BUILTIN_SYMBOL:
3848 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3850 case EXPR_ARRAY_ACCESS: {
3851 const expression_t *array_ref = expression->array_access.array_ref;
3852 type_t *type_left = skip_typeref(array_ref->base.type);
3853 if (!is_type_valid(type_left))
3855 assert(is_type_pointer(type_left));
3856 return type_left->pointer.points_to;
3859 case EXPR_STRING_LITERAL: {
3860 size_t size = expression->string.value.size;
3861 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
3864 case EXPR_WIDE_STRING_LITERAL: {
3865 size_t size = expression->wide_string.value.size;
3866 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
3869 case EXPR_COMPOUND_LITERAL:
3870 return expression->compound_literal.type;
3875 return expression->base.type;
3878 static expression_t *parse_reference(void)
3880 expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3882 reference_expression_t *ref = &expression->reference;
3883 ref->symbol = token.v.symbol;
3885 declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3887 source_position_t source_position = token.source_position;
3890 if(declaration == NULL) {
3891 if (! strict_mode && token.type == '(') {
3892 /* an implicitly defined function */
3893 if (warning.implicit_function_declaration) {
3894 warningf(HERE, "implicit declaration of function '%Y'",
3898 declaration = create_implicit_function(ref->symbol,
3901 errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3902 return create_invalid_expression();
3906 type_t *type = declaration->type;
3908 /* we always do the auto-type conversions; the & and sizeof parser contains
3909 * code to revert this! */
3910 type = automatic_type_conversion(type);
3912 ref->declaration = declaration;
3913 ref->base.type = type;
3915 /* this declaration is used */
3916 declaration->used = true;
3921 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3925 /* TODO check if explicit cast is allowed and issue warnings/errors */
3928 static expression_t *parse_compound_literal(type_t *type)
3930 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
3932 parse_initializer_env_t env;
3934 env.declaration = NULL;
3935 env.must_be_constant = false;
3936 initializer_t *initializer = parse_initializer(&env);
3939 expression->compound_literal.initializer = initializer;
3940 expression->compound_literal.type = type;
3941 expression->base.type = automatic_type_conversion(type);
3947 * Parse a cast expression.
3949 static expression_t *parse_cast(void)
3951 source_position_t source_position = token.source_position;
3953 type_t *type = parse_typename();
3957 if(token.type == '{') {
3958 return parse_compound_literal(type);
3961 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3962 cast->base.source_position = source_position;
3964 expression_t *value = parse_sub_expression(20);
3966 check_cast_allowed(value, type);
3968 cast->base.type = type;
3969 cast->unary.value = value;
3973 return create_invalid_expression();
3977 * Parse a statement expression.
3979 static expression_t *parse_statement_expression(void)
3981 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3983 statement_t *statement = parse_compound_statement();
3984 expression->statement.statement = statement;
3985 expression->base.source_position = statement->base.source_position;
3987 /* find last statement and use its type */
3988 type_t *type = type_void;
3989 const statement_t *stmt = statement->compound.statements;
3991 while (stmt->base.next != NULL)
3992 stmt = stmt->base.next;
3994 if (stmt->kind == STATEMENT_EXPRESSION) {
3995 type = stmt->expression.expression->base.type;
3998 warningf(expression->base.source_position, "empty statement expression ({})");
4000 expression->base.type = type;
4006 return create_invalid_expression();
4010 * Parse a braced expression.
4012 static expression_t *parse_brace_expression(void)
4016 switch(token.type) {
4018 /* gcc extension: a statement expression */
4019 return parse_statement_expression();
4023 return parse_cast();
4025 if(is_typedef_symbol(token.v.symbol)) {
4026 return parse_cast();
4030 expression_t *result = parse_expression();
4035 return create_invalid_expression();
4038 static expression_t *parse_function_keyword(void)
4043 if (current_function == NULL) {
4044 errorf(HERE, "'__func__' used outside of a function");
4047 expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
4048 expression->base.type = type_char_ptr;
4053 static expression_t *parse_pretty_function_keyword(void)
4055 eat(T___PRETTY_FUNCTION__);
4058 if (current_function == NULL) {
4059 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
4062 expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
4063 expression->base.type = type_char_ptr;
4068 static designator_t *parse_designator(void)
4070 designator_t *result = allocate_ast_zero(sizeof(result[0]));
4071 result->source_position = HERE;
4073 if(token.type != T_IDENTIFIER) {
4074 parse_error_expected("while parsing member designator",
4079 result->symbol = token.v.symbol;
4082 designator_t *last_designator = result;
4084 if(token.type == '.') {
4086 if(token.type != T_IDENTIFIER) {
4087 parse_error_expected("while parsing member designator",
4092 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4093 designator->source_position = HERE;
4094 designator->symbol = token.v.symbol;
4097 last_designator->next = designator;
4098 last_designator = designator;
4101 if(token.type == '[') {
4103 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
4104 designator->source_position = HERE;
4105 designator->array_index = parse_expression();
4106 if(designator->array_index == NULL) {
4112 last_designator->next = designator;
4113 last_designator = designator;
4125 * Parse the __builtin_offsetof() expression.
4127 static expression_t *parse_offsetof(void)
4129 eat(T___builtin_offsetof);
4131 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
4132 expression->base.type = type_size_t;
4135 type_t *type = parse_typename();
4137 designator_t *designator = parse_designator();
4140 expression->offsetofe.type = type;
4141 expression->offsetofe.designator = designator;
4144 memset(&path, 0, sizeof(path));
4145 path.top_type = type;
4146 path.path = NEW_ARR_F(type_path_entry_t, 0);
4148 descend_into_subtype(&path);
4150 if(!walk_designator(&path, designator, true)) {
4151 return create_invalid_expression();
4154 DEL_ARR_F(path.path);
4158 return create_invalid_expression();
4162 * Parses a _builtin_va_start() expression.
4164 static expression_t *parse_va_start(void)
4166 eat(T___builtin_va_start);
4168 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
4171 expression->va_starte.ap = parse_assignment_expression();
4173 expression_t *const expr = parse_assignment_expression();
4174 if (expr->kind == EXPR_REFERENCE) {
4175 declaration_t *const decl = expr->reference.declaration;
4177 return create_invalid_expression();
4178 if (decl->parent_scope == ¤t_function->scope &&
4179 decl->next == NULL) {
4180 expression->va_starte.parameter = decl;
4185 errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
4187 return create_invalid_expression();
4191 * Parses a _builtin_va_arg() expression.
4193 static expression_t *parse_va_arg(void)
4195 eat(T___builtin_va_arg);
4197 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
4200 expression->va_arge.ap = parse_assignment_expression();
4202 expression->base.type = parse_typename();
4207 return create_invalid_expression();
4210 static expression_t *parse_builtin_symbol(void)
4212 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
4214 symbol_t *symbol = token.v.symbol;
4216 expression->builtin_symbol.symbol = symbol;
4219 type_t *type = get_builtin_symbol_type(symbol);
4220 type = automatic_type_conversion(type);
4222 expression->base.type = type;
4227 * Parses a __builtin_constant() expression.
4229 static expression_t *parse_builtin_constant(void)
4231 eat(T___builtin_constant_p);
4233 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4236 expression->builtin_constant.value = parse_assignment_expression();
4238 expression->base.type = type_int;
4242 return create_invalid_expression();
4246 * Parses a __builtin_prefetch() expression.
4248 static expression_t *parse_builtin_prefetch(void)
4250 eat(T___builtin_prefetch);
4252 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4255 expression->builtin_prefetch.adr = parse_assignment_expression();
4256 if (token.type == ',') {
4258 expression->builtin_prefetch.rw = parse_assignment_expression();
4260 if (token.type == ',') {
4262 expression->builtin_prefetch.locality = parse_assignment_expression();
4265 expression->base.type = type_void;
4269 return create_invalid_expression();
4273 * Parses a __builtin_is_*() compare expression.
4275 static expression_t *parse_compare_builtin(void)
4277 expression_t *expression;
4279 switch(token.type) {
4280 case T___builtin_isgreater:
4281 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4283 case T___builtin_isgreaterequal:
4284 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4286 case T___builtin_isless:
4287 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4289 case T___builtin_islessequal:
4290 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4292 case T___builtin_islessgreater:
4293 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4295 case T___builtin_isunordered:
4296 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4299 panic("invalid compare builtin found");
4302 expression->base.source_position = HERE;
4306 expression->binary.left = parse_assignment_expression();
4308 expression->binary.right = parse_assignment_expression();
4311 type_t *const orig_type_left = expression->binary.left->base.type;
4312 type_t *const orig_type_right = expression->binary.right->base.type;
4314 type_t *const type_left = skip_typeref(orig_type_left);
4315 type_t *const type_right = skip_typeref(orig_type_right);
4316 if(!is_type_float(type_left) && !is_type_float(type_right)) {
4317 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4318 type_error_incompatible("invalid operands in comparison",
4319 expression->base.source_position, orig_type_left, orig_type_right);
4322 semantic_comparison(&expression->binary);
4327 return create_invalid_expression();
4331 * Parses a __builtin_expect() expression.
4333 static expression_t *parse_builtin_expect(void)
4335 eat(T___builtin_expect);
4337 expression_t *expression
4338 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4341 expression->binary.left = parse_assignment_expression();
4343 expression->binary.right = parse_constant_expression();
4346 expression->base.type = expression->binary.left->base.type;
4350 return create_invalid_expression();
4354 * Parses a MS assume() expression.
4356 static expression_t *parse_assume(void) {
4359 expression_t *expression
4360 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4363 expression->unary.value = parse_assignment_expression();
4366 expression->base.type = type_void;
4369 return create_invalid_expression();
4373 * Parses a primary expression.
4375 static expression_t *parse_primary_expression(void)
4377 switch (token.type) {
4378 case T_INTEGER: return parse_int_const();
4379 case T_CHARACTER_CONSTANT: return parse_character_constant();
4380 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
4381 case T_FLOATINGPOINT: return parse_float_const();
4382 case T_STRING_LITERAL:
4383 case T_WIDE_STRING_LITERAL: return parse_string_const();
4384 case T_IDENTIFIER: return parse_reference();
4385 case T___FUNCTION__:
4386 case T___func__: return parse_function_keyword();
4387 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
4388 case T___builtin_offsetof: return parse_offsetof();
4389 case T___builtin_va_start: return parse_va_start();
4390 case T___builtin_va_arg: return parse_va_arg();
4391 case T___builtin_expect: return parse_builtin_expect();
4392 case T___builtin_alloca:
4393 case T___builtin_nan:
4394 case T___builtin_nand:
4395 case T___builtin_nanf:
4396 case T___builtin_va_end: return parse_builtin_symbol();
4397 case T___builtin_isgreater:
4398 case T___builtin_isgreaterequal:
4399 case T___builtin_isless:
4400 case T___builtin_islessequal:
4401 case T___builtin_islessgreater:
4402 case T___builtin_isunordered: return parse_compare_builtin();
4403 case T___builtin_constant_p: return parse_builtin_constant();
4404 case T___builtin_prefetch: return parse_builtin_prefetch();
4405 case T_assume: return parse_assume();
4407 case '(': return parse_brace_expression();
4410 errorf(HERE, "unexpected token %K, expected an expression", &token);
4413 return create_invalid_expression();
4417 * Check if the expression has the character type and issue a warning then.
4419 static void check_for_char_index_type(const expression_t *expression) {
4420 type_t *const type = expression->base.type;
4421 const type_t *const base_type = skip_typeref(type);
4423 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4424 warning.char_subscripts) {
4425 warningf(expression->base.source_position,
4426 "array subscript has type '%T'", type);
4430 static expression_t *parse_array_expression(unsigned precedence,
4437 expression_t *inside = parse_expression();
4439 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4441 array_access_expression_t *array_access = &expression->array_access;
4443 type_t *const orig_type_left = left->base.type;
4444 type_t *const orig_type_inside = inside->base.type;
4446 type_t *const type_left = skip_typeref(orig_type_left);
4447 type_t *const type_inside = skip_typeref(orig_type_inside);
4449 type_t *return_type;
4450 if (is_type_pointer(type_left)) {
4451 return_type = type_left->pointer.points_to;
4452 array_access->array_ref = left;
4453 array_access->index = inside;
4454 check_for_char_index_type(inside);
4455 } else if (is_type_pointer(type_inside)) {
4456 return_type = type_inside->pointer.points_to;
4457 array_access->array_ref = inside;
4458 array_access->index = left;
4459 array_access->flipped = true;
4460 check_for_char_index_type(left);
4462 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4464 "array access on object with non-pointer types '%T', '%T'",
4465 orig_type_left, orig_type_inside);
4467 return_type = type_error_type;
4468 array_access->array_ref = create_invalid_expression();
4471 if(token.type != ']') {
4472 parse_error_expected("Problem while parsing array access", ']', 0);
4477 return_type = automatic_type_conversion(return_type);
4478 expression->base.type = return_type;
4483 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4485 expression_t *tp_expression = allocate_expression_zero(kind);
4486 tp_expression->base.type = type_size_t;
4488 if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4490 tp_expression->typeprop.type = parse_typename();
4493 expression_t *expression = parse_sub_expression(precedence);
4494 expression->base.type = revert_automatic_type_conversion(expression);
4496 tp_expression->typeprop.type = expression->base.type;
4497 tp_expression->typeprop.tp_expression = expression;
4500 return tp_expression;
4502 return create_invalid_expression();
4505 static expression_t *parse_sizeof(unsigned precedence)
4508 return parse_typeprop(EXPR_SIZEOF, precedence);
4511 static expression_t *parse_alignof(unsigned precedence)
4514 return parse_typeprop(EXPR_SIZEOF, precedence);
4517 static expression_t *parse_select_expression(unsigned precedence,
4518 expression_t *compound)
4521 assert(token.type == '.' || token.type == T_MINUSGREATER);
4523 bool is_pointer = (token.type == T_MINUSGREATER);
4526 expression_t *select = allocate_expression_zero(EXPR_SELECT);
4527 select->select.compound = compound;
4529 if(token.type != T_IDENTIFIER) {
4530 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4533 symbol_t *symbol = token.v.symbol;
4534 select->select.symbol = symbol;
4537 type_t *const orig_type = compound->base.type;
4538 type_t *const type = skip_typeref(orig_type);
4540 type_t *type_left = type;
4542 if (!is_type_pointer(type)) {
4543 if (is_type_valid(type)) {
4544 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4546 return create_invalid_expression();
4548 type_left = type->pointer.points_to;
4550 type_left = skip_typeref(type_left);
4552 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4553 type_left->kind != TYPE_COMPOUND_UNION) {
4554 if (is_type_valid(type_left)) {
4555 errorf(HERE, "request for member '%Y' in something not a struct or "
4556 "union, but '%T'", symbol, type_left);
4558 return create_invalid_expression();
4561 declaration_t *const declaration = type_left->compound.declaration;
4563 if(!declaration->init.is_defined) {
4564 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4566 return create_invalid_expression();
4569 declaration_t *iter = find_compound_entry(declaration, symbol);
4571 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4572 return create_invalid_expression();
4575 /* we always do the auto-type conversions; the & and sizeof parser contains
4576 * code to revert this! */
4577 type_t *expression_type = automatic_type_conversion(iter->type);
4579 select->select.compound_entry = iter;
4580 select->base.type = expression_type;
4582 if(expression_type->kind == TYPE_BITFIELD) {
4583 expression_t *extract
4584 = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4585 extract->unary.value = select;
4586 extract->base.type = expression_type->bitfield.base;
4595 * Parse a call expression, ie. expression '( ... )'.
4597 * @param expression the function address
4599 static expression_t *parse_call_expression(unsigned precedence,
4600 expression_t *expression)
4603 expression_t *result = allocate_expression_zero(EXPR_CALL);
4605 call_expression_t *call = &result->call;
4606 call->function = expression;
4608 type_t *const orig_type = expression->base.type;
4609 type_t *const type = skip_typeref(orig_type);
4611 function_type_t *function_type = NULL;
4612 if (is_type_pointer(type)) {
4613 type_t *const to_type = skip_typeref(type->pointer.points_to);
4615 if (is_type_function(to_type)) {
4616 function_type = &to_type->function;
4617 call->base.type = function_type->return_type;
4621 if (function_type == NULL && is_type_valid(type)) {
4622 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4625 /* parse arguments */
4628 if(token.type != ')') {
4629 call_argument_t *last_argument = NULL;
4632 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4634 argument->expression = parse_assignment_expression();
4635 if(last_argument == NULL) {
4636 call->arguments = argument;
4638 last_argument->next = argument;
4640 last_argument = argument;
4642 if(token.type != ',')
4649 if(function_type != NULL) {
4650 function_parameter_t *parameter = function_type->parameters;
4651 call_argument_t *argument = call->arguments;
4652 for( ; parameter != NULL && argument != NULL;
4653 parameter = parameter->next, argument = argument->next) {
4654 type_t *expected_type = parameter->type;
4655 /* TODO report scope in error messages */
4656 expression_t *const arg_expr = argument->expression;
4657 type_t *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4658 if (res_type == NULL) {
4659 /* TODO improve error message */
4660 errorf(arg_expr->base.source_position,
4661 "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4662 arg_expr, arg_expr->base.type, expected_type);
4664 argument->expression = create_implicit_cast(argument->expression, expected_type);
4667 /* too few parameters */
4668 if(parameter != NULL) {
4669 errorf(HERE, "too few arguments to function '%E'", expression);
4670 } else if(argument != NULL) {
4671 /* too many parameters */
4672 if(!function_type->variadic
4673 && !function_type->unspecified_parameters) {
4674 errorf(HERE, "too many arguments to function '%E'", expression);
4676 /* do default promotion */
4677 for( ; argument != NULL; argument = argument->next) {
4678 type_t *type = argument->expression->base.type;
4680 type = skip_typeref(type);
4681 if(is_type_integer(type)) {
4682 type = promote_integer(type);
4683 } else if(type == type_float) {
4687 argument->expression
4688 = create_implicit_cast(argument->expression, type);
4691 check_format(&result->call);
4694 check_format(&result->call);
4700 return create_invalid_expression();
4703 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4705 static bool same_compound_type(const type_t *type1, const type_t *type2)
4708 is_type_compound(type1) &&
4709 type1->kind == type2->kind &&
4710 type1->compound.declaration == type2->compound.declaration;
4714 * Parse a conditional expression, ie. 'expression ? ... : ...'.
4716 * @param expression the conditional expression
4718 static expression_t *parse_conditional_expression(unsigned precedence,
4719 expression_t *expression)
4723 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4725 conditional_expression_t *conditional = &result->conditional;
4726 conditional->condition = expression;
4729 type_t *const condition_type_orig = expression->base.type;
4730 type_t *const condition_type = skip_typeref(condition_type_orig);
4731 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4732 type_error("expected a scalar type in conditional condition",
4733 expression->base.source_position, condition_type_orig);
4736 expression_t *true_expression = parse_expression();
4738 expression_t *false_expression = parse_sub_expression(precedence);
4740 type_t *const orig_true_type = true_expression->base.type;
4741 type_t *const orig_false_type = false_expression->base.type;
4742 type_t *const true_type = skip_typeref(orig_true_type);
4743 type_t *const false_type = skip_typeref(orig_false_type);
4746 type_t *result_type;
4747 if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4748 result_type = semantic_arithmetic(true_type, false_type);
4750 true_expression = create_implicit_cast(true_expression, result_type);
4751 false_expression = create_implicit_cast(false_expression, result_type);
4753 conditional->true_expression = true_expression;
4754 conditional->false_expression = false_expression;
4755 conditional->base.type = result_type;
4756 } else if (same_compound_type(true_type, false_type) || (
4757 is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4758 is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4760 /* just take 1 of the 2 types */
4761 result_type = true_type;
4762 } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4763 && pointers_compatible(true_type, false_type)) {
4765 result_type = true_type;
4766 } else if (is_type_pointer(true_type)
4767 && is_null_pointer_constant(false_expression)) {
4768 result_type = true_type;
4769 } else if (is_type_pointer(false_type)
4770 && is_null_pointer_constant(true_expression)) {
4771 result_type = false_type;
4773 /* TODO: one pointer to void*, other some pointer */
4775 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4776 type_error_incompatible("while parsing conditional",
4777 expression->base.source_position, true_type,
4780 result_type = type_error_type;
4783 conditional->true_expression
4784 = create_implicit_cast(true_expression, result_type);
4785 conditional->false_expression
4786 = create_implicit_cast(false_expression, result_type);
4787 conditional->base.type = result_type;
4790 return create_invalid_expression();
4794 * Parse an extension expression.
4796 static expression_t *parse_extension(unsigned precedence)
4798 eat(T___extension__);
4800 /* TODO enable extensions */
4801 expression_t *expression = parse_sub_expression(precedence);
4802 /* TODO disable extensions */
4807 * Parse a __builtin_classify_type() expression.
4809 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4811 eat(T___builtin_classify_type);
4813 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4814 result->base.type = type_int;
4817 expression_t *expression = parse_sub_expression(precedence);
4819 result->classify_type.type_expression = expression;
4823 return create_invalid_expression();
4826 static void semantic_incdec(unary_expression_t *expression)
4828 type_t *const orig_type = expression->value->base.type;
4829 type_t *const type = skip_typeref(orig_type);
4830 /* TODO !is_type_real && !is_type_pointer */
4831 if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4832 if (is_type_valid(type)) {
4833 /* TODO: improve error message */
4834 errorf(HERE, "operation needs an arithmetic or pointer type");
4839 expression->base.type = orig_type;
4842 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4844 type_t *const orig_type = expression->value->base.type;
4845 type_t *const type = skip_typeref(orig_type);
4846 if(!is_type_arithmetic(type)) {
4847 if (is_type_valid(type)) {
4848 /* TODO: improve error message */
4849 errorf(HERE, "operation needs an arithmetic type");
4854 expression->base.type = orig_type;
4857 static void semantic_unexpr_scalar(unary_expression_t *expression)
4859 type_t *const orig_type = expression->value->base.type;
4860 type_t *const type = skip_typeref(orig_type);
4861 if (!is_type_scalar(type)) {
4862 if (is_type_valid(type)) {
4863 errorf(HERE, "operand of ! must be of scalar type");
4868 expression->base.type = orig_type;
4871 static void semantic_unexpr_integer(unary_expression_t *expression)
4873 type_t *const orig_type = expression->value->base.type;
4874 type_t *const type = skip_typeref(orig_type);
4875 if (!is_type_integer(type)) {
4876 if (is_type_valid(type)) {
4877 errorf(HERE, "operand of ~ must be of integer type");
4882 expression->base.type = orig_type;
4885 static void semantic_dereference(unary_expression_t *expression)
4887 type_t *const orig_type = expression->value->base.type;
4888 type_t *const type = skip_typeref(orig_type);
4889 if(!is_type_pointer(type)) {
4890 if (is_type_valid(type)) {
4891 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4896 type_t *result_type = type->pointer.points_to;
4897 result_type = automatic_type_conversion(result_type);
4898 expression->base.type = result_type;
4902 * Check the semantic of the address taken expression.
4904 static void semantic_take_addr(unary_expression_t *expression)
4906 expression_t *value = expression->value;
4907 value->base.type = revert_automatic_type_conversion(value);
4909 type_t *orig_type = value->base.type;
4910 if(!is_type_valid(orig_type))
4913 if(value->kind == EXPR_REFERENCE) {
4914 declaration_t *const declaration = value->reference.declaration;
4915 if(declaration != NULL) {
4916 if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4917 errorf(expression->base.source_position,
4918 "address of register variable '%Y' requested",
4919 declaration->symbol);
4921 declaration->address_taken = 1;
4925 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4928 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
4929 static expression_t *parse_##unexpression_type(unsigned precedence) \
4933 expression_t *unary_expression \
4934 = allocate_expression_zero(unexpression_type); \
4935 unary_expression->base.source_position = HERE; \
4936 unary_expression->unary.value = parse_sub_expression(precedence); \
4938 sfunc(&unary_expression->unary); \
4940 return unary_expression; \
4943 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4944 semantic_unexpr_arithmetic)
4945 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4946 semantic_unexpr_arithmetic)
4947 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4948 semantic_unexpr_scalar)
4949 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4950 semantic_dereference)
4951 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4953 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4954 semantic_unexpr_integer)
4955 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
4957 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4960 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4962 static expression_t *parse_##unexpression_type(unsigned precedence, \
4963 expression_t *left) \
4965 (void) precedence; \
4968 expression_t *unary_expression \
4969 = allocate_expression_zero(unexpression_type); \
4970 unary_expression->unary.value = left; \
4972 sfunc(&unary_expression->unary); \
4974 return unary_expression; \
4977 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4978 EXPR_UNARY_POSTFIX_INCREMENT,
4980 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4981 EXPR_UNARY_POSTFIX_DECREMENT,
4984 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4986 /* TODO: handle complex + imaginary types */
4988 /* § 6.3.1.8 Usual arithmetic conversions */
4989 if(type_left == type_long_double || type_right == type_long_double) {
4990 return type_long_double;
4991 } else if(type_left == type_double || type_right == type_double) {
4993 } else if(type_left == type_float || type_right == type_float) {
4997 type_right = promote_integer(type_right);
4998 type_left = promote_integer(type_left);
5000 if(type_left == type_right)
5003 bool signed_left = is_type_signed(type_left);
5004 bool signed_right = is_type_signed(type_right);
5005 int rank_left = get_rank(type_left);
5006 int rank_right = get_rank(type_right);
5007 if(rank_left < rank_right) {
5008 if(signed_left == signed_right || !signed_right) {
5014 if(signed_left == signed_right || !signed_left) {
5023 * Check the semantic restrictions for a binary expression.
5025 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
5027 expression_t *const left = expression->left;
5028 expression_t *const right = expression->right;
5029 type_t *const orig_type_left = left->base.type;
5030 type_t *const orig_type_right = right->base.type;
5031 type_t *const type_left = skip_typeref(orig_type_left);
5032 type_t *const type_right = skip_typeref(orig_type_right);
5034 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5035 /* TODO: improve error message */
5036 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5037 errorf(HERE, "operation needs arithmetic types");
5042 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5043 expression->left = create_implicit_cast(left, arithmetic_type);
5044 expression->right = create_implicit_cast(right, arithmetic_type);
5045 expression->base.type = arithmetic_type;
5048 static void semantic_shift_op(binary_expression_t *expression)
5050 expression_t *const left = expression->left;
5051 expression_t *const right = expression->right;
5052 type_t *const orig_type_left = left->base.type;
5053 type_t *const orig_type_right = right->base.type;
5054 type_t * type_left = skip_typeref(orig_type_left);
5055 type_t * type_right = skip_typeref(orig_type_right);
5057 if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
5058 /* TODO: improve error message */
5059 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5060 errorf(HERE, "operation needs integer types");
5065 type_left = promote_integer(type_left);
5066 type_right = promote_integer(type_right);
5068 expression->left = create_implicit_cast(left, type_left);
5069 expression->right = create_implicit_cast(right, type_right);
5070 expression->base.type = type_left;
5073 static void semantic_add(binary_expression_t *expression)
5075 expression_t *const left = expression->left;
5076 expression_t *const right = expression->right;
5077 type_t *const orig_type_left = left->base.type;
5078 type_t *const orig_type_right = right->base.type;
5079 type_t *const type_left = skip_typeref(orig_type_left);
5080 type_t *const type_right = skip_typeref(orig_type_right);
5083 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5084 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5085 expression->left = create_implicit_cast(left, arithmetic_type);
5086 expression->right = create_implicit_cast(right, arithmetic_type);
5087 expression->base.type = arithmetic_type;
5089 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5090 expression->base.type = type_left;
5091 } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
5092 expression->base.type = type_right;
5093 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5094 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
5098 static void semantic_sub(binary_expression_t *expression)
5100 expression_t *const left = expression->left;
5101 expression_t *const right = expression->right;
5102 type_t *const orig_type_left = left->base.type;
5103 type_t *const orig_type_right = right->base.type;
5104 type_t *const type_left = skip_typeref(orig_type_left);
5105 type_t *const type_right = skip_typeref(orig_type_right);
5108 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5109 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5110 expression->left = create_implicit_cast(left, arithmetic_type);
5111 expression->right = create_implicit_cast(right, arithmetic_type);
5112 expression->base.type = arithmetic_type;
5114 } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
5115 expression->base.type = type_left;
5116 } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
5117 if(!pointers_compatible(type_left, type_right)) {
5119 "pointers to incompatible objects to binary '-' ('%T', '%T')",
5120 orig_type_left, orig_type_right);
5122 expression->base.type = type_ptrdiff_t;
5124 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5125 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
5126 orig_type_left, orig_type_right);
5131 * Check the semantics of comparison expressions.
5133 * @param expression The expression to check.
5135 static void semantic_comparison(binary_expression_t *expression)
5137 expression_t *left = expression->left;
5138 expression_t *right = expression->right;
5139 type_t *orig_type_left = left->base.type;
5140 type_t *orig_type_right = right->base.type;
5142 type_t *type_left = skip_typeref(orig_type_left);
5143 type_t *type_right = skip_typeref(orig_type_right);
5145 /* TODO non-arithmetic types */
5146 if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5147 if (warning.sign_compare &&
5148 (expression->base.kind != EXPR_BINARY_EQUAL &&
5149 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
5150 (is_type_signed(type_left) != is_type_signed(type_right))) {
5151 warningf(expression->base.source_position,
5152 "comparison between signed and unsigned");
5154 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5155 expression->left = create_implicit_cast(left, arithmetic_type);
5156 expression->right = create_implicit_cast(right, arithmetic_type);
5157 expression->base.type = arithmetic_type;
5158 if (warning.float_equal &&
5159 (expression->base.kind == EXPR_BINARY_EQUAL ||
5160 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
5161 is_type_float(arithmetic_type)) {
5162 warningf(expression->base.source_position,
5163 "comparing floating point with == or != is unsafe");
5165 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
5166 /* TODO check compatibility */
5167 } else if (is_type_pointer(type_left)) {
5168 expression->right = create_implicit_cast(right, type_left);
5169 } else if (is_type_pointer(type_right)) {
5170 expression->left = create_implicit_cast(left, type_right);
5171 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5172 type_error_incompatible("invalid operands in comparison",
5173 expression->base.source_position,
5174 type_left, type_right);
5176 expression->base.type = type_int;
5179 static void semantic_arithmetic_assign(binary_expression_t *expression)
5181 expression_t *left = expression->left;
5182 expression_t *right = expression->right;
5183 type_t *orig_type_left = left->base.type;
5184 type_t *orig_type_right = right->base.type;
5186 type_t *type_left = skip_typeref(orig_type_left);
5187 type_t *type_right = skip_typeref(orig_type_right);
5189 if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
5190 /* TODO: improve error message */
5191 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5192 errorf(HERE, "operation needs arithmetic types");
5197 /* combined instructions are tricky. We can't create an implicit cast on
5198 * the left side, because we need the uncasted form for the store.
5199 * The ast2firm pass has to know that left_type must be right_type
5200 * for the arithmetic operation and create a cast by itself */
5201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
5202 expression->right = create_implicit_cast(right, arithmetic_type);
5203 expression->base.type = type_left;
5206 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
5208 expression_t *const left = expression->left;
5209 expression_t *const right = expression->right;
5210 type_t *const orig_type_left = left->base.type;
5211 type_t *const orig_type_right = right->base.type;
5212 type_t *const type_left = skip_typeref(orig_type_left);
5213 type_t *const type_right = skip_typeref(orig_type_right);
5215 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
5216 /* combined instructions are tricky. We can't create an implicit cast on
5217 * the left side, because we need the uncasted form for the store.
5218 * The ast2firm pass has to know that left_type must be right_type
5219 * for the arithmetic operation and create a cast by itself */
5220 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
5221 expression->right = create_implicit_cast(right, arithmetic_type);
5222 expression->base.type = type_left;
5223 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
5224 expression->base.type = type_left;
5225 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
5226 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
5231 * Check the semantic restrictions of a logical expression.
5233 static void semantic_logical_op(binary_expression_t *expression)
5235 expression_t *const left = expression->left;
5236 expression_t *const right = expression->right;
5237 type_t *const orig_type_left = left->base.type;
5238 type_t *const orig_type_right = right->base.type;
5239 type_t *const type_left = skip_typeref(orig_type_left);
5240 type_t *const type_right = skip_typeref(orig_type_right);
5242 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
5243 /* TODO: improve error message */
5244 if (is_type_valid(type_left) && is_type_valid(type_right)) {
5245 errorf(HERE, "operation needs scalar types");
5250 expression->base.type = type_int;
5254 * Checks if a compound type has constant fields.
5256 static bool has_const_fields(const compound_type_t *type)
5258 const scope_t *scope = &type->declaration->scope;
5259 const declaration_t *declaration = scope->declarations;
5261 for (; declaration != NULL; declaration = declaration->next) {
5262 if (declaration->namespc != NAMESPACE_NORMAL)
5265 const type_t *decl_type = skip_typeref(declaration->type);
5266 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5274 * Check the semantic restrictions of a binary assign expression.
5276 static void semantic_binexpr_assign(binary_expression_t *expression)
5278 expression_t *left = expression->left;
5279 type_t *orig_type_left = left->base.type;
5281 type_t *type_left = revert_automatic_type_conversion(left);
5282 type_left = skip_typeref(orig_type_left);
5284 /* must be a modifiable lvalue */
5285 if (is_type_array(type_left)) {
5286 errorf(HERE, "cannot assign to arrays ('%E')", left);
5289 if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5290 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5294 if(is_type_incomplete(type_left)) {
5296 "left-hand side of assignment '%E' has incomplete type '%T'",
5297 left, orig_type_left);
5300 if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5301 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5302 left, orig_type_left);
5306 type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5308 if (res_type == NULL) {
5309 errorf(expression->base.source_position,
5310 "cannot assign to '%T' from '%T'",
5311 orig_type_left, expression->right->base.type);
5313 expression->right = create_implicit_cast(expression->right, res_type);
5316 expression->base.type = orig_type_left;
5320 * Determine if the outermost operation (or parts thereof) of the given
5321 * expression has no effect in order to generate a warning about this fact.
5322 * Therefore in some cases this only examines some of the operands of the
5323 * expression (see comments in the function and examples below).
5325 * f() + 23; // warning, because + has no effect
5326 * x || f(); // no warning, because x controls execution of f()
5327 * x ? y : f(); // warning, because y has no effect
5328 * (void)x; // no warning to be able to suppress the warning
5329 * This function can NOT be used for an "expression has definitely no effect"-
5331 static bool expression_has_effect(const expression_t *const expr)
5333 switch (expr->kind) {
5334 case EXPR_UNKNOWN: break;
5335 case EXPR_INVALID: return true; /* do NOT warn */
5336 case EXPR_REFERENCE: return false;
5337 case EXPR_CONST: return false;
5338 case EXPR_CHARACTER_CONSTANT: return false;
5339 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
5340 case EXPR_STRING_LITERAL: return false;
5341 case EXPR_WIDE_STRING_LITERAL: return false;
5344 const call_expression_t *const call = &expr->call;
5345 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5348 switch (call->function->builtin_symbol.symbol->ID) {
5349 case T___builtin_va_end: return true;
5350 default: return false;
5354 /* Generate the warning if either the left or right hand side of a
5355 * conditional expression has no effect */
5356 case EXPR_CONDITIONAL: {
5357 const conditional_expression_t *const cond = &expr->conditional;
5359 expression_has_effect(cond->true_expression) &&
5360 expression_has_effect(cond->false_expression);
5363 case EXPR_SELECT: return false;
5364 case EXPR_ARRAY_ACCESS: return false;
5365 case EXPR_SIZEOF: return false;
5366 case EXPR_CLASSIFY_TYPE: return false;
5367 case EXPR_ALIGNOF: return false;
5369 case EXPR_FUNCTION: return false;
5370 case EXPR_PRETTY_FUNCTION: return false;
5371 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
5372 case EXPR_BUILTIN_CONSTANT_P: return false;
5373 case EXPR_BUILTIN_PREFETCH: return true;
5374 case EXPR_OFFSETOF: return false;
5375 case EXPR_VA_START: return true;
5376 case EXPR_VA_ARG: return true;
5377 case EXPR_STATEMENT: return true; // TODO
5378 case EXPR_COMPOUND_LITERAL: return false;
5380 case EXPR_UNARY_NEGATE: return false;
5381 case EXPR_UNARY_PLUS: return false;
5382 case EXPR_UNARY_BITWISE_NEGATE: return false;
5383 case EXPR_UNARY_NOT: return false;
5384 case EXPR_UNARY_DEREFERENCE: return false;
5385 case EXPR_UNARY_TAKE_ADDRESS: return false;
5386 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
5387 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
5388 case EXPR_UNARY_PREFIX_INCREMENT: return true;
5389 case EXPR_UNARY_PREFIX_DECREMENT: return true;
5391 /* Treat void casts as if they have an effect in order to being able to
5392 * suppress the warning */
5393 case EXPR_UNARY_CAST: {
5394 type_t *const type = skip_typeref(expr->base.type);
5395 return is_type_atomic(type, ATOMIC_TYPE_VOID);
5398 case EXPR_UNARY_CAST_IMPLICIT: return true;
5399 case EXPR_UNARY_ASSUME: return true;
5400 case EXPR_UNARY_BITFIELD_EXTRACT: return false;
5402 case EXPR_BINARY_ADD: return false;
5403 case EXPR_BINARY_SUB: return false;
5404 case EXPR_BINARY_MUL: return false;
5405 case EXPR_BINARY_DIV: return false;
5406 case EXPR_BINARY_MOD: return false;
5407 case EXPR_BINARY_EQUAL: return false;
5408 case EXPR_BINARY_NOTEQUAL: return false;
5409 case EXPR_BINARY_LESS: return false;
5410 case EXPR_BINARY_LESSEQUAL: return false;
5411 case EXPR_BINARY_GREATER: return false;
5412 case EXPR_BINARY_GREATEREQUAL: return false;
5413 case EXPR_BINARY_BITWISE_AND: return false;
5414 case EXPR_BINARY_BITWISE_OR: return false;
5415 case EXPR_BINARY_BITWISE_XOR: return false;
5416 case EXPR_BINARY_SHIFTLEFT: return false;
5417 case EXPR_BINARY_SHIFTRIGHT: return false;
5418 case EXPR_BINARY_ASSIGN: return true;
5419 case EXPR_BINARY_MUL_ASSIGN: return true;
5420 case EXPR_BINARY_DIV_ASSIGN: return true;
5421 case EXPR_BINARY_MOD_ASSIGN: return true;
5422 case EXPR_BINARY_ADD_ASSIGN: return true;
5423 case EXPR_BINARY_SUB_ASSIGN: return true;
5424 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
5425 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
5426 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5427 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5428 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
5430 /* Only examine the right hand side of && and ||, because the left hand
5431 * side already has the effect of controlling the execution of the right
5433 case EXPR_BINARY_LOGICAL_AND:
5434 case EXPR_BINARY_LOGICAL_OR:
5435 /* Only examine the right hand side of a comma expression, because the left
5436 * hand side has a separate warning */
5437 case EXPR_BINARY_COMMA:
5438 return expression_has_effect(expr->binary.right);
5440 case EXPR_BINARY_BUILTIN_EXPECT: return true;
5441 case EXPR_BINARY_ISGREATER: return false;
5442 case EXPR_BINARY_ISGREATEREQUAL: return false;
5443 case EXPR_BINARY_ISLESS: return false;
5444 case EXPR_BINARY_ISLESSEQUAL: return false;
5445 case EXPR_BINARY_ISLESSGREATER: return false;
5446 case EXPR_BINARY_ISUNORDERED: return false;
5449 panic("unexpected expression");
5452 static void semantic_comma(binary_expression_t *expression)
5454 if (warning.unused_value) {
5455 const expression_t *const left = expression->left;
5456 if (!expression_has_effect(left)) {
5457 warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5460 expression->base.type = expression->right->base.type;
5463 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
5464 static expression_t *parse_##binexpression_type(unsigned precedence, \
5465 expression_t *left) \
5468 source_position_t pos = HERE; \
5470 expression_t *right = parse_sub_expression(precedence + lr); \
5472 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5473 binexpr->base.source_position = pos; \
5474 binexpr->binary.left = left; \
5475 binexpr->binary.right = right; \
5476 sfunc(&binexpr->binary); \
5481 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, semantic_comma, 1)
5482 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, semantic_binexpr_arithmetic, 1)
5483 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, semantic_binexpr_arithmetic, 1)
5484 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, semantic_binexpr_arithmetic, 1)
5485 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, semantic_add, 1)
5486 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, semantic_sub, 1)
5487 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, semantic_comparison, 1)
5488 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, semantic_comparison, 1)
5489 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, semantic_binexpr_assign, 0)
5491 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL,
5492 semantic_comparison, 1)
5493 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5494 semantic_comparison, 1)
5495 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL,
5496 semantic_comparison, 1)
5497 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL,
5498 semantic_comparison, 1)
5500 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5501 semantic_binexpr_arithmetic, 1)
5502 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5503 semantic_binexpr_arithmetic, 1)
5504 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5505 semantic_binexpr_arithmetic, 1)
5506 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5507 semantic_logical_op, 1)
5508 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5509 semantic_logical_op, 1)
5510 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5511 semantic_shift_op, 1)
5512 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5513 semantic_shift_op, 1)
5514 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5515 semantic_arithmetic_addsubb_assign, 0)
5516 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5517 semantic_arithmetic_addsubb_assign, 0)
5518 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5519 semantic_arithmetic_assign, 0)
5520 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5521 semantic_arithmetic_assign, 0)
5522 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5523 semantic_arithmetic_assign, 0)
5524 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5525 semantic_arithmetic_assign, 0)
5526 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5527 semantic_arithmetic_assign, 0)
5528 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5529 semantic_arithmetic_assign, 0)
5530 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5531 semantic_arithmetic_assign, 0)
5532 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5533 semantic_arithmetic_assign, 0)
5535 static expression_t *parse_sub_expression(unsigned precedence)
5537 if(token.type < 0) {
5538 return expected_expression_error();
5541 expression_parser_function_t *parser
5542 = &expression_parsers[token.type];
5543 source_position_t source_position = token.source_position;
5546 if(parser->parser != NULL) {
5547 left = parser->parser(parser->precedence);
5549 left = parse_primary_expression();
5551 assert(left != NULL);
5552 left->base.source_position = source_position;
5555 if(token.type < 0) {
5556 return expected_expression_error();
5559 parser = &expression_parsers[token.type];
5560 if(parser->infix_parser == NULL)
5562 if(parser->infix_precedence < precedence)
5565 left = parser->infix_parser(parser->infix_precedence, left);
5567 assert(left != NULL);
5568 assert(left->kind != EXPR_UNKNOWN);
5569 left->base.source_position = source_position;
5576 * Parse an expression.
5578 static expression_t *parse_expression(void)
5580 return parse_sub_expression(1);
5584 * Register a parser for a prefix-like operator with given precedence.
5586 * @param parser the parser function
5587 * @param token_type the token type of the prefix token
5588 * @param precedence the precedence of the operator
5590 static void register_expression_parser(parse_expression_function parser,
5591 int token_type, unsigned precedence)
5593 expression_parser_function_t *entry = &expression_parsers[token_type];
5595 if(entry->parser != NULL) {
5596 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5597 panic("trying to register multiple expression parsers for a token");
5599 entry->parser = parser;
5600 entry->precedence = precedence;
5604 * Register a parser for an infix operator with given precedence.
5606 * @param parser the parser function
5607 * @param token_type the token type of the infix operator
5608 * @param precedence the precedence of the operator
5610 static void register_infix_parser(parse_expression_infix_function parser,
5611 int token_type, unsigned precedence)
5613 expression_parser_function_t *entry = &expression_parsers[token_type];
5615 if(entry->infix_parser != NULL) {
5616 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5617 panic("trying to register multiple infix expression parsers for a "
5620 entry->infix_parser = parser;
5621 entry->infix_precedence = precedence;
5625 * Initialize the expression parsers.
5627 static void init_expression_parsers(void)
5629 memset(&expression_parsers, 0, sizeof(expression_parsers));
5631 register_infix_parser(parse_array_expression, '[', 30);
5632 register_infix_parser(parse_call_expression, '(', 30);
5633 register_infix_parser(parse_select_expression, '.', 30);
5634 register_infix_parser(parse_select_expression, T_MINUSGREATER, 30);
5635 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5637 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5640 register_infix_parser(parse_EXPR_BINARY_MUL, '*', 16);
5641 register_infix_parser(parse_EXPR_BINARY_DIV, '/', 16);
5642 register_infix_parser(parse_EXPR_BINARY_MOD, '%', 16);
5643 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, 16);
5644 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, 16);
5645 register_infix_parser(parse_EXPR_BINARY_ADD, '+', 15);
5646 register_infix_parser(parse_EXPR_BINARY_SUB, '-', 15);
5647 register_infix_parser(parse_EXPR_BINARY_LESS, '<', 14);
5648 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', 14);
5649 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, 14);
5650 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, 14);
5651 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, 13);
5652 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5653 T_EXCLAMATIONMARKEQUAL, 13);
5654 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', 12);
5655 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', 11);
5656 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', 10);
5657 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, 9);
5658 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, 8);
5659 register_infix_parser(parse_conditional_expression, '?', 7);
5660 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', 2);
5661 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, 2);
5662 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, 2);
5663 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, 2);
5664 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, 2);
5665 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, 2);
5666 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5667 T_LESSLESSEQUAL, 2);
5668 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5669 T_GREATERGREATEREQUAL, 2);
5670 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5672 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5674 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5677 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', 1);
5679 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-', 25);
5680 register_expression_parser(parse_EXPR_UNARY_PLUS, '+', 25);
5681 register_expression_parser(parse_EXPR_UNARY_NOT, '!', 25);
5682 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~', 25);
5683 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*', 25);
5684 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&', 25);
5685 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5687 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5689 register_expression_parser(parse_sizeof, T_sizeof, 25);
5690 register_expression_parser(parse_alignof, T___alignof__, 25);
5691 register_expression_parser(parse_extension, T___extension__, 25);
5692 register_expression_parser(parse_builtin_classify_type,
5693 T___builtin_classify_type, 25);
5697 * Parse a asm statement constraints specification.
5699 static asm_constraint_t *parse_asm_constraints(void)
5701 asm_constraint_t *result = NULL;
5702 asm_constraint_t *last = NULL;
5704 while(token.type == T_STRING_LITERAL || token.type == '[') {
5705 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5706 memset(constraint, 0, sizeof(constraint[0]));
5708 if(token.type == '[') {
5710 if(token.type != T_IDENTIFIER) {
5711 parse_error_expected("while parsing asm constraint",
5715 constraint->symbol = token.v.symbol;
5720 constraint->constraints = parse_string_literals();
5722 constraint->expression = parse_expression();
5726 last->next = constraint;
5728 result = constraint;
5732 if(token.type != ',')
5743 * Parse a asm statement clobber specification.
5745 static asm_clobber_t *parse_asm_clobbers(void)
5747 asm_clobber_t *result = NULL;
5748 asm_clobber_t *last = NULL;
5750 while(token.type == T_STRING_LITERAL) {
5751 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5752 clobber->clobber = parse_string_literals();
5755 last->next = clobber;
5761 if(token.type != ',')
5770 * Parse an asm statement.
5772 static statement_t *parse_asm_statement(void)
5776 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
5777 statement->base.source_position = token.source_position;
5779 asm_statement_t *asm_statement = &statement->asms;
5781 if(token.type == T_volatile) {
5783 asm_statement->is_volatile = true;
5787 asm_statement->asm_text = parse_string_literals();
5789 if(token.type != ':')
5793 asm_statement->inputs = parse_asm_constraints();
5794 if(token.type != ':')
5798 asm_statement->outputs = parse_asm_constraints();
5799 if(token.type != ':')
5803 asm_statement->clobbers = parse_asm_clobbers();
5814 * Parse a case statement.
5816 static statement_t *parse_case_statement(void)
5820 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5822 statement->base.source_position = token.source_position;
5823 statement->case_label.expression = parse_expression();
5825 if (c_mode & _GNUC) {
5826 if (token.type == T_DOTDOTDOT) {
5828 statement->case_label.end_range = parse_expression();
5834 if (! is_constant_expression(statement->case_label.expression)) {
5835 errorf(statement->base.source_position,
5836 "case label does not reduce to an integer constant");
5838 /* TODO: check if the case label is already known */
5839 if (current_switch != NULL) {
5840 /* link all cases into the switch statement */
5841 if (current_switch->last_case == NULL) {
5842 current_switch->first_case =
5843 current_switch->last_case = &statement->case_label;
5845 current_switch->last_case->next = &statement->case_label;
5848 errorf(statement->base.source_position,
5849 "case label not within a switch statement");
5852 statement->case_label.statement = parse_statement();
5860 * Finds an existing default label of a switch statement.
5862 static case_label_statement_t *
5863 find_default_label(const switch_statement_t *statement)
5865 case_label_statement_t *label = statement->first_case;
5866 for ( ; label != NULL; label = label->next) {
5867 if (label->expression == NULL)
5874 * Parse a default statement.
5876 static statement_t *parse_default_statement(void)
5880 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5882 statement->base.source_position = token.source_position;
5885 if (current_switch != NULL) {
5886 const case_label_statement_t *def_label = find_default_label(current_switch);
5887 if (def_label != NULL) {
5888 errorf(HERE, "multiple default labels in one switch");
5889 errorf(def_label->base.source_position,
5890 "this is the first default label");
5892 /* link all cases into the switch statement */
5893 if (current_switch->last_case == NULL) {
5894 current_switch->first_case =
5895 current_switch->last_case = &statement->case_label;
5897 current_switch->last_case->next = &statement->case_label;
5901 errorf(statement->base.source_position,
5902 "'default' label not within a switch statement");
5904 statement->case_label.statement = parse_statement();
5912 * Return the declaration for a given label symbol or create a new one.
5914 static declaration_t *get_label(symbol_t *symbol)
5916 declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
5917 assert(current_function != NULL);
5918 /* if we found a label in the same function, then we already created the
5920 if(candidate != NULL
5921 && candidate->parent_scope == ¤t_function->scope) {
5925 /* otherwise we need to create a new one */
5926 declaration_t *const declaration = allocate_declaration_zero();
5927 declaration->namespc = NAMESPACE_LABEL;
5928 declaration->symbol = symbol;
5930 label_push(declaration);
5936 * Parse a label statement.
5938 static statement_t *parse_label_statement(void)
5940 assert(token.type == T_IDENTIFIER);
5941 symbol_t *symbol = token.v.symbol;
5944 declaration_t *label = get_label(symbol);
5946 /* if source position is already set then the label is defined twice,
5947 * otherwise it was just mentioned in a goto so far */
5948 if(label->source_position.input_name != NULL) {
5949 errorf(HERE, "duplicate label '%Y'", symbol);
5950 errorf(label->source_position, "previous definition of '%Y' was here",
5953 label->source_position = token.source_position;
5956 statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
5958 statement->base.source_position = token.source_position;
5959 statement->label.label = label;
5963 if(token.type == '}') {
5964 /* TODO only warn? */
5965 errorf(HERE, "label at end of compound statement");
5968 if (token.type == ';') {
5969 /* eat an empty statement here, to avoid the warning about an empty
5970 * after a label. label:; is commonly used to have a label before
5974 statement->label.statement = parse_statement();
5978 /* remember the labels's in a list for later checking */
5979 if (label_last == NULL) {
5980 label_first = &statement->label;
5982 label_last->next = &statement->label;
5984 label_last = &statement->label;
5990 * Parse an if statement.
5992 static statement_t *parse_if(void)
5996 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
5997 statement->base.source_position = token.source_position;
6000 statement->ifs.condition = parse_expression();
6003 statement->ifs.true_statement = parse_statement();
6004 if(token.type == T_else) {
6006 statement->ifs.false_statement = parse_statement();
6015 * Parse a switch statement.
6017 static statement_t *parse_switch(void)
6021 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
6022 statement->base.source_position = token.source_position;
6025 expression_t *const expr = parse_expression();
6026 type_t * type = skip_typeref(expr->base.type);
6027 if (is_type_integer(type)) {
6028 type = promote_integer(type);
6029 } else if (is_type_valid(type)) {
6030 errorf(expr->base.source_position,
6031 "switch quantity is not an integer, but '%T'", type);
6032 type = type_error_type;
6034 statement->switchs.expression = create_implicit_cast(expr, type);
6037 switch_statement_t *rem = current_switch;
6038 current_switch = &statement->switchs;
6039 statement->switchs.body = parse_statement();
6040 current_switch = rem;
6042 if (warning.switch_default
6043 && find_default_label(&statement->switchs) == NULL) {
6044 warningf(statement->base.source_position, "switch has no default case");
6052 static statement_t *parse_loop_body(statement_t *const loop)
6054 statement_t *const rem = current_loop;
6055 current_loop = loop;
6057 statement_t *const body = parse_statement();
6064 * Parse a while statement.
6066 static statement_t *parse_while(void)
6070 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
6071 statement->base.source_position = token.source_position;
6074 statement->whiles.condition = parse_expression();
6077 statement->whiles.body = parse_loop_body(statement);
6085 * Parse a do statement.
6087 static statement_t *parse_do(void)
6091 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
6093 statement->base.source_position = token.source_position;
6095 statement->do_while.body = parse_loop_body(statement);
6099 statement->do_while.condition = parse_expression();
6109 * Parse a for statement.
6111 static statement_t *parse_for(void)
6115 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
6116 statement->base.source_position = token.source_position;
6118 int top = environment_top();
6119 scope_t *last_scope = scope;
6120 set_scope(&statement->fors.scope);
6124 if(token.type != ';') {
6125 if(is_declaration_specifier(&token, false)) {
6126 parse_declaration(record_declaration);
6128 expression_t *const init = parse_expression();
6129 statement->fors.initialisation = init;
6130 if (warning.unused_value && !expression_has_effect(init)) {
6131 warningf(init->base.source_position,
6132 "initialisation of 'for'-statement has no effect");
6140 if(token.type != ';') {
6141 statement->fors.condition = parse_expression();
6144 if(token.type != ')') {
6145 expression_t *const step = parse_expression();
6146 statement->fors.step = step;
6147 if (warning.unused_value && !expression_has_effect(step)) {
6148 warningf(step->base.source_position,
6149 "step of 'for'-statement has no effect");
6153 statement->fors.body = parse_loop_body(statement);
6155 assert(scope == &statement->fors.scope);
6156 set_scope(last_scope);
6157 environment_pop_to(top);
6162 assert(scope == &statement->fors.scope);
6163 set_scope(last_scope);
6164 environment_pop_to(top);
6170 * Parse a goto statement.
6172 static statement_t *parse_goto(void)
6176 if(token.type != T_IDENTIFIER) {
6177 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
6181 symbol_t *symbol = token.v.symbol;
6184 declaration_t *label = get_label(symbol);
6186 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
6187 statement->base.source_position = token.source_position;
6189 statement->gotos.label = label;
6191 /* remember the goto's in a list for later checking */
6192 if (goto_last == NULL) {
6193 goto_first = &statement->gotos;
6195 goto_last->next = &statement->gotos;
6197 goto_last = &statement->gotos;
6207 * Parse a continue statement.
6209 static statement_t *parse_continue(void)
6211 statement_t *statement;
6212 if (current_loop == NULL) {
6213 errorf(HERE, "continue statement not within loop");
6216 statement = allocate_statement_zero(STATEMENT_CONTINUE);
6218 statement->base.source_position = token.source_position;
6230 * Parse a break statement.
6232 static statement_t *parse_break(void)
6234 statement_t *statement;
6235 if (current_switch == NULL && current_loop == NULL) {
6236 errorf(HERE, "break statement not within loop or switch");
6239 statement = allocate_statement_zero(STATEMENT_BREAK);
6241 statement->base.source_position = token.source_position;
6253 * Check if a given declaration represents a local variable.
6255 static bool is_local_var_declaration(const declaration_t *declaration) {
6256 switch ((storage_class_tag_t) declaration->storage_class) {
6257 case STORAGE_CLASS_AUTO:
6258 case STORAGE_CLASS_REGISTER: {
6259 const type_t *type = skip_typeref(declaration->type);
6260 if(is_type_function(type)) {
6272 * Check if a given declaration represents a variable.
6274 static bool is_var_declaration(const declaration_t *declaration) {
6275 if(declaration->storage_class == STORAGE_CLASS_TYPEDEF)
6278 const type_t *type = skip_typeref(declaration->type);
6279 return !is_type_function(type);
6283 * Check if a given expression represents a local variable.
6285 static bool is_local_variable(const expression_t *expression)
6287 if (expression->base.kind != EXPR_REFERENCE) {
6290 const declaration_t *declaration = expression->reference.declaration;
6291 return is_local_var_declaration(declaration);
6295 * Check if a given expression represents a local variable and
6296 * return its declaration then, else return NULL.
6298 declaration_t *expr_is_variable(const expression_t *expression)
6300 if (expression->base.kind != EXPR_REFERENCE) {
6303 declaration_t *declaration = expression->reference.declaration;
6304 if (is_var_declaration(declaration))
6310 * Parse a return statement.
6312 static statement_t *parse_return(void)
6316 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
6317 statement->base.source_position = token.source_position;
6319 expression_t *return_value = NULL;
6320 if(token.type != ';') {
6321 return_value = parse_expression();
6325 const type_t *const func_type = current_function->type;
6326 assert(is_type_function(func_type));
6327 type_t *const return_type = skip_typeref(func_type->function.return_type);
6329 if(return_value != NULL) {
6330 type_t *return_value_type = skip_typeref(return_value->base.type);
6332 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6333 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6334 warningf(statement->base.source_position,
6335 "'return' with a value, in function returning void");
6336 return_value = NULL;
6338 type_t *const res_type = semantic_assign(return_type,
6339 return_value, "'return'");
6340 if (res_type == NULL) {
6341 errorf(statement->base.source_position,
6342 "cannot return something of type '%T' in function returning '%T'",
6343 return_value->base.type, return_type);
6345 return_value = create_implicit_cast(return_value, res_type);
6348 /* check for returning address of a local var */
6349 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6350 const expression_t *expression = return_value->unary.value;
6351 if (is_local_variable(expression)) {
6352 warningf(statement->base.source_position,
6353 "function returns address of local variable");
6357 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6358 warningf(statement->base.source_position,
6359 "'return' without value, in function returning non-void");
6362 statement->returns.value = return_value;
6370 * Parse a declaration statement.
6372 static statement_t *parse_declaration_statement(void)
6374 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6376 statement->base.source_position = token.source_position;
6378 declaration_t *before = last_declaration;
6379 parse_declaration(record_declaration);
6381 if(before == NULL) {
6382 statement->declaration.declarations_begin = scope->declarations;
6384 statement->declaration.declarations_begin = before->next;
6386 statement->declaration.declarations_end = last_declaration;
6392 * Parse an expression statement, ie. expr ';'.
6394 static statement_t *parse_expression_statement(void)
6396 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6398 statement->base.source_position = token.source_position;
6399 expression_t *const expr = parse_expression();
6400 statement->expression.expression = expr;
6402 if (warning.unused_value && !expression_has_effect(expr)) {
6403 warningf(expr->base.source_position, "statement has no effect");
6414 * Parse a statement.
6416 static statement_t *parse_statement(void)
6418 statement_t *statement = NULL;
6420 /* declaration or statement */
6421 switch(token.type) {
6423 statement = parse_asm_statement();
6427 statement = parse_case_statement();
6431 statement = parse_default_statement();
6435 statement = parse_compound_statement();
6439 statement = parse_if();
6443 statement = parse_switch();
6447 statement = parse_while();
6451 statement = parse_do();
6455 statement = parse_for();
6459 statement = parse_goto();
6463 statement = parse_continue();
6467 statement = parse_break();
6471 statement = parse_return();
6475 if (warning.empty_statement) {
6476 warningf(HERE, "statement is empty");
6483 if(look_ahead(1)->type == ':') {
6484 statement = parse_label_statement();
6488 if(is_typedef_symbol(token.v.symbol)) {
6489 statement = parse_declaration_statement();
6493 statement = parse_expression_statement();
6496 case T___extension__:
6497 /* this can be a prefix to a declaration or an expression statement */
6498 /* we simply eat it now and parse the rest with tail recursion */
6501 } while(token.type == T___extension__);
6502 statement = parse_statement();
6506 statement = parse_declaration_statement();
6510 statement = parse_expression_statement();
6514 assert(statement == NULL
6515 || statement->base.source_position.input_name != NULL);
6521 * Parse a compound statement.
6523 static statement_t *parse_compound_statement(void)
6525 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6527 statement->base.source_position = token.source_position;
6531 int top = environment_top();
6532 scope_t *last_scope = scope;
6533 set_scope(&statement->compound.scope);
6535 statement_t *last_statement = NULL;
6537 while(token.type != '}' && token.type != T_EOF) {
6538 statement_t *sub_statement = parse_statement();
6539 if(sub_statement == NULL)
6542 if(last_statement != NULL) {
6543 last_statement->base.next = sub_statement;
6545 statement->compound.statements = sub_statement;
6548 while(sub_statement->base.next != NULL)
6549 sub_statement = sub_statement->base.next;
6551 last_statement = sub_statement;
6554 if(token.type == '}') {
6557 errorf(statement->base.source_position,
6558 "end of file while looking for closing '}'");
6561 assert(scope == &statement->compound.scope);
6562 set_scope(last_scope);
6563 environment_pop_to(top);
6569 * Initialize builtin types.
6571 static void initialize_builtin_types(void)
6573 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
6574 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
6575 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
6576 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
6577 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
6578 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6579 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", type_int);
6580 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
6582 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
6583 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6584 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
6585 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
6589 * Check for unused global static functions and variables
6591 static void check_unused_globals(void)
6593 if (!warning.unused_function && !warning.unused_variable)
6596 for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6597 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6600 type_t *const type = decl->type;
6602 if (is_type_function(skip_typeref(type))) {
6603 if (!warning.unused_function || decl->is_inline)
6606 s = (decl->init.statement != NULL ? "defined" : "declared");
6608 if (!warning.unused_variable)
6614 warningf(decl->source_position, "'%#T' %s but not used",
6615 type, decl->symbol, s);
6620 * Parse a translation unit.
6622 static translation_unit_t *parse_translation_unit(void)
6624 translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6626 assert(global_scope == NULL);
6627 global_scope = &unit->scope;
6629 assert(scope == NULL);
6630 set_scope(&unit->scope);
6632 initialize_builtin_types();
6634 while(token.type != T_EOF) {
6635 if (token.type == ';') {
6636 /* TODO error in strict mode */
6637 warningf(HERE, "stray ';' outside of function");
6640 parse_external_declaration();
6644 assert(scope == &unit->scope);
6646 last_declaration = NULL;
6648 assert(global_scope == &unit->scope);
6649 check_unused_globals();
6650 global_scope = NULL;
6658 * @return the translation unit or NULL if errors occurred.
6660 translation_unit_t *parse(void)
6662 environment_stack = NEW_ARR_F(stack_entry_t, 0);
6663 label_stack = NEW_ARR_F(stack_entry_t, 0);
6664 diagnostic_count = 0;
6668 type_set_output(stderr);
6669 ast_set_output(stderr);
6671 lookahead_bufpos = 0;
6672 for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6675 translation_unit_t *unit = parse_translation_unit();
6677 DEL_ARR_F(environment_stack);
6678 DEL_ARR_F(label_stack);
6687 * Initialize the parser.
6689 void init_parser(void)
6691 init_expression_parsers();
6692 obstack_init(&temp_obst);
6694 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6695 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6699 * Terminate the parser.
6701 void exit_parser(void)
6703 obstack_free(&temp_obst, NULL);