array sizes are determined correctly from initializer again
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "diagnostic.h"
8 #include "format_check.h"
9 #include "parser.h"
10 #include "lexer.h"
11 #include "token_t.h"
12 #include "types.h"
13 #include "type_t.h"
14 #include "type_hash.h"
15 #include "ast_t.h"
16 #include "lang_features.h"
17 #include "warning.h"
18 #include "adt/bitfiddle.h"
19 #include "adt/error.h"
20 #include "adt/array.h"
21
22 //#define PRINT_TOKENS
23 #define MAX_LOOKAHEAD 2
24
25 typedef struct {
26         declaration_t *old_declaration;
27         symbol_t      *symbol;
28         unsigned short namespc;
29 } stack_entry_t;
30
31 typedef struct declaration_specifiers_t  declaration_specifiers_t;
32 struct declaration_specifiers_t {
33         source_position_t  source_position;
34         unsigned char      storage_class;
35         bool               is_inline;
36         decl_modifiers_t   decl_modifiers;
37         type_t            *type;
38 };
39
40 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
41
42 static token_t             token;
43 static token_t             lookahead_buffer[MAX_LOOKAHEAD];
44 static int                 lookahead_bufpos;
45 static stack_entry_t      *environment_stack = NULL;
46 static stack_entry_t      *label_stack       = NULL;
47 static scope_t            *global_scope      = NULL;
48 static scope_t            *scope             = NULL;
49 static declaration_t      *last_declaration  = NULL;
50 static declaration_t      *current_function  = NULL;
51 static switch_statement_t *current_switch    = NULL;
52 static statement_t        *current_loop      = NULL;
53 static goto_statement_t   *goto_first        = NULL;
54 static goto_statement_t   *goto_last         = NULL;
55 static label_statement_t  *label_first       = NULL;
56 static label_statement_t  *label_last        = NULL;
57 static struct obstack      temp_obst;
58
59 /** The current source position. */
60 #define HERE token.source_position
61
62 static type_t *type_valist;
63
64 static statement_t *parse_compound_statement(void);
65 static statement_t *parse_statement(void);
66
67 static expression_t *parse_sub_expression(unsigned precedence);
68 static expression_t *parse_expression(void);
69 static type_t       *parse_typename(void);
70
71 static void parse_compound_type_entries(declaration_t *compound_declaration);
72 static declaration_t *parse_declarator(
73                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
74 static declaration_t *record_declaration(declaration_t *declaration);
75
76 static void semantic_comparison(binary_expression_t *expression);
77
78 #define STORAGE_CLASSES     \
79         case T_typedef:         \
80         case T_extern:          \
81         case T_static:          \
82         case T_auto:            \
83         case T_register:
84
85 #define TYPE_QUALIFIERS     \
86         case T_const:           \
87         case T_restrict:        \
88         case T_volatile:        \
89         case T_inline:          \
90         case T_forceinline:
91
92 #ifdef PROVIDE_COMPLEX
93 #define COMPLEX_SPECIFIERS  \
94         case T__Complex:
95 #define IMAGINARY_SPECIFIERS \
96         case T__Imaginary:
97 #else
98 #define COMPLEX_SPECIFIERS
99 #define IMAGINARY_SPECIFIERS
100 #endif
101
102 #define TYPE_SPECIFIERS       \
103         case T_void:              \
104         case T_char:              \
105         case T_short:             \
106         case T_int:               \
107         case T_long:              \
108         case T_float:             \
109         case T_double:            \
110         case T_signed:            \
111         case T_unsigned:          \
112         case T__Bool:             \
113         case T_struct:            \
114         case T_union:             \
115         case T_enum:              \
116         case T___typeof__:        \
117         case T___builtin_va_list: \
118         COMPLEX_SPECIFIERS        \
119         IMAGINARY_SPECIFIERS
120
121 #define DECLARATION_START   \
122         STORAGE_CLASSES         \
123         TYPE_QUALIFIERS         \
124         TYPE_SPECIFIERS
125
126 #define TYPENAME_START      \
127         TYPE_QUALIFIERS         \
128         TYPE_SPECIFIERS
129
130 /**
131  * Allocate an AST node with given size and
132  * initialize all fields with zero.
133  */
134 static void *allocate_ast_zero(size_t size)
135 {
136         void *res = allocate_ast(size);
137         memset(res, 0, size);
138         return res;
139 }
140
141 static declaration_t *allocate_declaration_zero(void)
142 {
143         declaration_t *declaration = allocate_ast_zero(sizeof(declaration_t));
144         declaration->type = type_error_type;
145         return declaration;
146 }
147
148 /**
149  * Returns the size of a statement node.
150  *
151  * @param kind  the statement kind
152  */
153 static size_t get_statement_struct_size(statement_kind_t kind)
154 {
155         static const size_t sizes[] = {
156                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
157                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
158                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
159                 [STATEMENT_IF]          = sizeof(if_statement_t),
160                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
161                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
162                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
163                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
164                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
165                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
166                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
167                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
168                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
169                 [STATEMENT_FOR]         = sizeof(for_statement_t),
170                 [STATEMENT_ASM]         = sizeof(asm_statement_t)
171         };
172         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
173         assert(sizes[kind] != 0);
174         return sizes[kind];
175 }
176
177 /**
178  * Allocate a statement node of given kind and initialize all
179  * fields with zero.
180  */
181 static statement_t *allocate_statement_zero(statement_kind_t kind)
182 {
183         size_t       size = get_statement_struct_size(kind);
184         statement_t *res  = allocate_ast_zero(size);
185
186         res->base.kind = kind;
187         return res;
188 }
189
190 /**
191  * Returns the size of an expression node.
192  *
193  * @param kind  the expression kind
194  */
195 static size_t get_expression_struct_size(expression_kind_t kind)
196 {
197         static const size_t sizes[] = {
198                 [EXPR_INVALID]             = sizeof(expression_base_t),
199                 [EXPR_REFERENCE]           = sizeof(reference_expression_t),
200                 [EXPR_CONST]               = sizeof(const_expression_t),
201                 [EXPR_CHAR_CONST]          = sizeof(const_expression_t),
202                 [EXPR_STRING_LITERAL]      = sizeof(string_literal_expression_t),
203                 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
204                 [EXPR_COMPOUND_LITERAL]    = sizeof(compound_literal_expression_t),
205                 [EXPR_CALL]                = sizeof(call_expression_t),
206                 [EXPR_UNARY_FIRST]         = sizeof(unary_expression_t),
207                 [EXPR_BINARY_FIRST]        = sizeof(binary_expression_t),
208                 [EXPR_CONDITIONAL]         = sizeof(conditional_expression_t),
209                 [EXPR_SELECT]              = sizeof(select_expression_t),
210                 [EXPR_ARRAY_ACCESS]        = sizeof(array_access_expression_t),
211                 [EXPR_SIZEOF]              = sizeof(typeprop_expression_t),
212                 [EXPR_ALIGNOF]             = sizeof(typeprop_expression_t),
213                 [EXPR_CLASSIFY_TYPE]       = sizeof(classify_type_expression_t),
214                 [EXPR_FUNCTION]            = sizeof(string_literal_expression_t),
215                 [EXPR_PRETTY_FUNCTION]     = sizeof(string_literal_expression_t),
216                 [EXPR_BUILTIN_SYMBOL]      = sizeof(builtin_symbol_expression_t),
217                 [EXPR_BUILTIN_CONSTANT_P]  = sizeof(builtin_constant_expression_t),
218                 [EXPR_BUILTIN_PREFETCH]    = sizeof(builtin_prefetch_expression_t),
219                 [EXPR_OFFSETOF]            = sizeof(offsetof_expression_t),
220                 [EXPR_VA_START]            = sizeof(va_start_expression_t),
221                 [EXPR_VA_ARG]              = sizeof(va_arg_expression_t),
222                 [EXPR_STATEMENT]           = sizeof(statement_expression_t),
223         };
224         if(kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
225                 return sizes[EXPR_UNARY_FIRST];
226         }
227         if(kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
228                 return sizes[EXPR_BINARY_FIRST];
229         }
230         assert(kind <= sizeof(sizes) / sizeof(sizes[0]));
231         assert(sizes[kind] != 0);
232         return sizes[kind];
233 }
234
235 /**
236  * Allocate an expression node of given kind and initialize all
237  * fields with zero.
238  */
239 static expression_t *allocate_expression_zero(expression_kind_t kind)
240 {
241         size_t        size = get_expression_struct_size(kind);
242         expression_t *res  = allocate_ast_zero(size);
243
244         res->base.kind = kind;
245         res->base.type = type_error_type;
246         return res;
247 }
248
249 /**
250  * Returns the size of a type node.
251  *
252  * @param kind  the type kind
253  */
254 static size_t get_type_struct_size(type_kind_t kind)
255 {
256         static const size_t sizes[] = {
257                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
258                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
259                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
260                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
261                 [TYPE_ENUM]            = sizeof(enum_type_t),
262                 [TYPE_FUNCTION]        = sizeof(function_type_t),
263                 [TYPE_POINTER]         = sizeof(pointer_type_t),
264                 [TYPE_ARRAY]           = sizeof(array_type_t),
265                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
266                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
267                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
268         };
269         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
270         assert(kind <= TYPE_TYPEOF);
271         assert(sizes[kind] != 0);
272         return sizes[kind];
273 }
274
275 /**
276  * Allocate a type node of given kind and initialize all
277  * fields with zero.
278  */
279 static type_t *allocate_type_zero(type_kind_t kind, source_position_t source_position)
280 {
281         size_t  size = get_type_struct_size(kind);
282         type_t *res  = obstack_alloc(type_obst, size);
283         memset(res, 0, size);
284
285         res->base.kind            = kind;
286         res->base.source_position = source_position;
287         return res;
288 }
289
290 /**
291  * Returns the size of an initializer node.
292  *
293  * @param kind  the initializer kind
294  */
295 static size_t get_initializer_size(initializer_kind_t kind)
296 {
297         static const size_t sizes[] = {
298                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
299                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
300                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
301                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
302                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
303         };
304         assert(kind < sizeof(sizes) / sizeof(*sizes));
305         assert(sizes[kind] != 0);
306         return sizes[kind];
307 }
308
309 /**
310  * Allocate an initializer node of given kind and initialize all
311  * fields with zero.
312  */
313 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
314 {
315         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
316         result->kind          = kind;
317
318         return result;
319 }
320
321 /**
322  * Free a type from the type obstack.
323  */
324 static void free_type(void *type)
325 {
326         obstack_free(type_obst, type);
327 }
328
329 /**
330  * Returns the index of the top element of the environment stack.
331  */
332 static size_t environment_top(void)
333 {
334         return ARR_LEN(environment_stack);
335 }
336
337 /**
338  * Returns the index of the top element of the label stack.
339  */
340 static size_t label_top(void)
341 {
342         return ARR_LEN(label_stack);
343 }
344
345
346 /**
347  * Return the next token.
348  */
349 static inline void next_token(void)
350 {
351         token                              = lookahead_buffer[lookahead_bufpos];
352         lookahead_buffer[lookahead_bufpos] = lexer_token;
353         lexer_next_token();
354
355         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
356
357 #ifdef PRINT_TOKENS
358         print_token(stderr, &token);
359         fprintf(stderr, "\n");
360 #endif
361 }
362
363 /**
364  * Return the next token with a given lookahead.
365  */
366 static inline const token_t *look_ahead(int num)
367 {
368         assert(num > 0 && num <= MAX_LOOKAHEAD);
369         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
370         return &lookahead_buffer[pos];
371 }
372
373 #define eat(token_type)  do { assert(token.type == token_type); next_token(); } while(0)
374
375 /**
376  * Report a parse error because an expected token was not found.
377  */
378 static void parse_error_expected(const char *message, ...)
379 {
380         if(message != NULL) {
381                 errorf(HERE, "%s", message);
382         }
383         va_list ap;
384         va_start(ap, message);
385         errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
386         va_end(ap);
387 }
388
389 /**
390  * Report a type error.
391  */
392 static void type_error(const char *msg, const source_position_t source_position,
393                        type_t *type)
394 {
395         errorf(source_position, "%s, but found type '%T'", msg, type);
396 }
397
398 /**
399  * Report an incompatible type.
400  */
401 static void type_error_incompatible(const char *msg,
402                 const source_position_t source_position, type_t *type1, type_t *type2)
403 {
404         errorf(source_position, "%s, incompatible types: '%T' - '%T'", msg, type1, type2);
405 }
406
407 /**
408  * Eat an complete block, ie. '{ ... }'.
409  */
410 static void eat_block(void)
411 {
412         if(token.type == '{')
413                 next_token();
414
415         while(token.type != '}') {
416                 if(token.type == T_EOF)
417                         return;
418                 if(token.type == '{') {
419                         eat_block();
420                         continue;
421                 }
422                 next_token();
423         }
424         eat('}');
425 }
426
427 /**
428  * Eat a statement until an ';' token.
429  */
430 static void eat_statement(void)
431 {
432         while(token.type != ';') {
433                 if(token.type == T_EOF)
434                         return;
435                 if(token.type == '}')
436                         return;
437                 if(token.type == '{') {
438                         eat_block();
439                         continue;
440                 }
441                 next_token();
442         }
443         eat(';');
444 }
445
446 /**
447  * Eat a parenthesed term, ie. '( ... )'.
448  */
449 static void eat_paren(void)
450 {
451         if(token.type == '(')
452                 next_token();
453
454         while(token.type != ')') {
455                 if(token.type == T_EOF)
456                         return;
457                 if(token.type == ')' || token.type == ';' || token.type == '}') {
458                         return;
459                 }
460                 if(token.type == '(') {
461                         eat_paren();
462                         continue;
463                 }
464                 if(token.type == '{') {
465                         eat_block();
466                         continue;
467                 }
468                 next_token();
469         }
470         eat(')');
471 }
472
473 #define expect(expected)                           \
474         do {                                           \
475     if(UNLIKELY(token.type != (expected))) {       \
476         parse_error_expected(NULL, (expected), 0); \
477         eat_statement();                           \
478         return NULL;                               \
479     }                                              \
480     next_token();                                  \
481         } while(0)
482
483 #define expect_block(expected)                     \
484         do {                                           \
485     if(UNLIKELY(token.type != (expected))) {       \
486         parse_error_expected(NULL, (expected), 0); \
487         eat_block();                               \
488         return NULL;                               \
489     }                                              \
490     next_token();                                  \
491         } while(0)
492
493 #define expect_void(expected)                      \
494         do {                                           \
495     if(UNLIKELY(token.type != (expected))) {       \
496         parse_error_expected(NULL, (expected), 0); \
497         eat_statement();                           \
498         return;                                    \
499     }                                              \
500     next_token();                                  \
501     } while(0)
502
503 static void set_scope(scope_t *new_scope)
504 {
505         if(scope != NULL) {
506                 scope->last_declaration = last_declaration;
507         }
508         scope = new_scope;
509
510         last_declaration = new_scope->last_declaration;
511 }
512
513 /**
514  * Search a symbol in a given namespace and returns its declaration or
515  * NULL if this symbol was not found.
516  */
517 static declaration_t *get_declaration(const symbol_t *const symbol, const namespace_t namespc)
518 {
519         declaration_t *declaration = symbol->declaration;
520         for( ; declaration != NULL; declaration = declaration->symbol_next) {
521                 if(declaration->namespc == namespc)
522                         return declaration;
523         }
524
525         return NULL;
526 }
527
528 /**
529  * pushs an environment_entry on the environment stack and links the
530  * corresponding symbol to the new entry
531  */
532 static void stack_push(stack_entry_t **stack_ptr, declaration_t *declaration)
533 {
534         symbol_t    *symbol  = declaration->symbol;
535         namespace_t  namespc = (namespace_t) declaration->namespc;
536
537         /* replace/add declaration into declaration list of the symbol */
538         declaration_t *iter = symbol->declaration;
539         if (iter == NULL) {
540                 symbol->declaration = declaration;
541         } else {
542                 declaration_t *iter_last = NULL;
543                 for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
544                         /* replace an entry? */
545                         if(iter->namespc == namespc) {
546                                 if(iter_last == NULL) {
547                                         symbol->declaration = declaration;
548                                 } else {
549                                         iter_last->symbol_next = declaration;
550                                 }
551                                 declaration->symbol_next = iter->symbol_next;
552                                 break;
553                         }
554                 }
555                 if(iter == NULL) {
556                         assert(iter_last->symbol_next == NULL);
557                         iter_last->symbol_next = declaration;
558                 }
559         }
560
561         /* remember old declaration */
562         stack_entry_t entry;
563         entry.symbol          = symbol;
564         entry.old_declaration = iter;
565         entry.namespc         = (unsigned short) namespc;
566         ARR_APP1(stack_entry_t, *stack_ptr, entry);
567 }
568
569 static void environment_push(declaration_t *declaration)
570 {
571         assert(declaration->source_position.input_name != NULL);
572         assert(declaration->parent_scope != NULL);
573         stack_push(&environment_stack, declaration);
574 }
575
576 static void label_push(declaration_t *declaration)
577 {
578         declaration->parent_scope = &current_function->scope;
579         stack_push(&label_stack, declaration);
580 }
581
582 /**
583  * pops symbols from the environment stack until @p new_top is the top element
584  */
585 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
586 {
587         stack_entry_t *stack = *stack_ptr;
588         size_t         top   = ARR_LEN(stack);
589         size_t         i;
590
591         assert(new_top <= top);
592         if(new_top == top)
593                 return;
594
595         for(i = top; i > new_top; --i) {
596                 stack_entry_t *entry = &stack[i - 1];
597
598                 declaration_t *old_declaration = entry->old_declaration;
599                 symbol_t      *symbol          = entry->symbol;
600                 namespace_t    namespc         = (namespace_t)entry->namespc;
601
602                 /* replace/remove declaration */
603                 declaration_t *declaration = symbol->declaration;
604                 assert(declaration != NULL);
605                 if(declaration->namespc == namespc) {
606                         if(old_declaration == NULL) {
607                                 symbol->declaration = declaration->symbol_next;
608                         } else {
609                                 symbol->declaration = old_declaration;
610                         }
611                 } else {
612                         declaration_t *iter_last = declaration;
613                         declaration_t *iter      = declaration->symbol_next;
614                         for( ; iter != NULL; iter_last = iter, iter = iter->symbol_next) {
615                                 /* replace an entry? */
616                                 if(iter->namespc == namespc) {
617                                         assert(iter_last != NULL);
618                                         iter_last->symbol_next = old_declaration;
619                                         if(old_declaration != NULL) {
620                                                 old_declaration->symbol_next = iter->symbol_next;
621                                         }
622                                         break;
623                                 }
624                         }
625                         assert(iter != NULL);
626                 }
627         }
628
629         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
630 }
631
632 static void environment_pop_to(size_t new_top)
633 {
634         stack_pop_to(&environment_stack, new_top);
635 }
636
637 static void label_pop_to(size_t new_top)
638 {
639         stack_pop_to(&label_stack, new_top);
640 }
641
642
643 static int get_rank(const type_t *type)
644 {
645         assert(!is_typeref(type));
646         /* The C-standard allows promoting to int or unsigned int (see Â§ 7.2.2
647          * and esp. footnote 108). However we can't fold constants (yet), so we
648          * can't decide whether unsigned int is possible, while int always works.
649          * (unsigned int would be preferable when possible... for stuff like
650          *  struct { enum { ... } bla : 4; } ) */
651         if(type->kind == TYPE_ENUM)
652                 return ATOMIC_TYPE_INT;
653
654         assert(type->kind == TYPE_ATOMIC);
655         return type->atomic.akind;
656 }
657
658 static type_t *promote_integer(type_t *type)
659 {
660         if(type->kind == TYPE_BITFIELD)
661                 type = type->bitfield.base;
662
663         if(get_rank(type) < ATOMIC_TYPE_INT)
664                 type = type_int;
665
666         return type;
667 }
668
669 /**
670  * Create a cast expression.
671  *
672  * @param expression  the expression to cast
673  * @param dest_type   the destination type
674  */
675 static expression_t *create_cast_expression(expression_t *expression,
676                                             type_t *dest_type)
677 {
678         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
679
680         cast->unary.value = expression;
681         cast->base.type   = dest_type;
682
683         return cast;
684 }
685
686 /**
687  * Check if a given expression represents the 0 pointer constant.
688  */
689 static bool is_null_pointer_constant(const expression_t *expression)
690 {
691         /* skip void* cast */
692         if(expression->kind == EXPR_UNARY_CAST
693                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
694                 expression = expression->unary.value;
695         }
696
697         /* TODO: not correct yet, should be any constant integer expression
698          * which evaluates to 0 */
699         if (expression->kind != EXPR_CONST)
700                 return false;
701
702         type_t *const type = skip_typeref(expression->base.type);
703         if (!is_type_integer(type))
704                 return false;
705
706         return expression->conste.v.int_value == 0;
707 }
708
709 /**
710  * Create an implicit cast expression.
711  *
712  * @param expression  the expression to cast
713  * @param dest_type   the destination type
714  */
715 static expression_t *create_implicit_cast(expression_t *expression,
716                                           type_t *dest_type)
717 {
718         type_t *const source_type = expression->base.type;
719
720         if (source_type == dest_type)
721                 return expression;
722
723         return create_cast_expression(expression, dest_type);
724 }
725
726 /** Implements the rules from Â§ 6.5.16.1 */
727 static type_t *semantic_assign(type_t *orig_type_left,
728                             const expression_t *const right,
729                             const char *context)
730 {
731         type_t *const orig_type_right = right->base.type;
732         type_t *const type_left       = skip_typeref(orig_type_left);
733         type_t *const type_right      = skip_typeref(orig_type_right);
734
735         if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
736             (is_type_pointer(type_left) && is_null_pointer_constant(right)) ||
737             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
738                 && is_type_pointer(type_right))) {
739                 return orig_type_left;
740         }
741
742         if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
743                 type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
744                 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
745
746                 /* the left type has all qualifiers from the right type */
747                 unsigned missing_qualifiers
748                         = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
749                 if(missing_qualifiers != 0) {
750                         errorf(HERE, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointed-to type", type_left, context, type_right, missing_qualifiers);
751                         return orig_type_left;
752                 }
753
754                 points_to_left  = get_unqualified_type(points_to_left);
755                 points_to_right = get_unqualified_type(points_to_right);
756
757                 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID) ||
758                                 is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
759                         return orig_type_left;
760                 }
761
762                 if (!types_compatible(points_to_left, points_to_right)) {
763                         warningf(right->base.source_position,
764                                 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
765                                 orig_type_left, context, right, orig_type_right);
766                 }
767
768                 return orig_type_left;
769         }
770
771         if ((is_type_compound(type_left)  && is_type_compound(type_right))
772                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
773                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
774                 type_t *const unqual_type_right = get_unqualified_type(type_right);
775                 if (types_compatible(unqual_type_left, unqual_type_right)) {
776                         return orig_type_left;
777                 }
778         }
779
780         if (!is_type_valid(type_left))
781                 return type_left;
782
783         if (!is_type_valid(type_right))
784                 return orig_type_right;
785
786         return NULL;
787 }
788
789 static expression_t *parse_constant_expression(void)
790 {
791         /* start parsing at precedence 7 (conditional expression) */
792         expression_t *result = parse_sub_expression(7);
793
794         if(!is_constant_expression(result)) {
795                 errorf(result->base.source_position, "expression '%E' is not constant\n", result);
796         }
797
798         return result;
799 }
800
801 static expression_t *parse_assignment_expression(void)
802 {
803         /* start parsing at precedence 2 (assignment expression) */
804         return parse_sub_expression(2);
805 }
806
807 static type_t *make_global_typedef(const char *name, type_t *type)
808 {
809         symbol_t *const symbol       = symbol_table_insert(name);
810
811         declaration_t *const declaration = allocate_declaration_zero();
812         declaration->namespc         = NAMESPACE_NORMAL;
813         declaration->storage_class   = STORAGE_CLASS_TYPEDEF;
814         declaration->type            = type;
815         declaration->symbol          = symbol;
816         declaration->source_position = builtin_source_position;
817
818         record_declaration(declaration);
819
820         type_t *typedef_type               = allocate_type_zero(TYPE_TYPEDEF, builtin_source_position);
821         typedef_type->typedeft.declaration = declaration;
822
823         return typedef_type;
824 }
825
826 static string_t parse_string_literals(void)
827 {
828         assert(token.type == T_STRING_LITERAL);
829         string_t result = token.v.string;
830
831         next_token();
832
833         while (token.type == T_STRING_LITERAL) {
834                 result = concat_strings(&result, &token.v.string);
835                 next_token();
836         }
837
838         return result;
839 }
840
841 static void parse_attributes(void)
842 {
843         while(true) {
844                 switch(token.type) {
845                 case T___attribute__: {
846                         next_token();
847
848                         expect_void('(');
849                         int depth = 1;
850                         while(depth > 0) {
851                                 switch(token.type) {
852                                 case T_EOF:
853                                         errorf(HERE, "EOF while parsing attribute");
854                                         break;
855                                 case '(':
856                                         next_token();
857                                         depth++;
858                                         break;
859                                 case ')':
860                                         next_token();
861                                         depth--;
862                                         break;
863                                 default:
864                                         next_token();
865                                 }
866                         }
867                         break;
868                 }
869                 case T_asm:
870                         next_token();
871                         expect_void('(');
872                         if(token.type != T_STRING_LITERAL) {
873                                 parse_error_expected("while parsing assembler attribute",
874                                                      T_STRING_LITERAL);
875                                 eat_paren();
876                                 break;
877                         } else {
878                                 parse_string_literals();
879                         }
880                         expect_void(')');
881                         break;
882                 default:
883                         goto attributes_finished;
884                 }
885         }
886
887 attributes_finished:
888         ;
889 }
890
891 static designator_t *parse_designation(void)
892 {
893         designator_t *result = NULL;
894         designator_t *last   = NULL;
895
896         while(true) {
897                 designator_t *designator;
898                 switch(token.type) {
899                 case '[':
900                         designator = allocate_ast_zero(sizeof(designator[0]));
901                         designator->source_position = token.source_position;
902                         next_token();
903                         designator->array_index = parse_constant_expression();
904                         expect(']');
905                         break;
906                 case '.':
907                         designator = allocate_ast_zero(sizeof(designator[0]));
908                         designator->source_position = token.source_position;
909                         next_token();
910                         if(token.type != T_IDENTIFIER) {
911                                 parse_error_expected("while parsing designator",
912                                                      T_IDENTIFIER, 0);
913                                 return NULL;
914                         }
915                         designator->symbol = token.v.symbol;
916                         next_token();
917                         break;
918                 default:
919                         expect('=');
920                         return result;
921                 }
922
923                 assert(designator != NULL);
924                 if(last != NULL) {
925                         last->next = designator;
926                 } else {
927                         result = designator;
928                 }
929                 last = designator;
930         }
931 }
932
933 static initializer_t *initializer_from_string(array_type_t *type,
934                                               const string_t *const string)
935 {
936         /* TODO: check len vs. size of array type */
937         (void) type;
938
939         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
940         initializer->string.string = *string;
941
942         return initializer;
943 }
944
945 static initializer_t *initializer_from_wide_string(array_type_t *const type,
946                                                    wide_string_t *const string)
947 {
948         /* TODO: check len vs. size of array type */
949         (void) type;
950
951         initializer_t *const initializer =
952                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
953         initializer->wide_string.string = *string;
954
955         return initializer;
956 }
957
958 static initializer_t *initializer_from_expression(type_t *orig_type,
959                                                   expression_t *expression)
960 {
961         /* TODO check that expression is a constant expression */
962
963         /* Â§ 6.7.8.14/15 char array may be initialized by string literals */
964         type_t *type           = skip_typeref(orig_type);
965         type_t *expr_type_orig = expression->base.type;
966         type_t *expr_type      = skip_typeref(expr_type_orig);
967         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
968                 array_type_t *const array_type   = &type->array;
969                 type_t       *const element_type = skip_typeref(array_type->element_type);
970
971                 if (element_type->kind == TYPE_ATOMIC) {
972                         atomic_type_kind_t akind = element_type->atomic.akind;
973                         switch (expression->kind) {
974                                 case EXPR_STRING_LITERAL:
975                                         if (akind == ATOMIC_TYPE_CHAR
976                                                         || akind == ATOMIC_TYPE_SCHAR
977                                                         || akind == ATOMIC_TYPE_UCHAR) {
978                                                 return initializer_from_string(array_type,
979                                                         &expression->string.value);
980                                         }
981
982                                 case EXPR_WIDE_STRING_LITERAL: {
983                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
984                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
985                                                 return initializer_from_wide_string(array_type,
986                                                         &expression->wide_string.value);
987                                         }
988                                 }
989
990                                 default:
991                                         break;
992                         }
993                 }
994         }
995
996         type_t *const res_type = semantic_assign(type, expression, "initializer");
997         if (res_type == NULL)
998                 return NULL;
999
1000         initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1001         result->value.value = create_implicit_cast(expression, res_type);
1002
1003         return result;
1004 }
1005
1006 static initializer_t *parse_scalar_initializer(type_t *type,
1007                                                bool must_be_constant)
1008 {
1009         /* there might be extra {} hierarchies */
1010         int braces = 0;
1011         while(token.type == '{') {
1012                 next_token();
1013                 if(braces == 0) {
1014                         warningf(HERE, "extra curly braces around scalar initializer");
1015                 }
1016                 braces++;
1017         }
1018
1019         expression_t *expression = parse_assignment_expression();
1020         if(must_be_constant && !is_constant_expression(expression)) {
1021                 errorf(expression->base.source_position,
1022                        "Initialisation expression '%E' is not constant\n",
1023                        expression);
1024         }
1025
1026         initializer_t *initializer = initializer_from_expression(type, expression);
1027
1028         if(initializer == NULL) {
1029                 errorf(expression->base.source_position,
1030                        "expression '%E' doesn't match expected type '%T'",
1031                        expression, type);
1032                 /* TODO */
1033                 return NULL;
1034         }
1035
1036         bool additional_warning_displayed = false;
1037         while(braces > 0) {
1038                 if(token.type == ',') {
1039                         next_token();
1040                 }
1041                 if(token.type != '}') {
1042                         if(!additional_warning_displayed) {
1043                                 warningf(HERE, "additional elements in scalar initializer");
1044                                 additional_warning_displayed = true;
1045                         }
1046                 }
1047                 eat_block();
1048                 braces--;
1049         }
1050
1051         return initializer;
1052 }
1053
1054 typedef struct type_path_entry_t type_path_entry_t;
1055 struct type_path_entry_t {
1056         type_t *type;
1057         union {
1058                 size_t         index;
1059                 declaration_t *compound_entry;
1060         } v;
1061 };
1062
1063 typedef struct type_path_t type_path_t;
1064 struct type_path_t {
1065         type_path_entry_t *path;
1066         type_t            *top_type;     /**< type of the element the path points */
1067         size_t             max_index;    /**< largest index in outermost array */
1068         bool               invalid;
1069 };
1070
1071 static __attribute__((unused)) void debug_print_type_path(
1072                 const type_path_t *path)
1073 {
1074         size_t len = ARR_LEN(path->path);
1075
1076         if(path->invalid) {
1077                 fprintf(stderr, "invalid path");
1078                 return;
1079         }
1080
1081         for(size_t i = 0; i < len; ++i) {
1082                 const type_path_entry_t *entry = & path->path[i];
1083
1084                 type_t *type = skip_typeref(entry->type);
1085                 if(is_type_compound(type)) {
1086                         fprintf(stderr, ".%s", entry->v.compound_entry->symbol->string);
1087                 } else if(is_type_array(type)) {
1088                         fprintf(stderr, "[%u]", entry->v.index);
1089                 } else {
1090                         fprintf(stderr, "-INVALID-");
1091                 }
1092         }
1093         fprintf(stderr, "  (");
1094         print_type(path->top_type);
1095         fprintf(stderr, ")");
1096 }
1097
1098 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1099 {
1100         size_t len = ARR_LEN(path->path);
1101         assert(len > 0);
1102         return & path->path[len-1];
1103 }
1104
1105 static type_path_entry_t *append_to_type_path(type_path_t *path)
1106 {
1107         size_t len = ARR_LEN(path->path);
1108         ARR_RESIZE(type_path_entry_t, path->path, len+1);
1109
1110         type_path_entry_t *result = & path->path[len];
1111         memset(result, 0, sizeof(result[0]));
1112         return result;
1113 }
1114
1115 static void descend_into_subtype(type_path_t *path)
1116 {
1117         type_t *orig_top_type = path->top_type;
1118         type_t *top_type      = skip_typeref(orig_top_type);
1119
1120         assert(is_type_compound(top_type) || is_type_array(top_type));
1121
1122         type_path_entry_t *top = append_to_type_path(path);
1123         top->type              = top_type;
1124
1125         if(is_type_compound(top_type)) {
1126                 declaration_t *declaration = top_type->compound.declaration;
1127                 declaration_t *entry       = declaration->scope.declarations;
1128
1129                 top->v.compound_entry = entry;
1130                 path->top_type        = entry->type;
1131         } else {
1132                 assert(is_type_array(top_type));
1133
1134                 top->v.index   = 0;
1135                 path->top_type = top_type->array.element_type;
1136         }
1137 }
1138
1139 static void ascend_from_subtype(type_path_t *path)
1140 {
1141         type_path_entry_t *top = get_type_path_top(path);
1142
1143         path->top_type = top->type;
1144
1145         size_t len = ARR_LEN(path->path);
1146         ARR_RESIZE(type_path_entry_t, path->path, len-1);
1147 }
1148
1149 static void ascend_to(type_path_t *path, size_t top_path_level)
1150 {
1151         size_t len = ARR_LEN(path->path);
1152         assert(len >= top_path_level);
1153
1154         while(len > top_path_level) {
1155                 ascend_from_subtype(path);
1156                 len = ARR_LEN(path->path);
1157         }
1158 }
1159
1160 static bool walk_designator(type_path_t *path, const designator_t *designator,
1161                             bool used_in_offsetof)
1162 {
1163         for( ; designator != NULL; designator = designator->next) {
1164                 type_path_entry_t *top       = get_type_path_top(path);
1165                 type_t            *orig_type = top->type;
1166
1167                 type_t *type = skip_typeref(orig_type);
1168
1169                 if(designator->symbol != NULL) {
1170                         symbol_t *symbol = designator->symbol;
1171                         if(!is_type_compound(type)) {
1172                                 if(is_type_valid(type)) {
1173                                         errorf(designator->source_position,
1174                                                "'.%Y' designator used for non-compound type '%T'",
1175                                                symbol, orig_type);
1176                                 }
1177                                 goto failed;
1178                         }
1179
1180                         declaration_t *declaration = type->compound.declaration;
1181                         declaration_t *iter        = declaration->scope.declarations;
1182                         for( ; iter != NULL; iter = iter->next) {
1183                                 if(iter->symbol == symbol) {
1184                                         break;
1185                                 }
1186                         }
1187                         if(iter == NULL) {
1188                                 errorf(designator->source_position,
1189                                        "'%T' has no member named '%Y'", orig_type, symbol);
1190                                 goto failed;
1191                         }
1192                         if(used_in_offsetof) {
1193                                 type_t *real_type = skip_typeref(iter->type);
1194                                 if(real_type->kind == TYPE_BITFIELD) {
1195                                         errorf(designator->source_position,
1196                                                "offsetof designator '%Y' may not specify bitfield",
1197                                                symbol);
1198                                         goto failed;
1199                                 }
1200                         }
1201
1202                         top->type             = orig_type;
1203                         top->v.compound_entry = iter;
1204                         orig_type             = iter->type;
1205                 } else {
1206                         expression_t *array_index = designator->array_index;
1207                         assert(designator->array_index != NULL);
1208
1209                         if(!is_type_array(type)) {
1210                                 if(is_type_valid(type)) {
1211                                         errorf(designator->source_position,
1212                                                "[%E] designator used for non-array type '%T'",
1213                                                array_index, orig_type);
1214                                 }
1215                                 goto failed;
1216                         }
1217                         if(!is_type_valid(array_index->base.type)) {
1218                                 goto failed;
1219                         }
1220
1221                         long index = fold_constant(array_index);
1222                         if(!used_in_offsetof) {
1223                                 if(index < 0) {
1224                                         errorf(designator->source_position,
1225                                                "array index [%E] must be positive", array_index);
1226                                         goto failed;
1227                                 }
1228                                 if(type->array.size_constant == true) {
1229                                         long array_size = type->array.size;
1230                                         if(index >= array_size) {
1231                                                 errorf(designator->source_position,
1232                                                                 "designator [%E] (%d) exceeds array size %d",
1233                                                                 array_index, index, array_size);
1234                                                 goto failed;
1235                                         }
1236                                 }
1237                         }
1238
1239                         top->type    = orig_type;
1240                         top->v.index = (size_t) index;
1241                         orig_type    = type->array.element_type;
1242                 }
1243                 path->top_type = orig_type;
1244
1245                 if(designator->next != NULL) {
1246                         descend_into_subtype(path);
1247                 }
1248         }
1249
1250         path->invalid  = false;
1251         return true;
1252
1253 failed:
1254         return false;
1255 }
1256
1257 static void advance_current_object(type_path_t *path, size_t top_path_level)
1258 {
1259         if(path->invalid)
1260                 return;
1261
1262         type_path_entry_t *top = get_type_path_top(path);
1263
1264         type_t *type = skip_typeref(top->type);
1265         if(is_type_union(type)) {
1266                 /* in unions only the first element is initialized */
1267                 top->v.compound_entry = NULL;
1268         } else if(is_type_struct(type)) {
1269                 declaration_t *entry = top->v.compound_entry;
1270
1271                 entry                 = entry->next;
1272                 top->v.compound_entry = entry;
1273                 if(entry != NULL) {
1274                         path->top_type = entry->type;
1275                         return;
1276                 }
1277         } else {
1278                 assert(is_type_array(type));
1279
1280                 top->v.index++;
1281
1282                 if(!type->array.size_constant || top->v.index < type->array.size) {
1283                         return;
1284                 }
1285         }
1286
1287         /* we're past the last member of the current sub-aggregate, try if we
1288          * can ascend in the type hierarchy and continue with another subobject */
1289         size_t len = ARR_LEN(path->path);
1290
1291         if(len > top_path_level) {
1292                 ascend_from_subtype(path);
1293                 advance_current_object(path, top_path_level);
1294         } else {
1295                 path->invalid = true;
1296         }
1297 }
1298
1299 static void skip_initializers(void)
1300 {
1301         if(token.type == '{')
1302                 next_token();
1303
1304         while(token.type != '}') {
1305                 if(token.type == T_EOF)
1306                         return;
1307                 if(token.type == '{') {
1308                         eat_block();
1309                         continue;
1310                 }
1311                 next_token();
1312         }
1313 }
1314
1315 static initializer_t *parse_sub_initializer(type_path_t *path,
1316                 type_t *outer_type, size_t top_path_level, bool must_be_constant)
1317 {
1318         type_t *orig_type = path->top_type;
1319         type_t *type      = skip_typeref(orig_type);
1320
1321         /* we can't do usefull stuff if we didn't even parse the type. Skip the
1322          * initializers in this case. */
1323         if(!is_type_valid(type)) {
1324                 skip_initializers();
1325                 return NULL;
1326         }
1327
1328         initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1329
1330         while(true) {
1331                 designator_t *designator = NULL;
1332                 if(token.type == '.' || token.type == '[') {
1333                         designator = parse_designation();
1334
1335                         /* reset path to toplevel, evaluate designator from there */
1336                         ascend_to(path, top_path_level);
1337                         if(!walk_designator(path, designator, false)) {
1338                                 /* can't continue after designation error */
1339                                 goto end_error;
1340                         }
1341
1342                         initializer_t *designator_initializer
1343                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1344                         designator_initializer->designator.designator = designator;
1345                         ARR_APP1(initializer_t*, initializers, designator_initializer);
1346                 }
1347
1348                 initializer_t *sub;
1349
1350                 if(token.type == '{') {
1351                         if(is_type_scalar(type)) {
1352                                 sub = parse_scalar_initializer(type, must_be_constant);
1353                         } else {
1354                                 eat('{');
1355                                 descend_into_subtype(path);
1356
1357                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
1358                                                             must_be_constant);
1359
1360                                 ascend_from_subtype(path);
1361
1362                                 expect_block('}');
1363                         }
1364                 } else {
1365                         /* must be an expression */
1366                         expression_t *expression = parse_assignment_expression();
1367
1368                         if(must_be_constant && !is_constant_expression(expression)) {
1369                                 errorf(expression->base.source_position,
1370                                        "Initialisation expression '%E' is not constant\n",
1371                                        expression);
1372                         }
1373
1374                         /* handle { "string" } special case */
1375                         if((expression->kind == EXPR_STRING_LITERAL
1376                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
1377                                         && outer_type != NULL) {
1378                                 sub = initializer_from_expression(outer_type, expression);
1379                                 if(sub != NULL) {
1380                                         if(token.type == ',') {
1381                                                 next_token();
1382                                         }
1383                                         if(token.type != '}') {
1384                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
1385                                                                  orig_type);
1386                                         }
1387                                         /* TODO: eat , ... */
1388                                         return sub;
1389                                 }
1390                         }
1391
1392                         /* descend into subtypes until expression matches type */
1393                         while(true) {
1394                                 orig_type = path->top_type;
1395                                 type      = skip_typeref(orig_type);
1396
1397                                 sub = initializer_from_expression(orig_type, expression);
1398                                 if(sub != NULL) {
1399                                         break;
1400                                 }
1401                                 if(!is_type_valid(type)) {
1402                                         goto end_error;
1403                                 }
1404                                 if(is_type_scalar(type)) {
1405                                         errorf(expression->base.source_position,
1406                                                         "expression '%E' doesn't match expected type '%T'",
1407                                                         expression, orig_type);
1408                                         goto end_error;
1409                                 }
1410
1411                                 descend_into_subtype(path);
1412                         }
1413                 }
1414
1415                 /* update largest index of top array */
1416                 const type_path_entry_t *first      = &path->path[0];
1417                 type_t                  *first_type = first->type;
1418                 first_type                          = skip_typeref(first_type);
1419                 if(is_type_array(first_type)) {
1420                         size_t index = first->v.index;
1421                         if(index > path->max_index)
1422                                 path->max_index = index;
1423                 }
1424
1425                 /* append to initializers list */
1426                 ARR_APP1(initializer_t*, initializers, sub);
1427
1428                 if(token.type == '}') {
1429                         break;
1430                 }
1431                 expect(',');
1432                 if(token.type == '}') {
1433                         break;
1434                 }
1435
1436                 advance_current_object(path, top_path_level);
1437                 orig_type = path->top_type;
1438                 type      = skip_typeref(orig_type);
1439         }
1440
1441         size_t len  = ARR_LEN(initializers);
1442         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
1443         initializer_t *result = allocate_ast_zero(size);
1444         result->kind          = INITIALIZER_LIST;
1445         result->list.len      = len;
1446         memcpy(&result->list.initializers, initializers,
1447                len * sizeof(initializers[0]));
1448
1449         ascend_to(path, top_path_level);
1450
1451         return result;
1452
1453 end_error:
1454         skip_initializers();
1455         DEL_ARR_F(initializers);
1456         ascend_to(path, top_path_level);
1457         return NULL;
1458 }
1459
1460 typedef struct parse_initializer_env_t {
1461         type_t        *type;        /* the type of the initializer. In case of an
1462                                        array type with unspecified size this gets
1463                                        adjusted to the actual size. */
1464         initializer_t *initializer; /* initializer will be filled in here */
1465         bool           must_be_constant;
1466 } parse_initializer_env_t;
1467
1468 static void parse_initializer(parse_initializer_env_t *env)
1469 {
1470         type_t        *type   = skip_typeref(env->type);
1471         initializer_t *result = NULL;
1472         size_t         max_index;
1473
1474         if(token.type != '{') {
1475                 expression_t *expression = parse_assignment_expression();
1476
1477                 result = initializer_from_expression(type, expression);
1478                 if(result == NULL) {
1479                         errorf(HERE,
1480                                 "initializer expression '%E' of type '%T' is incompatible with type '%T'",
1481                                 expression, expression->base.type, env->type);
1482                 }
1483         } else if(is_type_scalar(type)) {
1484                 /* TODO: Â§ 6.7.8.11; eat {} without warning */
1485                 result = parse_scalar_initializer(type, env->must_be_constant);
1486
1487                 if(token.type == ',')
1488                         next_token();
1489         } else if(token.type == '{') {
1490                 next_token();
1491
1492                 type_path_t path;
1493                 memset(&path, 0, sizeof(path));
1494                 path.top_type = env->type;
1495                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
1496
1497                 descend_into_subtype(&path);
1498
1499                 result = parse_sub_initializer(&path, env->type, 1,
1500                                                env->must_be_constant);
1501
1502                 max_index = path.max_index;
1503                 DEL_ARR_F(path.path);
1504
1505                 expect_void('}');
1506         } else {
1507                 /* TODO: can this even happen? */
1508                 panic("TODO");
1509         }
1510
1511         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
1512          * the array type size */
1513         if(is_type_array(type) && type->array.size_expression == NULL
1514                         && result != NULL) {
1515                 size_t size;
1516                 switch (result->kind) {
1517                 case INITIALIZER_LIST:
1518                         size = max_index + 1;
1519                         break;
1520
1521                 case INITIALIZER_STRING:
1522                         size = result->string.string.size;
1523                         break;
1524
1525                 case INITIALIZER_WIDE_STRING:
1526                         size = result->wide_string.string.size;
1527                         break;
1528
1529                 default:
1530                         panic("invalid initializer type");
1531                 }
1532
1533                 expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
1534                 cnst->base.type          = type_size_t;
1535                 cnst->conste.v.int_value = size;
1536
1537                 type_t *new_type = duplicate_type(type);
1538
1539                 new_type->array.size_expression = cnst;
1540                 new_type->array.size_constant   = true;
1541                 new_type->array.size            = size;
1542                 env->type = new_type;
1543         }
1544
1545         env->initializer = result;
1546 }
1547
1548 static declaration_t *append_declaration(declaration_t *declaration);
1549
1550 static declaration_t *parse_compound_type_specifier(bool is_struct)
1551 {
1552         if(is_struct) {
1553                 eat(T_struct);
1554         } else {
1555                 eat(T_union);
1556         }
1557
1558         symbol_t      *symbol      = NULL;
1559         declaration_t *declaration = NULL;
1560
1561         if (token.type == T___attribute__) {
1562                 /* TODO */
1563                 parse_attributes();
1564         }
1565
1566         if(token.type == T_IDENTIFIER) {
1567                 symbol = token.v.symbol;
1568                 next_token();
1569
1570                 if(is_struct) {
1571                         declaration = get_declaration(symbol, NAMESPACE_STRUCT);
1572                 } else {
1573                         declaration = get_declaration(symbol, NAMESPACE_UNION);
1574                 }
1575         } else if(token.type != '{') {
1576                 if(is_struct) {
1577                         parse_error_expected("while parsing struct type specifier",
1578                                              T_IDENTIFIER, '{', 0);
1579                 } else {
1580                         parse_error_expected("while parsing union type specifier",
1581                                              T_IDENTIFIER, '{', 0);
1582                 }
1583
1584                 return NULL;
1585         }
1586
1587         if(declaration == NULL) {
1588                 declaration = allocate_declaration_zero();
1589                 declaration->namespc         =
1590                         (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
1591                 declaration->source_position = token.source_position;
1592                 declaration->symbol          = symbol;
1593                 declaration->parent_scope  = scope;
1594                 if (symbol != NULL) {
1595                         environment_push(declaration);
1596                 }
1597                 append_declaration(declaration);
1598         }
1599
1600         if(token.type == '{') {
1601                 if(declaration->init.is_defined) {
1602                         assert(symbol != NULL);
1603                         errorf(HERE, "multiple definitions of '%s %Y'",
1604                                is_struct ? "struct" : "union", symbol);
1605                         declaration->scope.declarations = NULL;
1606                 }
1607                 declaration->init.is_defined = true;
1608
1609                 parse_compound_type_entries(declaration);
1610                 parse_attributes();
1611         }
1612
1613         return declaration;
1614 }
1615
1616 static void parse_enum_entries(type_t *const enum_type)
1617 {
1618         eat('{');
1619
1620         if(token.type == '}') {
1621                 next_token();
1622                 errorf(HERE, "empty enum not allowed");
1623                 return;
1624         }
1625
1626         do {
1627                 if(token.type != T_IDENTIFIER) {
1628                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, 0);
1629                         eat_block();
1630                         return;
1631                 }
1632
1633                 declaration_t *const entry = allocate_declaration_zero();
1634                 entry->storage_class   = STORAGE_CLASS_ENUM_ENTRY;
1635                 entry->type            = enum_type;
1636                 entry->symbol          = token.v.symbol;
1637                 entry->source_position = token.source_position;
1638                 next_token();
1639
1640                 if(token.type == '=') {
1641                         next_token();
1642                         expression_t *value = parse_constant_expression();
1643
1644                         value = create_implicit_cast(value, enum_type);
1645                         entry->init.enum_value = value;
1646
1647                         /* TODO semantic */
1648                 }
1649
1650                 record_declaration(entry);
1651
1652                 if(token.type != ',')
1653                         break;
1654                 next_token();
1655         } while(token.type != '}');
1656
1657         expect_void('}');
1658 }
1659
1660 static type_t *parse_enum_specifier(void)
1661 {
1662         eat(T_enum);
1663
1664         declaration_t *declaration;
1665         symbol_t      *symbol;
1666
1667         if(token.type == T_IDENTIFIER) {
1668                 symbol = token.v.symbol;
1669                 next_token();
1670
1671                 declaration = get_declaration(symbol, NAMESPACE_ENUM);
1672         } else if(token.type != '{') {
1673                 parse_error_expected("while parsing enum type specifier",
1674                                      T_IDENTIFIER, '{', 0);
1675                 return NULL;
1676         } else {
1677                 declaration = NULL;
1678                 symbol      = NULL;
1679         }
1680
1681         if(declaration == NULL) {
1682                 declaration = allocate_declaration_zero();
1683                 declaration->namespc         = NAMESPACE_ENUM;
1684                 declaration->source_position = token.source_position;
1685                 declaration->symbol          = symbol;
1686                 declaration->parent_scope  = scope;
1687         }
1688
1689         type_t *const type      = allocate_type_zero(TYPE_ENUM, declaration->source_position);
1690         type->enumt.declaration = declaration;
1691
1692         if(token.type == '{') {
1693                 if(declaration->init.is_defined) {
1694                         errorf(HERE, "multiple definitions of enum %Y", symbol);
1695                 }
1696                 if (symbol != NULL) {
1697                         environment_push(declaration);
1698                 }
1699                 append_declaration(declaration);
1700                 declaration->init.is_defined = 1;
1701
1702                 parse_enum_entries(type);
1703                 parse_attributes();
1704         }
1705
1706         return type;
1707 }
1708
1709 /**
1710  * if a symbol is a typedef to another type, return true
1711  */
1712 static bool is_typedef_symbol(symbol_t *symbol)
1713 {
1714         const declaration_t *const declaration =
1715                 get_declaration(symbol, NAMESPACE_NORMAL);
1716         return
1717                 declaration != NULL &&
1718                 declaration->storage_class == STORAGE_CLASS_TYPEDEF;
1719 }
1720
1721 static type_t *parse_typeof(void)
1722 {
1723         eat(T___typeof__);
1724
1725         type_t *type;
1726
1727         expect('(');
1728
1729         expression_t *expression  = NULL;
1730
1731 restart:
1732         switch(token.type) {
1733         case T___extension__:
1734                 /* this can be a prefix to a typename or an expression */
1735                 /* we simply eat it now. */
1736                 do {
1737                         next_token();
1738                 } while(token.type == T___extension__);
1739                 goto restart;
1740
1741         case T_IDENTIFIER:
1742                 if(is_typedef_symbol(token.v.symbol)) {
1743                         type = parse_typename();
1744                 } else {
1745                         expression = parse_expression();
1746                         type       = expression->base.type;
1747                 }
1748                 break;
1749
1750         TYPENAME_START
1751                 type = parse_typename();
1752                 break;
1753
1754         default:
1755                 expression = parse_expression();
1756                 type       = expression->base.type;
1757                 break;
1758         }
1759
1760         expect(')');
1761
1762         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF, expression->base.source_position);
1763         typeof_type->typeoft.expression  = expression;
1764         typeof_type->typeoft.typeof_type = type;
1765
1766         return typeof_type;
1767 }
1768
1769 typedef enum {
1770         SPECIFIER_SIGNED    = 1 << 0,
1771         SPECIFIER_UNSIGNED  = 1 << 1,
1772         SPECIFIER_LONG      = 1 << 2,
1773         SPECIFIER_INT       = 1 << 3,
1774         SPECIFIER_DOUBLE    = 1 << 4,
1775         SPECIFIER_CHAR      = 1 << 5,
1776         SPECIFIER_SHORT     = 1 << 6,
1777         SPECIFIER_LONG_LONG = 1 << 7,
1778         SPECIFIER_FLOAT     = 1 << 8,
1779         SPECIFIER_BOOL      = 1 << 9,
1780         SPECIFIER_VOID      = 1 << 10,
1781 #ifdef PROVIDE_COMPLEX
1782         SPECIFIER_COMPLEX   = 1 << 11,
1783         SPECIFIER_IMAGINARY = 1 << 12,
1784 #endif
1785 } specifiers_t;
1786
1787 static type_t *create_builtin_type(symbol_t *const symbol,
1788                                    type_t *const real_type)
1789 {
1790         type_t *type            = allocate_type_zero(TYPE_BUILTIN, builtin_source_position);
1791         type->builtin.symbol    = symbol;
1792         type->builtin.real_type = real_type;
1793
1794         type_t *result = typehash_insert(type);
1795         if (type != result) {
1796                 free_type(type);
1797         }
1798
1799         return result;
1800 }
1801
1802 static type_t *get_typedef_type(symbol_t *symbol)
1803 {
1804         declaration_t *declaration = get_declaration(symbol, NAMESPACE_NORMAL);
1805         if(declaration == NULL
1806                         || declaration->storage_class != STORAGE_CLASS_TYPEDEF)
1807                 return NULL;
1808
1809         type_t *type               = allocate_type_zero(TYPE_TYPEDEF, declaration->source_position);
1810         type->typedeft.declaration = declaration;
1811
1812         return type;
1813 }
1814
1815 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
1816 {
1817         type_t   *type            = NULL;
1818         unsigned  type_qualifiers = 0;
1819         unsigned  type_specifiers = 0;
1820         int       newtype         = 0;
1821
1822         specifiers->source_position = token.source_position;
1823
1824         while(true) {
1825                 switch(token.type) {
1826
1827                 /* storage class */
1828 #define MATCH_STORAGE_CLASS(token, class)                                \
1829                 case token:                                                      \
1830                         if(specifiers->storage_class != STORAGE_CLASS_NONE) {        \
1831                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
1832                         }                                                            \
1833                         specifiers->storage_class = class;                           \
1834                         next_token();                                                \
1835                         break;
1836
1837                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
1838                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
1839                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
1840                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
1841                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
1842
1843                 case T___thread:
1844                         switch (specifiers->storage_class) {
1845                                 case STORAGE_CLASS_NONE:
1846                                         specifiers->storage_class = STORAGE_CLASS_THREAD;
1847                                         break;
1848
1849                                 case STORAGE_CLASS_EXTERN:
1850                                         specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
1851                                         break;
1852
1853                                 case STORAGE_CLASS_STATIC:
1854                                         specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
1855                                         break;
1856
1857                                 default:
1858                                         errorf(HERE, "multiple storage classes in declaration specifiers");
1859                                         break;
1860                         }
1861                         next_token();
1862                         break;
1863
1864                 /* type qualifiers */
1865 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
1866                 case token:                                                     \
1867                         type_qualifiers |= qualifier;                               \
1868                         next_token();                                               \
1869                         break;
1870
1871                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1872                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1873                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1874
1875                 case T___extension__:
1876                         /* TODO */
1877                         next_token();
1878                         break;
1879
1880                 /* type specifiers */
1881 #define MATCH_SPECIFIER(token, specifier, name)                         \
1882                 case token:                                                     \
1883                         next_token();                                               \
1884                         if(type_specifiers & specifier) {                           \
1885                                 errorf(HERE, "multiple " name " type specifiers given"); \
1886                         } else {                                                    \
1887                                 type_specifiers |= specifier;                           \
1888                         }                                                           \
1889                         break;
1890
1891                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void")
1892                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char")
1893                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short")
1894                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int")
1895                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float")
1896                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double")
1897                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed")
1898                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned")
1899                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool")
1900 #ifdef PROVIDE_COMPLEX
1901                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex")
1902                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary")
1903 #endif
1904                 case T_forceinline:
1905                         /* only in microsoft mode */
1906                         specifiers->decl_modifiers |= DM_FORCEINLINE;
1907
1908                 case T_inline:
1909                         next_token();
1910                         specifiers->is_inline = true;
1911                         break;
1912
1913                 case T_long:
1914                         next_token();
1915                         if(type_specifiers & SPECIFIER_LONG_LONG) {
1916                                 errorf(HERE, "multiple type specifiers given");
1917                         } else if(type_specifiers & SPECIFIER_LONG) {
1918                                 type_specifiers |= SPECIFIER_LONG_LONG;
1919                         } else {
1920                                 type_specifiers |= SPECIFIER_LONG;
1921                         }
1922                         break;
1923
1924                 case T_struct: {
1925                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT, HERE);
1926
1927                         type->compound.declaration = parse_compound_type_specifier(true);
1928                         break;
1929                 }
1930                 case T_union: {
1931                         type = allocate_type_zero(TYPE_COMPOUND_UNION, HERE);
1932
1933                         type->compound.declaration = parse_compound_type_specifier(false);
1934                         break;
1935                 }
1936                 case T_enum:
1937                         type = parse_enum_specifier();
1938                         break;
1939                 case T___typeof__:
1940                         type = parse_typeof();
1941                         break;
1942                 case T___builtin_va_list:
1943                         type = duplicate_type(type_valist);
1944                         next_token();
1945                         break;
1946
1947                 case T___attribute__:
1948                         parse_attributes();
1949                         break;
1950
1951                 case T_IDENTIFIER: {
1952                         /* only parse identifier if we haven't found a type yet */
1953                         if(type != NULL || type_specifiers != 0)
1954                                 goto finish_specifiers;
1955
1956                         type_t *typedef_type = get_typedef_type(token.v.symbol);
1957
1958                         if(typedef_type == NULL)
1959                                 goto finish_specifiers;
1960
1961                         next_token();
1962                         type = typedef_type;
1963                         break;
1964                 }
1965
1966                 /* function specifier */
1967                 default:
1968                         goto finish_specifiers;
1969                 }
1970         }
1971
1972 finish_specifiers:
1973
1974         if(type == NULL) {
1975                 atomic_type_kind_t atomic_type;
1976
1977                 /* match valid basic types */
1978                 switch(type_specifiers) {
1979                 case SPECIFIER_VOID:
1980                         atomic_type = ATOMIC_TYPE_VOID;
1981                         break;
1982                 case SPECIFIER_CHAR:
1983                         atomic_type = ATOMIC_TYPE_CHAR;
1984                         break;
1985                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
1986                         atomic_type = ATOMIC_TYPE_SCHAR;
1987                         break;
1988                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
1989                         atomic_type = ATOMIC_TYPE_UCHAR;
1990                         break;
1991                 case SPECIFIER_SHORT:
1992                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
1993                 case SPECIFIER_SHORT | SPECIFIER_INT:
1994                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1995                         atomic_type = ATOMIC_TYPE_SHORT;
1996                         break;
1997                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
1998                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
1999                         atomic_type = ATOMIC_TYPE_USHORT;
2000                         break;
2001                 case SPECIFIER_INT:
2002                 case SPECIFIER_SIGNED:
2003                 case SPECIFIER_SIGNED | SPECIFIER_INT:
2004                         atomic_type = ATOMIC_TYPE_INT;
2005                         break;
2006                 case SPECIFIER_UNSIGNED:
2007                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2008                         atomic_type = ATOMIC_TYPE_UINT;
2009                         break;
2010                 case SPECIFIER_LONG:
2011                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2012                 case SPECIFIER_LONG | SPECIFIER_INT:
2013                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2014                         atomic_type = ATOMIC_TYPE_LONG;
2015                         break;
2016                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2017                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2018                         atomic_type = ATOMIC_TYPE_ULONG;
2019                         break;
2020                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2021                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2022                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2023                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2024                         | SPECIFIER_INT:
2025                         atomic_type = ATOMIC_TYPE_LONGLONG;
2026                         break;
2027                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2028                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2029                         | SPECIFIER_INT:
2030                         atomic_type = ATOMIC_TYPE_ULONGLONG;
2031                         break;
2032                 case SPECIFIER_FLOAT:
2033                         atomic_type = ATOMIC_TYPE_FLOAT;
2034                         break;
2035                 case SPECIFIER_DOUBLE:
2036                         atomic_type = ATOMIC_TYPE_DOUBLE;
2037                         break;
2038                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2039                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2040                         break;
2041                 case SPECIFIER_BOOL:
2042                         atomic_type = ATOMIC_TYPE_BOOL;
2043                         break;
2044 #ifdef PROVIDE_COMPLEX
2045                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2046                         atomic_type = ATOMIC_TYPE_FLOAT_COMPLEX;
2047                         break;
2048                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2049                         atomic_type = ATOMIC_TYPE_DOUBLE_COMPLEX;
2050                         break;
2051                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2052                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_COMPLEX;
2053                         break;
2054                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2055                         atomic_type = ATOMIC_TYPE_FLOAT_IMAGINARY;
2056                         break;
2057                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2058                         atomic_type = ATOMIC_TYPE_DOUBLE_IMAGINARY;
2059                         break;
2060                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2061                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE_IMAGINARY;
2062                         break;
2063 #endif
2064                 default:
2065                         /* invalid specifier combination, give an error message */
2066                         if(type_specifiers == 0) {
2067                                 if (! strict_mode) {
2068                                         if (warning.implicit_int) {
2069                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
2070                                         }
2071                                         atomic_type = ATOMIC_TYPE_INT;
2072                                         break;
2073                                 } else {
2074                                         errorf(HERE, "no type specifiers given in declaration");
2075                                 }
2076                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
2077                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
2078                                 errorf(HERE, "signed and unsigned specifiers gives");
2079                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2080                                 errorf(HERE, "only integer types can be signed or unsigned");
2081                         } else {
2082                                 errorf(HERE, "multiple datatypes in declaration");
2083                         }
2084                         atomic_type = ATOMIC_TYPE_INVALID;
2085                 }
2086
2087                 type               = allocate_type_zero(TYPE_ATOMIC, builtin_source_position);
2088                 type->atomic.akind = atomic_type;
2089                 newtype            = 1;
2090         } else {
2091                 if(type_specifiers != 0) {
2092                         errorf(HERE, "multiple datatypes in declaration");
2093                 }
2094         }
2095
2096         type->base.qualifiers = type_qualifiers;
2097
2098         type_t *result = typehash_insert(type);
2099         if(newtype && result != type) {
2100                 free_type(type);
2101         }
2102
2103         specifiers->type = result;
2104 }
2105
2106 static type_qualifiers_t parse_type_qualifiers(void)
2107 {
2108         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
2109
2110         while(true) {
2111                 switch(token.type) {
2112                 /* type qualifiers */
2113                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
2114                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2115                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2116
2117                 default:
2118                         return type_qualifiers;
2119                 }
2120         }
2121 }
2122
2123 static declaration_t *parse_identifier_list(void)
2124 {
2125         declaration_t *declarations     = NULL;
2126         declaration_t *last_declaration = NULL;
2127         do {
2128                 declaration_t *const declaration = allocate_declaration_zero();
2129                 declaration->type            = NULL; /* a K&R parameter list has no types, yet */
2130                 declaration->source_position = token.source_position;
2131                 declaration->symbol          = token.v.symbol;
2132                 next_token();
2133
2134                 if(last_declaration != NULL) {
2135                         last_declaration->next = declaration;
2136                 } else {
2137                         declarations = declaration;
2138                 }
2139                 last_declaration = declaration;
2140
2141                 if(token.type != ',')
2142                         break;
2143                 next_token();
2144         } while(token.type == T_IDENTIFIER);
2145
2146         return declarations;
2147 }
2148
2149 static void semantic_parameter(declaration_t *declaration)
2150 {
2151         /* TODO: improve error messages */
2152
2153         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
2154                 errorf(HERE, "typedef not allowed in parameter list");
2155         } else if(declaration->storage_class != STORAGE_CLASS_NONE
2156                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
2157                 errorf(HERE, "parameter may only have none or register storage class");
2158         }
2159
2160         type_t *const orig_type = declaration->type;
2161         type_t *      type      = skip_typeref(orig_type);
2162
2163         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
2164          * into a pointer. Â§ 6.7.5.3 (7) */
2165         if (is_type_array(type)) {
2166                 type_t *const element_type = type->array.element_type;
2167
2168                 type = make_pointer_type(element_type, type->base.qualifiers);
2169
2170                 declaration->type = type;
2171         }
2172
2173         if(is_type_incomplete(type)) {
2174                 errorf(HERE, "incomplete type '%T' not allowed for parameter '%Y'",
2175                        orig_type, declaration->symbol);
2176         }
2177 }
2178
2179 static declaration_t *parse_parameter(void)
2180 {
2181         declaration_specifiers_t specifiers;
2182         memset(&specifiers, 0, sizeof(specifiers));
2183
2184         parse_declaration_specifiers(&specifiers);
2185
2186         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
2187
2188         semantic_parameter(declaration);
2189
2190         return declaration;
2191 }
2192
2193 static declaration_t *parse_parameters(function_type_t *type)
2194 {
2195         if(token.type == T_IDENTIFIER) {
2196                 symbol_t *symbol = token.v.symbol;
2197                 if(!is_typedef_symbol(symbol)) {
2198                         type->kr_style_parameters = true;
2199                         return parse_identifier_list();
2200                 }
2201         }
2202
2203         if(token.type == ')') {
2204                 type->unspecified_parameters = 1;
2205                 return NULL;
2206         }
2207         if(token.type == T_void && look_ahead(1)->type == ')') {
2208                 next_token();
2209                 return NULL;
2210         }
2211
2212         declaration_t        *declarations = NULL;
2213         declaration_t        *declaration;
2214         declaration_t        *last_declaration = NULL;
2215         function_parameter_t *parameter;
2216         function_parameter_t *last_parameter = NULL;
2217
2218         while(true) {
2219                 switch(token.type) {
2220                 case T_DOTDOTDOT:
2221                         next_token();
2222                         type->variadic = 1;
2223                         return declarations;
2224
2225                 case T_IDENTIFIER:
2226                 case T___extension__:
2227                 DECLARATION_START
2228                         declaration = parse_parameter();
2229
2230                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
2231                         memset(parameter, 0, sizeof(parameter[0]));
2232                         parameter->type = declaration->type;
2233
2234                         if(last_parameter != NULL) {
2235                                 last_declaration->next = declaration;
2236                                 last_parameter->next   = parameter;
2237                         } else {
2238                                 type->parameters = parameter;
2239                                 declarations     = declaration;
2240                         }
2241                         last_parameter   = parameter;
2242                         last_declaration = declaration;
2243                         break;
2244
2245                 default:
2246                         return declarations;
2247                 }
2248                 if(token.type != ',')
2249                         return declarations;
2250                 next_token();
2251         }
2252 }
2253
2254 typedef enum {
2255         CONSTRUCT_INVALID,
2256         CONSTRUCT_POINTER,
2257         CONSTRUCT_FUNCTION,
2258         CONSTRUCT_ARRAY
2259 } construct_type_kind_t;
2260
2261 typedef struct construct_type_t construct_type_t;
2262 struct construct_type_t {
2263         construct_type_kind_t  kind;
2264         construct_type_t      *next;
2265 };
2266
2267 typedef struct parsed_pointer_t parsed_pointer_t;
2268 struct parsed_pointer_t {
2269         construct_type_t  construct_type;
2270         type_qualifiers_t type_qualifiers;
2271 };
2272
2273 typedef struct construct_function_type_t construct_function_type_t;
2274 struct construct_function_type_t {
2275         construct_type_t  construct_type;
2276         type_t           *function_type;
2277 };
2278
2279 typedef struct parsed_array_t parsed_array_t;
2280 struct parsed_array_t {
2281         construct_type_t  construct_type;
2282         type_qualifiers_t type_qualifiers;
2283         bool              is_static;
2284         bool              is_variable;
2285         expression_t     *size;
2286 };
2287
2288 typedef struct construct_base_type_t construct_base_type_t;
2289 struct construct_base_type_t {
2290         construct_type_t  construct_type;
2291         type_t           *type;
2292 };
2293
2294 static construct_type_t *parse_pointer_declarator(void)
2295 {
2296         eat('*');
2297
2298         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
2299         memset(pointer, 0, sizeof(pointer[0]));
2300         pointer->construct_type.kind = CONSTRUCT_POINTER;
2301         pointer->type_qualifiers     = parse_type_qualifiers();
2302
2303         return (construct_type_t*) pointer;
2304 }
2305
2306 static construct_type_t *parse_array_declarator(void)
2307 {
2308         eat('[');
2309
2310         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
2311         memset(array, 0, sizeof(array[0]));
2312         array->construct_type.kind = CONSTRUCT_ARRAY;
2313
2314         if(token.type == T_static) {
2315                 array->is_static = true;
2316                 next_token();
2317         }
2318
2319         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2320         if(type_qualifiers != 0) {
2321                 if(token.type == T_static) {
2322                         array->is_static = true;
2323                         next_token();
2324                 }
2325         }
2326         array->type_qualifiers = type_qualifiers;
2327
2328         if(token.type == '*' && look_ahead(1)->type == ']') {
2329                 array->is_variable = true;
2330                 next_token();
2331         } else if(token.type != ']') {
2332                 array->size = parse_assignment_expression();
2333         }
2334
2335         expect(']');
2336
2337         return (construct_type_t*) array;
2338 }
2339
2340 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2341 {
2342         eat('(');
2343
2344         type_t *type;
2345         if(declaration != NULL) {
2346                 type = allocate_type_zero(TYPE_FUNCTION, declaration->source_position);
2347         } else {
2348                 type = allocate_type_zero(TYPE_FUNCTION, token.source_position);
2349         }
2350
2351         declaration_t *parameters = parse_parameters(&type->function);
2352         if(declaration != NULL) {
2353                 declaration->scope.declarations = parameters;
2354         }
2355
2356         construct_function_type_t *construct_function_type =
2357                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2358         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2359         construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
2360         construct_function_type->function_type       = type;
2361
2362         expect(')');
2363
2364         return (construct_type_t*) construct_function_type;
2365 }
2366
2367 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2368                 bool may_be_abstract)
2369 {
2370         /* construct a single linked list of construct_type_t's which describe
2371          * how to construct the final declarator type */
2372         construct_type_t *first = NULL;
2373         construct_type_t *last  = NULL;
2374
2375         /* pointers */
2376         while(token.type == '*') {
2377                 construct_type_t *type = parse_pointer_declarator();
2378
2379                 if(last == NULL) {
2380                         first = type;
2381                         last  = type;
2382                 } else {
2383                         last->next = type;
2384                         last       = type;
2385                 }
2386         }
2387
2388         /* TODO: find out if this is correct */
2389         parse_attributes();
2390
2391         construct_type_t *inner_types = NULL;
2392
2393         switch(token.type) {
2394         case T_IDENTIFIER:
2395                 if(declaration == NULL) {
2396                         errorf(HERE, "no identifier expected in typename");
2397                 } else {
2398                         declaration->symbol          = token.v.symbol;
2399                         declaration->source_position = token.source_position;
2400                 }
2401                 next_token();
2402                 break;
2403         case '(':
2404                 next_token();
2405                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2406                 expect(')');
2407                 break;
2408         default:
2409                 if(may_be_abstract)
2410                         break;
2411                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2412                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2413                  * eat '}' */
2414                 if(token.type == '}' && current_function == NULL) {
2415                         next_token();
2416                 } else {
2417                         eat_statement();
2418                 }
2419                 return NULL;
2420         }
2421
2422         construct_type_t *p = last;
2423
2424         while(true) {
2425                 construct_type_t *type;
2426                 switch(token.type) {
2427                 case '(':
2428                         type = parse_function_declarator(declaration);
2429                         break;
2430                 case '[':
2431                         type = parse_array_declarator();
2432                         break;
2433                 default:
2434                         goto declarator_finished;
2435                 }
2436
2437                 /* insert in the middle of the list (behind p) */
2438                 if(p != NULL) {
2439                         type->next = p->next;
2440                         p->next    = type;
2441                 } else {
2442                         type->next = first;
2443                         first      = type;
2444                 }
2445                 if(last == p) {
2446                         last = type;
2447                 }
2448         }
2449
2450 declarator_finished:
2451         parse_attributes();
2452
2453         /* append inner_types at the end of the list, we don't to set last anymore
2454          * as it's not needed anymore */
2455         if(last == NULL) {
2456                 assert(first == NULL);
2457                 first = inner_types;
2458         } else {
2459                 last->next = inner_types;
2460         }
2461
2462         return first;
2463 }
2464
2465 static type_t *construct_declarator_type(construct_type_t *construct_list,
2466                                          type_t *type)
2467 {
2468         construct_type_t *iter = construct_list;
2469         for( ; iter != NULL; iter = iter->next) {
2470                 switch(iter->kind) {
2471                 case CONSTRUCT_INVALID:
2472                         panic("invalid type construction found");
2473                 case CONSTRUCT_FUNCTION: {
2474                         construct_function_type_t *construct_function_type
2475                                 = (construct_function_type_t*) iter;
2476
2477                         type_t *function_type = construct_function_type->function_type;
2478
2479                         function_type->function.return_type = type;
2480
2481                         type_t *skipped_return_type = skip_typeref(type);
2482                         if (is_type_function(skipped_return_type)) {
2483                                 errorf(HERE, "function returning function is not allowed");
2484                                 type = type_error_type;
2485                         } else if (is_type_array(skipped_return_type)) {
2486                                 errorf(HERE, "function returning array is not allowed");
2487                                 type = type_error_type;
2488                         } else {
2489                                 type = function_type;
2490                         }
2491                         break;
2492                 }
2493
2494                 case CONSTRUCT_POINTER: {
2495                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2496                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER, (source_position_t){NULL, 0});
2497                         pointer_type->pointer.points_to  = type;
2498                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2499
2500                         type = pointer_type;
2501                         break;
2502                 }
2503
2504                 case CONSTRUCT_ARRAY: {
2505                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2506                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY, (source_position_t){NULL, 0});
2507
2508                         expression_t *size_expression = parsed_array->size;
2509
2510                         array_type->base.qualifiers       = parsed_array->type_qualifiers;
2511                         array_type->array.element_type    = type;
2512                         array_type->array.is_static       = parsed_array->is_static;
2513                         array_type->array.is_variable     = parsed_array->is_variable;
2514                         array_type->array.size_expression = size_expression;
2515
2516                         if(size_expression != NULL &&
2517                                         is_constant_expression(size_expression)) {
2518                                 array_type->array.size_constant = true;
2519                                 array_type->array.size
2520                                         = fold_constant(size_expression);
2521                         }
2522
2523                         type_t *skipped_type = skip_typeref(type);
2524                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2525                                 errorf(HERE, "array of void is not allowed");
2526                                 type = type_error_type;
2527                         } else {
2528                                 type = array_type;
2529                         }
2530                         break;
2531                 }
2532                 }
2533
2534                 type_t *hashed_type = typehash_insert(type);
2535                 if(hashed_type != type) {
2536                         /* the function type was constructed earlier freeing it here will
2537                          * destroy other types... */
2538                         if(iter->kind != CONSTRUCT_FUNCTION) {
2539                                 free_type(type);
2540                         }
2541                         type = hashed_type;
2542                 }
2543         }
2544
2545         return type;
2546 }
2547
2548 static declaration_t *parse_declarator(
2549                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2550 {
2551         declaration_t *const declaration = allocate_declaration_zero();
2552         declaration->storage_class  = specifiers->storage_class;
2553         declaration->modifiers      = specifiers->decl_modifiers;
2554         declaration->is_inline      = specifiers->is_inline;
2555
2556         construct_type_t *construct_type
2557                 = parse_inner_declarator(declaration, may_be_abstract);
2558         type_t *const type = specifiers->type;
2559         declaration->type = construct_declarator_type(construct_type, type);
2560
2561         if(construct_type != NULL) {
2562                 obstack_free(&temp_obst, construct_type);
2563         }
2564
2565         return declaration;
2566 }
2567
2568 static type_t *parse_abstract_declarator(type_t *base_type)
2569 {
2570         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2571
2572         type_t *result = construct_declarator_type(construct_type, base_type);
2573         if(construct_type != NULL) {
2574                 obstack_free(&temp_obst, construct_type);
2575         }
2576
2577         return result;
2578 }
2579
2580 static declaration_t *append_declaration(declaration_t* const declaration)
2581 {
2582         if (last_declaration != NULL) {
2583                 last_declaration->next = declaration;
2584         } else {
2585                 scope->declarations = declaration;
2586         }
2587         last_declaration = declaration;
2588         return declaration;
2589 }
2590
2591 /**
2592  * Check if the declaration of main is suspicious.  main should be a
2593  * function with external linkage, returning int, taking either zero
2594  * arguments, two, or three arguments of appropriate types, ie.
2595  *
2596  * int main([ int argc, char **argv [, char **env ] ]).
2597  *
2598  * @param decl    the declaration to check
2599  * @param type    the function type of the declaration
2600  */
2601 static void check_type_of_main(const declaration_t *const decl, const function_type_t *const func_type)
2602 {
2603         if (decl->storage_class == STORAGE_CLASS_STATIC) {
2604                 warningf(decl->source_position, "'main' is normally a non-static function");
2605         }
2606         if (skip_typeref(func_type->return_type) != type_int) {
2607                 warningf(decl->source_position, "return type of 'main' should be 'int', but is '%T'", func_type->return_type);
2608         }
2609         const function_parameter_t *parm = func_type->parameters;
2610         if (parm != NULL) {
2611                 type_t *const first_type = parm->type;
2612                 if (!types_compatible(skip_typeref(first_type), type_int)) {
2613                         warningf(decl->source_position, "first argument of 'main' should be 'int', but is '%T'", first_type);
2614                 }
2615                 parm = parm->next;
2616                 if (parm != NULL) {
2617                         type_t *const second_type = parm->type;
2618                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
2619                                 warningf(decl->source_position, "second argument of 'main' should be 'char**', but is '%T'", second_type);
2620                         }
2621                         parm = parm->next;
2622                         if (parm != NULL) {
2623                                 type_t *const third_type = parm->type;
2624                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
2625                                         warningf(decl->source_position, "third argument of 'main' should be 'char**', but is '%T'", third_type);
2626                                 }
2627                                 parm = parm->next;
2628                                 if (parm != NULL) {
2629                                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2630                                 }
2631                         }
2632                 } else {
2633                         warningf(decl->source_position, "'main' takes only zero, two or three arguments");
2634                 }
2635         }
2636 }
2637
2638 /**
2639  * Check if a symbol is the equal to "main".
2640  */
2641 static bool is_sym_main(const symbol_t *const sym)
2642 {
2643         return strcmp(sym->string, "main") == 0;
2644 }
2645
2646 static declaration_t *internal_record_declaration(
2647         declaration_t *const declaration,
2648         const bool is_function_definition)
2649 {
2650         const symbol_t *const symbol  = declaration->symbol;
2651         const namespace_t     namespc = (namespace_t)declaration->namespc;
2652
2653         type_t *const orig_type = declaration->type;
2654         type_t *const type      = skip_typeref(orig_type);
2655         if (is_type_function(type) &&
2656                         type->function.unspecified_parameters &&
2657                         warning.strict_prototypes) {
2658                 warningf(declaration->source_position,
2659                          "function declaration '%#T' is not a prototype",
2660                          orig_type, declaration->symbol);
2661         }
2662
2663         if (is_function_definition && warning.main && is_sym_main(symbol)) {
2664                 check_type_of_main(declaration, &type->function);
2665         }
2666
2667         assert(declaration->symbol != NULL);
2668         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2669
2670         assert(declaration != previous_declaration);
2671         if (previous_declaration != NULL) {
2672                 if (previous_declaration->parent_scope == scope) {
2673                         /* can happen for K&R style declarations */
2674                         if(previous_declaration->type == NULL) {
2675                                 previous_declaration->type = declaration->type;
2676                         }
2677
2678                         const type_t *prev_type = skip_typeref(previous_declaration->type);
2679                         if (!types_compatible(type, prev_type)) {
2680                                 errorf(declaration->source_position,
2681                                        "declaration '%#T' is incompatible with "
2682                                        "previous declaration '%#T'",
2683                                        orig_type, symbol, previous_declaration->type, symbol);
2684                                 errorf(previous_declaration->source_position,
2685                                        "previous declaration of '%Y' was here", symbol);
2686                         } else {
2687                                 unsigned old_storage_class
2688                                         = previous_declaration->storage_class;
2689                                 unsigned new_storage_class = declaration->storage_class;
2690
2691                                 if(is_type_incomplete(prev_type)) {
2692                                         previous_declaration->type = type;
2693                                         prev_type                  = type;
2694                                 }
2695
2696                                 /* pretend no storage class means extern for function
2697                                  * declarations (except if the previous declaration is neither
2698                                  * none nor extern) */
2699                                 if (is_type_function(type)) {
2700                                         switch (old_storage_class) {
2701                                                 case STORAGE_CLASS_NONE:
2702                                                         old_storage_class = STORAGE_CLASS_EXTERN;
2703
2704                                                 case STORAGE_CLASS_EXTERN:
2705                                                         if (is_function_definition) {
2706                                                                 if (warning.missing_prototypes &&
2707                                                                     prev_type->function.unspecified_parameters &&
2708                                                                     !is_sym_main(symbol)) {
2709                                                                         warningf(declaration->source_position,
2710                                                                                  "no previous prototype for '%#T'",
2711                                                                                  orig_type, symbol);
2712                                                                 }
2713                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
2714                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
2715                                                         }
2716                                                         break;
2717
2718                                                 default: break;
2719                                         }
2720                                 }
2721
2722                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2723                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
2724 warn_redundant_declaration:
2725                                         if (warning.redundant_decls) {
2726                                                 warningf(declaration->source_position,
2727                                                          "redundant declaration for '%Y'", symbol);
2728                                                 warningf(previous_declaration->source_position,
2729                                                          "previous declaration of '%Y' was here",
2730                                                          symbol);
2731                                         }
2732                                 } else if (current_function == NULL) {
2733                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
2734                                                         new_storage_class == STORAGE_CLASS_STATIC) {
2735                                                 errorf(declaration->source_position,
2736                                                        "static declaration of '%Y' follows non-static declaration",
2737                                                        symbol);
2738                                                 errorf(previous_declaration->source_position,
2739                                                        "previous declaration of '%Y' was here", symbol);
2740                                         } else {
2741                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2742                                                         goto warn_redundant_declaration;
2743                                                 }
2744                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
2745                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
2746                                                 }
2747                                         }
2748                                 } else {
2749                                         if (old_storage_class == new_storage_class) {
2750                                                 errorf(declaration->source_position,
2751                                                        "redeclaration of '%Y'", symbol);
2752                                         } else {
2753                                                 errorf(declaration->source_position,
2754                                                        "redeclaration of '%Y' with different linkage",
2755                                                        symbol);
2756                                         }
2757                                         errorf(previous_declaration->source_position,
2758                                                "previous declaration of '%Y' was here", symbol);
2759                                 }
2760                         }
2761                         return previous_declaration;
2762                 }
2763         } else if (is_function_definition) {
2764                 if (declaration->storage_class != STORAGE_CLASS_STATIC) {
2765                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
2766                                 warningf(declaration->source_position,
2767                                          "no previous prototype for '%#T'", orig_type, symbol);
2768                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
2769                                 warningf(declaration->source_position,
2770                                          "no previous declaration for '%#T'", orig_type,
2771                                          symbol);
2772                         }
2773                 }
2774         } else if (warning.missing_declarations &&
2775             scope == global_scope &&
2776             !is_type_function(type) && (
2777               declaration->storage_class == STORAGE_CLASS_NONE ||
2778               declaration->storage_class == STORAGE_CLASS_THREAD
2779             )) {
2780                 warningf(declaration->source_position,
2781                          "no previous declaration for '%#T'", orig_type, symbol);
2782         }
2783
2784         assert(declaration->parent_scope == NULL);
2785         assert(scope != NULL);
2786
2787         declaration->parent_scope = scope;
2788
2789         environment_push(declaration);
2790         return append_declaration(declaration);
2791 }
2792
2793 static declaration_t *record_declaration(declaration_t *declaration)
2794 {
2795         return internal_record_declaration(declaration, false);
2796 }
2797
2798 static declaration_t *record_function_definition(declaration_t *declaration)
2799 {
2800         return internal_record_declaration(declaration, true);
2801 }
2802
2803 static void parser_error_multiple_definition(declaration_t *declaration,
2804                 const source_position_t source_position)
2805 {
2806         errorf(source_position, "multiple definition of symbol '%Y'",
2807                declaration->symbol);
2808         errorf(declaration->source_position,
2809                "this is the location of the previous definition.");
2810 }
2811
2812 static bool is_declaration_specifier(const token_t *token,
2813                                      bool only_type_specifiers)
2814 {
2815         switch(token->type) {
2816                 TYPE_SPECIFIERS
2817                         return true;
2818                 case T_IDENTIFIER:
2819                         return is_typedef_symbol(token->v.symbol);
2820
2821                 case T___extension__:
2822                 STORAGE_CLASSES
2823                 TYPE_QUALIFIERS
2824                         return !only_type_specifiers;
2825
2826                 default:
2827                         return false;
2828         }
2829 }
2830
2831 static void parse_init_declarator_rest(declaration_t *declaration)
2832 {
2833         eat('=');
2834
2835         type_t *orig_type = declaration->type;
2836         type_t *type      = skip_typeref(orig_type);
2837
2838         if(declaration->init.initializer != NULL) {
2839                 parser_error_multiple_definition(declaration, token.source_position);
2840         }
2841
2842         bool must_be_constant = false;
2843         if(declaration->storage_class == STORAGE_CLASS_STATIC
2844                         || declaration->storage_class == STORAGE_CLASS_THREAD_STATIC
2845                         || declaration->parent_scope == global_scope) {
2846                 must_be_constant = true;
2847         }
2848
2849         parse_initializer_env_t env;
2850         env.type             = orig_type;
2851         env.must_be_constant = must_be_constant;
2852         parse_initializer(&env);
2853
2854         if(env.type != orig_type) {
2855                 orig_type         = env.type;
2856                 type              = skip_typeref(orig_type);
2857                 declaration->type = env.type;
2858         }
2859
2860         if(is_type_function(type)) {
2861                 errorf(declaration->source_position,
2862                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2863                        declaration->symbol, orig_type);
2864         } else {
2865                 declaration->init.initializer = env.initializer;
2866         }
2867 }
2868
2869 /* parse rest of a declaration without any declarator */
2870 static void parse_anonymous_declaration_rest(
2871                 const declaration_specifiers_t *specifiers,
2872                 parsed_declaration_func finished_declaration)
2873 {
2874         eat(';');
2875
2876         declaration_t *const declaration = allocate_declaration_zero();
2877         declaration->type            = specifiers->type;
2878         declaration->storage_class   = specifiers->storage_class;
2879         declaration->source_position = specifiers->source_position;
2880
2881         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2882                 warningf(declaration->source_position, "useless storage class in empty declaration");
2883         }
2884
2885         type_t *type = declaration->type;
2886         switch (type->kind) {
2887                 case TYPE_COMPOUND_STRUCT:
2888                 case TYPE_COMPOUND_UNION: {
2889                         if (type->compound.declaration->symbol == NULL) {
2890                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2891                         }
2892                         break;
2893                 }
2894
2895                 case TYPE_ENUM:
2896                         break;
2897
2898                 default:
2899                         warningf(declaration->source_position, "empty declaration");
2900                         break;
2901         }
2902
2903         finished_declaration(declaration);
2904 }
2905
2906 static void parse_declaration_rest(declaration_t *ndeclaration,
2907                 const declaration_specifiers_t *specifiers,
2908                 parsed_declaration_func finished_declaration)
2909 {
2910         while(true) {
2911                 declaration_t *declaration = finished_declaration(ndeclaration);
2912
2913                 type_t *orig_type = declaration->type;
2914                 type_t *type      = skip_typeref(orig_type);
2915
2916                 if (type->kind != TYPE_FUNCTION &&
2917                     declaration->is_inline &&
2918                     is_type_valid(type)) {
2919                         warningf(declaration->source_position,
2920                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2921                 }
2922
2923                 if(token.type == '=') {
2924                         parse_init_declarator_rest(declaration);
2925                 }
2926
2927                 if(token.type != ',')
2928                         break;
2929                 eat(',');
2930
2931                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2932         }
2933         expect_void(';');
2934 }
2935
2936 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2937 {
2938         symbol_t *symbol  = declaration->symbol;
2939         if(symbol == NULL) {
2940                 errorf(HERE, "anonymous declaration not valid as function parameter");
2941                 return declaration;
2942         }
2943         namespace_t namespc = (namespace_t) declaration->namespc;
2944         if(namespc != NAMESPACE_NORMAL) {
2945                 return record_declaration(declaration);
2946         }
2947
2948         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2949         if(previous_declaration == NULL ||
2950                         previous_declaration->parent_scope != scope) {
2951                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2952                        symbol);
2953                 return declaration;
2954         }
2955
2956         if(previous_declaration->type == NULL) {
2957                 previous_declaration->type          = declaration->type;
2958                 previous_declaration->storage_class = declaration->storage_class;
2959                 previous_declaration->parent_scope  = scope;
2960                 return previous_declaration;
2961         } else {
2962                 return record_declaration(declaration);
2963         }
2964 }
2965
2966 static void parse_declaration(parsed_declaration_func finished_declaration)
2967 {
2968         declaration_specifiers_t specifiers;
2969         memset(&specifiers, 0, sizeof(specifiers));
2970         parse_declaration_specifiers(&specifiers);
2971
2972         if(token.type == ';') {
2973                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2974         } else {
2975                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2976                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2977         }
2978 }
2979
2980 static void parse_kr_declaration_list(declaration_t *declaration)
2981 {
2982         type_t *type = skip_typeref(declaration->type);
2983         if(!is_type_function(type))
2984                 return;
2985
2986         if(!type->function.kr_style_parameters)
2987                 return;
2988
2989         /* push function parameters */
2990         int       top        = environment_top();
2991         scope_t  *last_scope = scope;
2992         set_scope(&declaration->scope);
2993
2994         declaration_t *parameter = declaration->scope.declarations;
2995         for( ; parameter != NULL; parameter = parameter->next) {
2996                 assert(parameter->parent_scope == NULL);
2997                 parameter->parent_scope = scope;
2998                 environment_push(parameter);
2999         }
3000
3001         /* parse declaration list */
3002         while(is_declaration_specifier(&token, false)) {
3003                 parse_declaration(finished_kr_declaration);
3004         }
3005
3006         /* pop function parameters */
3007         assert(scope == &declaration->scope);
3008         set_scope(last_scope);
3009         environment_pop_to(top);
3010
3011         /* update function type */
3012         type_t *new_type = duplicate_type(type);
3013         new_type->function.kr_style_parameters = false;
3014
3015         function_parameter_t *parameters     = NULL;
3016         function_parameter_t *last_parameter = NULL;
3017
3018         declaration_t *parameter_declaration = declaration->scope.declarations;
3019         for( ; parameter_declaration != NULL;
3020                         parameter_declaration = parameter_declaration->next) {
3021                 type_t *parameter_type = parameter_declaration->type;
3022                 if(parameter_type == NULL) {
3023                         if (strict_mode) {
3024                                 errorf(HERE, "no type specified for function parameter '%Y'",
3025                                        parameter_declaration->symbol);
3026                         } else {
3027                                 if (warning.implicit_int) {
3028                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
3029                                                 parameter_declaration->symbol);
3030                                 }
3031                                 parameter_type              = type_int;
3032                                 parameter_declaration->type = parameter_type;
3033                         }
3034                 }
3035
3036                 semantic_parameter(parameter_declaration);
3037                 parameter_type = parameter_declaration->type;
3038
3039                 function_parameter_t *function_parameter
3040                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
3041                 memset(function_parameter, 0, sizeof(function_parameter[0]));
3042
3043                 function_parameter->type = parameter_type;
3044                 if(last_parameter != NULL) {
3045                         last_parameter->next = function_parameter;
3046                 } else {
3047                         parameters = function_parameter;
3048                 }
3049                 last_parameter = function_parameter;
3050         }
3051         new_type->function.parameters = parameters;
3052
3053         type = typehash_insert(new_type);
3054         if(type != new_type) {
3055                 obstack_free(type_obst, new_type);
3056         }
3057
3058         declaration->type = type;
3059 }
3060
3061 static bool first_err = true;
3062
3063 /**
3064  * When called with first_err set, prints the name of the current function,
3065  * else does noting.
3066  */
3067 static void print_in_function(void) {
3068         if (first_err) {
3069                 first_err = false;
3070                 diagnosticf("%s: In function '%Y':\n",
3071                         current_function->source_position.input_name,
3072                         current_function->symbol);
3073         }
3074 }
3075
3076 /**
3077  * Check if all labels are defined in the current function.
3078  * Check if all labels are used in the current function.
3079  */
3080 static void check_labels(void)
3081 {
3082         for (const goto_statement_t *goto_statement = goto_first;
3083             goto_statement != NULL;
3084             goto_statement = goto_statement->next) {
3085                 declaration_t *label = goto_statement->label;
3086
3087                 label->used = true;
3088                 if (label->source_position.input_name == NULL) {
3089                         print_in_function();
3090                         errorf(goto_statement->base.source_position,
3091                                "label '%Y' used but not defined", label->symbol);
3092                  }
3093         }
3094         goto_first = goto_last = NULL;
3095
3096         if (warning.unused_label) {
3097                 for (const label_statement_t *label_statement = label_first;
3098                          label_statement != NULL;
3099                          label_statement = label_statement->next) {
3100                         const declaration_t *label = label_statement->label;
3101
3102                         if (! label->used) {
3103                                 print_in_function();
3104                                 warningf(label_statement->base.source_position,
3105                                         "label '%Y' defined but not used", label->symbol);
3106                         }
3107                 }
3108         }
3109         label_first = label_last = NULL;
3110 }
3111
3112 /**
3113  * Check declarations of current_function for unused entities.
3114  */
3115 static void check_declarations(void)
3116 {
3117         if (warning.unused_parameter) {
3118                 const scope_t *scope = &current_function->scope;
3119
3120                 const declaration_t *parameter = scope->declarations;
3121                 for (; parameter != NULL; parameter = parameter->next) {
3122                         if (! parameter->used) {
3123                                 print_in_function();
3124                                 warningf(parameter->source_position,
3125                                         "unused parameter '%Y'", parameter->symbol);
3126                         }
3127                 }
3128         }
3129         if (warning.unused_variable) {
3130         }
3131 }
3132
3133 static void parse_external_declaration(void)
3134 {
3135         /* function-definitions and declarations both start with declaration
3136          * specifiers */
3137         declaration_specifiers_t specifiers;
3138         memset(&specifiers, 0, sizeof(specifiers));
3139         parse_declaration_specifiers(&specifiers);
3140
3141         /* must be a declaration */
3142         if(token.type == ';') {
3143                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
3144                 return;
3145         }
3146
3147         /* declarator is common to both function-definitions and declarations */
3148         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
3149
3150         /* must be a declaration */
3151         if(token.type == ',' || token.type == '=' || token.type == ';') {
3152                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
3153                 return;
3154         }
3155
3156         /* must be a function definition */
3157         parse_kr_declaration_list(ndeclaration);
3158
3159         if(token.type != '{') {
3160                 parse_error_expected("while parsing function definition", '{', 0);
3161                 eat_statement();
3162                 return;
3163         }
3164
3165         type_t *type = ndeclaration->type;
3166
3167         /* note that we don't skip typerefs: the standard doesn't allow them here
3168          * (so we can't use is_type_function here) */
3169         if(type->kind != TYPE_FUNCTION) {
3170                 if (is_type_valid(type)) {
3171                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
3172                                type, ndeclaration->symbol);
3173                 }
3174                 eat_block();
3175                 return;
3176         }
3177
3178         /* Â§ 6.7.5.3 (14) a function definition with () means no
3179          * parameters (and not unspecified parameters) */
3180         if(type->function.unspecified_parameters) {
3181                 type_t *duplicate = duplicate_type(type);
3182                 duplicate->function.unspecified_parameters = false;
3183
3184                 type = typehash_insert(duplicate);
3185                 if(type != duplicate) {
3186                         obstack_free(type_obst, duplicate);
3187                 }
3188                 ndeclaration->type = type;
3189         }
3190
3191         declaration_t *const declaration = record_function_definition(ndeclaration);
3192         if(ndeclaration != declaration) {
3193                 declaration->scope = ndeclaration->scope;
3194         }
3195         type = skip_typeref(declaration->type);
3196
3197         /* push function parameters and switch scope */
3198         int       top        = environment_top();
3199         scope_t  *last_scope = scope;
3200         set_scope(&declaration->scope);
3201
3202         declaration_t *parameter = declaration->scope.declarations;
3203         for( ; parameter != NULL; parameter = parameter->next) {
3204                 if(parameter->parent_scope == &ndeclaration->scope) {
3205                         parameter->parent_scope = scope;
3206                 }
3207                 assert(parameter->parent_scope == NULL
3208                                 || parameter->parent_scope == scope);
3209                 parameter->parent_scope = scope;
3210                 environment_push(parameter);
3211         }
3212
3213         if(declaration->init.statement != NULL) {
3214                 parser_error_multiple_definition(declaration, token.source_position);
3215                 eat_block();
3216                 goto end_of_parse_external_declaration;
3217         } else {
3218                 /* parse function body */
3219                 int            label_stack_top      = label_top();
3220                 declaration_t *old_current_function = current_function;
3221                 current_function                    = declaration;
3222
3223                 declaration->init.statement = parse_compound_statement();
3224                 first_err = true;
3225                 check_labels();
3226                 check_declarations();
3227
3228                 assert(current_function == declaration);
3229                 current_function = old_current_function;
3230                 label_pop_to(label_stack_top);
3231         }
3232
3233 end_of_parse_external_declaration:
3234         assert(scope == &declaration->scope);
3235         set_scope(last_scope);
3236         environment_pop_to(top);
3237 }
3238
3239 static type_t *make_bitfield_type(type_t *base, expression_t *size,
3240                                   source_position_t source_position)
3241 {
3242         type_t *type        = allocate_type_zero(TYPE_BITFIELD, source_position);
3243         type->bitfield.base = base;
3244         type->bitfield.size = size;
3245
3246         return type;
3247 }
3248
3249 static declaration_t *find_compound_entry(declaration_t *compound_declaration,
3250                                           symbol_t *symbol)
3251 {
3252         declaration_t *iter = compound_declaration->scope.declarations;
3253         for( ; iter != NULL; iter = iter->next) {
3254                 if(iter->namespc != NAMESPACE_NORMAL)
3255                         continue;
3256
3257                 if(iter->symbol == NULL) {
3258                         type_t *type = skip_typeref(iter->type);
3259                         if(is_type_compound(type)) {
3260                                 declaration_t *result
3261                                         = find_compound_entry(type->compound.declaration, symbol);
3262                                 if(result != NULL)
3263                                         return result;
3264                         }
3265                         continue;
3266                 }
3267
3268                 if(iter->symbol == symbol) {
3269                         return iter;
3270                 }
3271         }
3272
3273         return NULL;
3274 }
3275
3276 static void parse_compound_declarators(declaration_t *struct_declaration,
3277                 const declaration_specifiers_t *specifiers)
3278 {
3279         declaration_t *last_declaration = struct_declaration->scope.declarations;
3280         if(last_declaration != NULL) {
3281                 while(last_declaration->next != NULL) {
3282                         last_declaration = last_declaration->next;
3283                 }
3284         }
3285
3286         while(1) {
3287                 declaration_t *declaration;
3288
3289                 if(token.type == ':') {
3290                         source_position_t source_position = HERE;
3291                         next_token();
3292
3293                         type_t *base_type = specifiers->type;
3294                         expression_t *size = parse_constant_expression();
3295
3296                         if(!is_type_integer(skip_typeref(base_type))) {
3297                                 errorf(HERE, "bitfield base type '%T' is not an integer type",
3298                                        base_type);
3299                         }
3300
3301                         type_t *type = make_bitfield_type(base_type, size, source_position);
3302
3303                         declaration                  = allocate_declaration_zero();
3304                         declaration->namespc         = NAMESPACE_NORMAL;
3305                         declaration->storage_class   = STORAGE_CLASS_NONE;
3306                         declaration->source_position = source_position;
3307                         declaration->modifiers       = specifiers->decl_modifiers;
3308                         declaration->type            = type;
3309                 } else {
3310                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
3311
3312                         type_t *orig_type = declaration->type;
3313                         type_t *type      = skip_typeref(orig_type);
3314
3315                         if(token.type == ':') {
3316                                 source_position_t source_position = HERE;
3317                                 next_token();
3318                                 expression_t *size = parse_constant_expression();
3319
3320                                 if(!is_type_integer(type)) {
3321                                         errorf(HERE, "bitfield base type '%T' is not an "
3322                                                "integer type", orig_type);
3323                                 }
3324
3325                                 type_t *bitfield_type = make_bitfield_type(orig_type, size, source_position);
3326                                 declaration->type = bitfield_type;
3327                         } else {
3328                                 /* TODO we ignore arrays for now... what is missing is a check
3329                                  * that they're at the end of the struct */
3330                                 if(is_type_incomplete(type) && !is_type_array(type)) {
3331                                         errorf(HERE,
3332                                                "compound member '%Y' has incomplete type '%T'",
3333                                                declaration->symbol, orig_type);
3334                                 } else if(is_type_function(type)) {
3335                                         errorf(HERE, "compound member '%Y' must not have function "
3336                                                "type '%T'", declaration->symbol, orig_type);
3337                                 }
3338                         }
3339                 }
3340
3341                 /* make sure we don't define a symbol multiple times */
3342                 symbol_t *symbol = declaration->symbol;
3343                 if(symbol != NULL) {
3344                         declaration_t *prev_decl
3345                                 = find_compound_entry(struct_declaration, symbol);
3346
3347                         if(prev_decl != NULL) {
3348                                 assert(prev_decl->symbol == symbol);
3349                                 errorf(declaration->source_position,
3350                                        "multiple declarations of symbol '%Y'", symbol);
3351                                 errorf(prev_decl->source_position,
3352                                        "previous declaration of '%Y' was here", symbol);
3353                         }
3354                 }
3355
3356                 /* append declaration */
3357                 if(last_declaration != NULL) {
3358                         last_declaration->next = declaration;
3359                 } else {
3360                         struct_declaration->scope.declarations = declaration;
3361                 }
3362                 last_declaration = declaration;
3363
3364                 if(token.type != ',')
3365                         break;
3366                 next_token();
3367         }
3368         expect_void(';');
3369 }
3370
3371 static void parse_compound_type_entries(declaration_t *compound_declaration)
3372 {
3373         eat('{');
3374
3375         while(token.type != '}' && token.type != T_EOF) {
3376                 declaration_specifiers_t specifiers;
3377                 memset(&specifiers, 0, sizeof(specifiers));
3378                 parse_declaration_specifiers(&specifiers);
3379
3380                 parse_compound_declarators(compound_declaration, &specifiers);
3381         }
3382         if(token.type == T_EOF) {
3383                 errorf(HERE, "EOF while parsing struct");
3384         }
3385         next_token();
3386 }
3387
3388 static type_t *parse_typename(void)
3389 {
3390         declaration_specifiers_t specifiers;
3391         memset(&specifiers, 0, sizeof(specifiers));
3392         parse_declaration_specifiers(&specifiers);
3393         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
3394                 /* TODO: improve error message, user does probably not know what a
3395                  * storage class is...
3396                  */
3397                 errorf(HERE, "typename may not have a storage class");
3398         }
3399
3400         type_t *result = parse_abstract_declarator(specifiers.type);
3401
3402         return result;
3403 }
3404
3405
3406
3407
3408 typedef expression_t* (*parse_expression_function) (unsigned precedence);
3409 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
3410                                                           expression_t *left);
3411
3412 typedef struct expression_parser_function_t expression_parser_function_t;
3413 struct expression_parser_function_t {
3414         unsigned                         precedence;
3415         parse_expression_function        parser;
3416         unsigned                         infix_precedence;
3417         parse_expression_infix_function  infix_parser;
3418 };
3419
3420 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
3421
3422 /**
3423  * Creates a new invalid expression.
3424  */
3425 static expression_t *create_invalid_expression(void)
3426 {
3427         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
3428         expression->base.source_position = token.source_position;
3429         return expression;
3430 }
3431
3432 /**
3433  * Prints an error message if an expression was expected but not read
3434  */
3435 static expression_t *expected_expression_error(void)
3436 {
3437         /* skip the error message if the error token was read */
3438         if (token.type != T_ERROR) {
3439                 errorf(HERE, "expected expression, got token '%K'", &token);
3440         }
3441         next_token();
3442
3443         return create_invalid_expression();
3444 }
3445
3446 /**
3447  * Parse a string constant.
3448  */
3449 static expression_t *parse_string_const(void)
3450 {
3451         wide_string_t wres;
3452         if (token.type == T_STRING_LITERAL) {
3453                 string_t res = token.v.string;
3454                 next_token();
3455                 while (token.type == T_STRING_LITERAL) {
3456                         res = concat_strings(&res, &token.v.string);
3457                         next_token();
3458                 }
3459                 if (token.type != T_WIDE_STRING_LITERAL) {
3460                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
3461                         cnst->base.type    = type_char_ptr;
3462                         cnst->string.value = res;
3463                         return cnst;
3464                 }
3465
3466                 wres = concat_string_wide_string(&res, &token.v.wide_string);
3467         } else {
3468                 wres = token.v.wide_string;
3469         }
3470         next_token();
3471
3472         for (;;) {
3473                 switch (token.type) {
3474                         case T_WIDE_STRING_LITERAL:
3475                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
3476                                 break;
3477
3478                         case T_STRING_LITERAL:
3479                                 wres = concat_wide_string_string(&wres, &token.v.string);
3480                                 break;
3481
3482                         default: {
3483                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
3484                                 cnst->base.type         = type_wchar_t_ptr;
3485                                 cnst->wide_string.value = wres;
3486                                 return cnst;
3487                         }
3488                 }
3489                 next_token();
3490         }
3491 }
3492
3493 /**
3494  * Parse an integer constant.
3495  */
3496 static expression_t *parse_int_const(void)
3497 {
3498         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3499         cnst->base.source_position = HERE;
3500         cnst->base.type            = token.datatype;
3501         cnst->conste.v.int_value   = token.v.intvalue;
3502
3503         next_token();
3504
3505         return cnst;
3506 }
3507
3508 /**
3509  * Parse a character constant.
3510  */
3511 static expression_t *parse_char_const(void)
3512 {
3513         expression_t *cnst         = allocate_expression_zero(EXPR_CHAR_CONST);
3514         cnst->base.source_position = HERE;
3515         cnst->base.type            = token.datatype;
3516         cnst->conste.v.chars.begin = token.v.string.begin;
3517         cnst->conste.v.chars.size  = token.v.string.size;
3518
3519         if (cnst->conste.v.chars.size != 1) {
3520                 if (warning.multichar && (c_mode & _GNUC)) {
3521                         /* TODO */
3522                         warningf(HERE, "multi-character character constant");
3523                 } else {
3524                         errorf(HERE, "more than 1 characters in character constant");
3525                 }
3526         }
3527         next_token();
3528
3529         return cnst;
3530 }
3531
3532 /**
3533  * Parse a float constant.
3534  */
3535 static expression_t *parse_float_const(void)
3536 {
3537         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
3538         cnst->base.type            = token.datatype;
3539         cnst->conste.v.float_value = token.v.floatvalue;
3540
3541         next_token();
3542
3543         return cnst;
3544 }
3545
3546 static declaration_t *create_implicit_function(symbol_t *symbol,
3547                 const source_position_t source_position)
3548 {
3549         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION, source_position);
3550         ntype->function.return_type            = type_int;
3551         ntype->function.unspecified_parameters = true;
3552
3553         type_t *type = typehash_insert(ntype);
3554         if(type != ntype) {
3555                 free_type(ntype);
3556         }
3557
3558         declaration_t *const declaration = allocate_declaration_zero();
3559         declaration->storage_class   = STORAGE_CLASS_EXTERN;
3560         declaration->type            = type;
3561         declaration->symbol          = symbol;
3562         declaration->source_position = source_position;
3563         declaration->parent_scope  = global_scope;
3564
3565         scope_t *old_scope = scope;
3566         set_scope(global_scope);
3567
3568         environment_push(declaration);
3569         /* prepends the declaration to the global declarations list */
3570         declaration->next   = scope->declarations;
3571         scope->declarations = declaration;
3572
3573         assert(scope == global_scope);
3574         set_scope(old_scope);
3575
3576         return declaration;
3577 }
3578
3579 /**
3580  * Creates a return_type (func)(argument_type) function type if not
3581  * already exists.
3582  *
3583  * @param return_type    the return type
3584  * @param argument_type  the argument type
3585  */
3586 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3587 {
3588         function_parameter_t *parameter
3589                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3590         memset(parameter, 0, sizeof(parameter[0]));
3591         parameter->type = argument_type;
3592
3593         type_t *type               = allocate_type_zero(TYPE_FUNCTION, builtin_source_position);
3594         type->function.return_type = return_type;
3595         type->function.parameters  = parameter;
3596
3597         type_t *result = typehash_insert(type);
3598         if(result != type) {
3599                 free_type(type);
3600         }
3601
3602         return result;
3603 }
3604
3605 /**
3606  * Creates a function type for some function like builtins.
3607  *
3608  * @param symbol   the symbol describing the builtin
3609  */
3610 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3611 {
3612         switch(symbol->ID) {
3613         case T___builtin_alloca:
3614                 return make_function_1_type(type_void_ptr, type_size_t);
3615         case T___builtin_nan:
3616                 return make_function_1_type(type_double, type_char_ptr);
3617         case T___builtin_nanf:
3618                 return make_function_1_type(type_float, type_char_ptr);
3619         case T___builtin_nand:
3620                 return make_function_1_type(type_long_double, type_char_ptr);
3621         case T___builtin_va_end:
3622                 return make_function_1_type(type_void, type_valist);
3623         default:
3624                 panic("not implemented builtin symbol found");
3625         }
3626 }
3627
3628 /**
3629  * Performs automatic type cast as described in Â§ 6.3.2.1.
3630  *
3631  * @param orig_type  the original type
3632  */
3633 static type_t *automatic_type_conversion(type_t *orig_type)
3634 {
3635         type_t *type = skip_typeref(orig_type);
3636         if(is_type_array(type)) {
3637                 array_type_t *array_type   = &type->array;
3638                 type_t       *element_type = array_type->element_type;
3639                 unsigned      qualifiers   = array_type->type.qualifiers;
3640
3641                 return make_pointer_type(element_type, qualifiers);
3642         }
3643
3644         if(is_type_function(type)) {
3645                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3646         }
3647
3648         return orig_type;
3649 }
3650
3651 /**
3652  * reverts the automatic casts of array to pointer types and function
3653  * to function-pointer types as defined Â§ 6.3.2.1
3654  */
3655 type_t *revert_automatic_type_conversion(const expression_t *expression)
3656 {
3657         switch (expression->kind) {
3658                 case EXPR_REFERENCE: return expression->reference.declaration->type;
3659                 case EXPR_SELECT:    return expression->select.compound_entry->type;
3660
3661                 case EXPR_UNARY_DEREFERENCE: {
3662                         const expression_t *const value = expression->unary.value;
3663                         type_t             *const type  = skip_typeref(value->base.type);
3664                         assert(is_type_pointer(type));
3665                         return type->pointer.points_to;
3666                 }
3667
3668                 case EXPR_BUILTIN_SYMBOL:
3669                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3670
3671                 case EXPR_ARRAY_ACCESS: {
3672                         const expression_t *array_ref = expression->array_access.array_ref;
3673                         type_t             *type_left = skip_typeref(array_ref->base.type);
3674                         if (!is_type_valid(type_left))
3675                                 return type_left;
3676                         assert(is_type_pointer(type_left));
3677                         return type_left->pointer.points_to;
3678                 }
3679
3680                 case EXPR_COMPOUND_LITERAL:
3681                         return expression->compound_literal.type;
3682
3683                 default: break;
3684         }
3685
3686         return expression->base.type;
3687 }
3688
3689 static expression_t *parse_reference(void)
3690 {
3691         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3692
3693         reference_expression_t *ref = &expression->reference;
3694         ref->symbol = token.v.symbol;
3695
3696         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3697
3698         source_position_t source_position = token.source_position;
3699         next_token();
3700
3701         if(declaration == NULL) {
3702                 if (! strict_mode && token.type == '(') {
3703                         /* an implicitly defined function */
3704                         if (warning.implicit_function_declaration) {
3705                                 warningf(HERE, "implicit declaration of function '%Y'",
3706                                         ref->symbol);
3707                         }
3708
3709                         declaration = create_implicit_function(ref->symbol,
3710                                                                source_position);
3711                 } else {
3712                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3713                         return create_invalid_expression();
3714                 }
3715         }
3716
3717         type_t *type         = declaration->type;
3718
3719         /* we always do the auto-type conversions; the & and sizeof parser contains
3720          * code to revert this! */
3721         type = automatic_type_conversion(type);
3722
3723         ref->declaration = declaration;
3724         ref->base.type   = type;
3725
3726         /* this declaration is used */
3727         declaration->used = true;
3728
3729         return expression;
3730 }
3731
3732 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3733 {
3734         (void) expression;
3735         (void) dest_type;
3736         /* TODO check if explicit cast is allowed and issue warnings/errors */
3737 }
3738
3739 static expression_t *parse_compound_literal(type_t *type)
3740 {
3741         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
3742
3743         parse_initializer_env_t env;
3744         env.type             = type;
3745         env.must_be_constant = false;
3746         parse_initializer(&env);
3747         type = env.type;
3748
3749         expression->compound_literal.type        = type;
3750         expression->compound_literal.initializer = env.initializer;
3751         expression->base.type                    = automatic_type_conversion(type);
3752
3753         return expression;
3754 }
3755
3756 static expression_t *parse_cast(void)
3757 {
3758         source_position_t source_position = token.source_position;
3759
3760         type_t *type  = parse_typename();
3761
3762         expect(')');
3763
3764         if(token.type == '{') {
3765                 return parse_compound_literal(type);
3766         }
3767
3768         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3769         cast->base.source_position = source_position;
3770
3771         expression_t *value = parse_sub_expression(20);
3772
3773         check_cast_allowed(value, type);
3774
3775         cast->base.type   = type;
3776         cast->unary.value = value;
3777
3778         return cast;
3779 }
3780
3781 static expression_t *parse_statement_expression(void)
3782 {
3783         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3784
3785         statement_t *statement           = parse_compound_statement();
3786         expression->statement.statement  = statement;
3787         expression->base.source_position = statement->base.source_position;
3788
3789         /* find last statement and use its type */
3790         type_t *type = type_void;
3791         const statement_t *stmt = statement->compound.statements;
3792         if (stmt != NULL) {
3793                 while (stmt->base.next != NULL)
3794                         stmt = stmt->base.next;
3795
3796                 if (stmt->kind == STATEMENT_EXPRESSION) {
3797                         type = stmt->expression.expression->base.type;
3798                 }
3799         } else {
3800                 warningf(expression->base.source_position, "empty statement expression ({})");
3801         }
3802         expression->base.type = type;
3803
3804         expect(')');
3805
3806         return expression;
3807 }
3808
3809 static expression_t *parse_brace_expression(void)
3810 {
3811         eat('(');
3812
3813         switch(token.type) {
3814         case '{':
3815                 /* gcc extension: a statement expression */
3816                 return parse_statement_expression();
3817
3818         TYPE_QUALIFIERS
3819         TYPE_SPECIFIERS
3820                 return parse_cast();
3821         case T_IDENTIFIER:
3822                 if(is_typedef_symbol(token.v.symbol)) {
3823                         return parse_cast();
3824                 }
3825         }
3826
3827         expression_t *result = parse_expression();
3828         expect(')');
3829
3830         return result;
3831 }
3832
3833 static expression_t *parse_function_keyword(void)
3834 {
3835         next_token();
3836         /* TODO */
3837
3838         if (current_function == NULL) {
3839                 errorf(HERE, "'__func__' used outside of a function");
3840         }
3841
3842         expression_t *expression = allocate_expression_zero(EXPR_FUNCTION);
3843         expression->base.type    = type_char_ptr;
3844
3845         return expression;
3846 }
3847
3848 static expression_t *parse_pretty_function_keyword(void)
3849 {
3850         eat(T___PRETTY_FUNCTION__);
3851         /* TODO */
3852
3853         if (current_function == NULL) {
3854                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3855         }
3856
3857         expression_t *expression = allocate_expression_zero(EXPR_PRETTY_FUNCTION);
3858         expression->base.type    = type_char_ptr;
3859
3860         return expression;
3861 }
3862
3863 static designator_t *parse_designator(void)
3864 {
3865         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
3866         result->source_position = HERE;
3867
3868         if(token.type != T_IDENTIFIER) {
3869                 parse_error_expected("while parsing member designator",
3870                                      T_IDENTIFIER, 0);
3871                 eat_paren();
3872                 return NULL;
3873         }
3874         result->symbol = token.v.symbol;
3875         next_token();
3876
3877         designator_t *last_designator = result;
3878         while(true) {
3879                 if(token.type == '.') {
3880                         next_token();
3881                         if(token.type != T_IDENTIFIER) {
3882                                 parse_error_expected("while parsing member designator",
3883                                                      T_IDENTIFIER, 0);
3884                                 eat_paren();
3885                                 return NULL;
3886                         }
3887                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3888                         designator->source_position = HERE;
3889                         designator->symbol          = token.v.symbol;
3890                         next_token();
3891
3892                         last_designator->next = designator;
3893                         last_designator       = designator;
3894                         continue;
3895                 }
3896                 if(token.type == '[') {
3897                         next_token();
3898                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
3899                         designator->source_position = HERE;
3900                         designator->array_index     = parse_expression();
3901                         if(designator->array_index == NULL) {
3902                                 eat_paren();
3903                                 return NULL;
3904                         }
3905                         expect(']');
3906
3907                         last_designator->next = designator;
3908                         last_designator       = designator;
3909                         continue;
3910                 }
3911                 break;
3912         }
3913
3914         return result;
3915 }
3916
3917 static expression_t *parse_offsetof(void)
3918 {
3919         eat(T___builtin_offsetof);
3920
3921         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
3922         expression->base.type    = type_size_t;
3923
3924         expect('(');
3925         type_t *type = parse_typename();
3926         expect(',');
3927         designator_t *designator = parse_designator();
3928         expect(')');
3929
3930         expression->offsetofe.type       = type;
3931         expression->offsetofe.designator = designator;
3932
3933         type_path_t path;
3934         memset(&path, 0, sizeof(path));
3935         path.top_type = type;
3936         path.path     = NEW_ARR_F(type_path_entry_t, 0);
3937
3938         descend_into_subtype(&path);
3939
3940         if(!walk_designator(&path, designator, true)) {
3941                 return create_invalid_expression();
3942         }
3943
3944         DEL_ARR_F(path.path);
3945
3946         return expression;
3947 }
3948
3949 static expression_t *parse_va_start(void)
3950 {
3951         eat(T___builtin_va_start);
3952
3953         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3954
3955         expect('(');
3956         expression->va_starte.ap = parse_assignment_expression();
3957         expect(',');
3958         expression_t *const expr = parse_assignment_expression();
3959         if (expr->kind == EXPR_REFERENCE) {
3960                 declaration_t *const decl = expr->reference.declaration;
3961                 if (decl == NULL)
3962                         return create_invalid_expression();
3963                 if (decl->parent_scope == &current_function->scope &&
3964                     decl->next == NULL) {
3965                         expression->va_starte.parameter = decl;
3966                         expect(')');
3967                         return expression;
3968                 }
3969         }
3970         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3971
3972         return create_invalid_expression();
3973 }
3974
3975 static expression_t *parse_va_arg(void)
3976 {
3977         eat(T___builtin_va_arg);
3978
3979         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3980
3981         expect('(');
3982         expression->va_arge.ap = parse_assignment_expression();
3983         expect(',');
3984         expression->base.type = parse_typename();
3985         expect(')');
3986
3987         return expression;
3988 }
3989
3990 static expression_t *parse_builtin_symbol(void)
3991 {
3992         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3993
3994         symbol_t *symbol = token.v.symbol;
3995
3996         expression->builtin_symbol.symbol = symbol;
3997         next_token();
3998
3999         type_t *type = get_builtin_symbol_type(symbol);
4000         type = automatic_type_conversion(type);
4001
4002         expression->base.type = type;
4003         return expression;
4004 }
4005
4006 static expression_t *parse_builtin_constant(void)
4007 {
4008         eat(T___builtin_constant_p);
4009
4010         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
4011
4012         expect('(');
4013         expression->builtin_constant.value = parse_assignment_expression();
4014         expect(')');
4015         expression->base.type = type_int;
4016
4017         return expression;
4018 }
4019
4020 static expression_t *parse_builtin_prefetch(void)
4021 {
4022         eat(T___builtin_prefetch);
4023
4024         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
4025
4026         expect('(');
4027         expression->builtin_prefetch.adr = parse_assignment_expression();
4028         if (token.type == ',') {
4029                 next_token();
4030                 expression->builtin_prefetch.rw = parse_assignment_expression();
4031         }
4032         if (token.type == ',') {
4033                 next_token();
4034                 expression->builtin_prefetch.locality = parse_assignment_expression();
4035         }
4036         expect(')');
4037         expression->base.type = type_void;
4038
4039         return expression;
4040 }
4041
4042 static expression_t *parse_compare_builtin(void)
4043 {
4044         expression_t *expression;
4045
4046         switch(token.type) {
4047         case T___builtin_isgreater:
4048                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
4049                 break;
4050         case T___builtin_isgreaterequal:
4051                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
4052                 break;
4053         case T___builtin_isless:
4054                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
4055                 break;
4056         case T___builtin_islessequal:
4057                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
4058                 break;
4059         case T___builtin_islessgreater:
4060                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
4061                 break;
4062         case T___builtin_isunordered:
4063                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
4064                 break;
4065         default:
4066                 panic("invalid compare builtin found");
4067                 break;
4068         }
4069         expression->base.source_position = HERE;
4070         next_token();
4071
4072         expect('(');
4073         expression->binary.left = parse_assignment_expression();
4074         expect(',');
4075         expression->binary.right = parse_assignment_expression();
4076         expect(')');
4077
4078         type_t *const orig_type_left  = expression->binary.left->base.type;
4079         type_t *const orig_type_right = expression->binary.right->base.type;
4080
4081         type_t *const type_left  = skip_typeref(orig_type_left);
4082         type_t *const type_right = skip_typeref(orig_type_right);
4083         if(!is_type_float(type_left) && !is_type_float(type_right)) {
4084                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4085                         type_error_incompatible("invalid operands in comparison",
4086                                 expression->base.source_position, orig_type_left, orig_type_right);
4087                 }
4088         } else {
4089                 semantic_comparison(&expression->binary);
4090         }
4091
4092         return expression;
4093 }
4094
4095 static expression_t *parse_builtin_expect(void)
4096 {
4097         eat(T___builtin_expect);
4098
4099         expression_t *expression
4100                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
4101
4102         expect('(');
4103         expression->binary.left = parse_assignment_expression();
4104         expect(',');
4105         expression->binary.right = parse_constant_expression();
4106         expect(')');
4107
4108         expression->base.type = expression->binary.left->base.type;
4109
4110         return expression;
4111 }
4112
4113 static expression_t *parse_assume(void) {
4114         eat(T_assume);
4115
4116         expression_t *expression
4117                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
4118
4119         expect('(');
4120         expression->unary.value = parse_assignment_expression();
4121         expect(')');
4122
4123         expression->base.type = type_void;
4124         return expression;
4125 }
4126
4127 static expression_t *parse_primary_expression(void)
4128 {
4129         switch (token.type) {
4130                 case T_INTEGER:                  return parse_int_const();
4131                 case T_CHARS:                    return parse_char_const();
4132                 case T_FLOATINGPOINT:            return parse_float_const();
4133                 case T_STRING_LITERAL:
4134                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
4135                 case T_IDENTIFIER:               return parse_reference();
4136                 case T___FUNCTION__:
4137                 case T___func__:                 return parse_function_keyword();
4138                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
4139                 case T___builtin_offsetof:       return parse_offsetof();
4140                 case T___builtin_va_start:       return parse_va_start();
4141                 case T___builtin_va_arg:         return parse_va_arg();
4142                 case T___builtin_expect:         return parse_builtin_expect();
4143                 case T___builtin_alloca:
4144                 case T___builtin_nan:
4145                 case T___builtin_nand:
4146                 case T___builtin_nanf:
4147                 case T___builtin_va_end:         return parse_builtin_symbol();
4148                 case T___builtin_isgreater:
4149                 case T___builtin_isgreaterequal:
4150                 case T___builtin_isless:
4151                 case T___builtin_islessequal:
4152                 case T___builtin_islessgreater:
4153                 case T___builtin_isunordered:    return parse_compare_builtin();
4154                 case T___builtin_constant_p:     return parse_builtin_constant();
4155                 case T___builtin_prefetch:       return parse_builtin_prefetch();
4156                 case T_assume:                   return parse_assume();
4157
4158                 case '(':                        return parse_brace_expression();
4159         }
4160
4161         errorf(HERE, "unexpected token %K, expected an expression", &token);
4162         eat_statement();
4163
4164         return create_invalid_expression();
4165 }
4166
4167 /**
4168  * Check if the expression has the character type and issue a warning then.
4169  */
4170 static void check_for_char_index_type(const expression_t *expression) {
4171         type_t       *const type      = expression->base.type;
4172         const type_t *const base_type = skip_typeref(type);
4173
4174         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
4175                         warning.char_subscripts) {
4176                 warningf(expression->base.source_position,
4177                         "array subscript has type '%T'", type);
4178         }
4179 }
4180
4181 static expression_t *parse_array_expression(unsigned precedence,
4182                                             expression_t *left)
4183 {
4184         (void) precedence;
4185
4186         eat('[');
4187
4188         expression_t *inside = parse_expression();
4189
4190         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
4191
4192         array_access_expression_t *array_access = &expression->array_access;
4193
4194         type_t *const orig_type_left   = left->base.type;
4195         type_t *const orig_type_inside = inside->base.type;
4196
4197         type_t *const type_left   = skip_typeref(orig_type_left);
4198         type_t *const type_inside = skip_typeref(orig_type_inside);
4199
4200         type_t *return_type;
4201         if (is_type_pointer(type_left)) {
4202                 return_type             = type_left->pointer.points_to;
4203                 array_access->array_ref = left;
4204                 array_access->index     = inside;
4205                 check_for_char_index_type(inside);
4206         } else if (is_type_pointer(type_inside)) {
4207                 return_type             = type_inside->pointer.points_to;
4208                 array_access->array_ref = inside;
4209                 array_access->index     = left;
4210                 array_access->flipped   = true;
4211                 check_for_char_index_type(left);
4212         } else {
4213                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
4214                         errorf(HERE,
4215                                 "array access on object with non-pointer types '%T', '%T'",
4216                                 orig_type_left, orig_type_inside);
4217                 }
4218                 return_type             = type_error_type;
4219                 array_access->array_ref = create_invalid_expression();
4220         }
4221
4222         if(token.type != ']') {
4223                 parse_error_expected("Problem while parsing array access", ']', 0);
4224                 return expression;
4225         }
4226         next_token();
4227
4228         return_type           = automatic_type_conversion(return_type);
4229         expression->base.type = return_type;
4230
4231         return expression;
4232 }
4233
4234 static expression_t *parse_typeprop(expression_kind_t kind, unsigned precedence)
4235 {
4236         expression_t *tp_expression = allocate_expression_zero(kind);
4237         tp_expression->base.type    = type_size_t;
4238
4239         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
4240                 next_token();
4241                 tp_expression->typeprop.type = parse_typename();
4242                 expect(')');
4243         } else {
4244                 expression_t *expression = parse_sub_expression(precedence);
4245                 expression->base.type    = revert_automatic_type_conversion(expression);
4246
4247                 tp_expression->typeprop.type          = expression->base.type;
4248                 tp_expression->typeprop.tp_expression = expression;
4249         }
4250
4251         return tp_expression;
4252 }
4253
4254 static expression_t *parse_sizeof(unsigned precedence)
4255 {
4256         eat(T_sizeof);
4257         return parse_typeprop(EXPR_SIZEOF, precedence);
4258 }
4259
4260 static expression_t *parse_alignof(unsigned precedence)
4261 {
4262         eat(T___alignof__);
4263         return parse_typeprop(EXPR_SIZEOF, precedence);
4264 }
4265
4266 static expression_t *parse_select_expression(unsigned precedence,
4267                                              expression_t *compound)
4268 {
4269         (void) precedence;
4270         assert(token.type == '.' || token.type == T_MINUSGREATER);
4271
4272         bool is_pointer = (token.type == T_MINUSGREATER);
4273         next_token();
4274
4275         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
4276         select->select.compound = compound;
4277
4278         if(token.type != T_IDENTIFIER) {
4279                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
4280                 return select;
4281         }
4282         symbol_t *symbol      = token.v.symbol;
4283         select->select.symbol = symbol;
4284         next_token();
4285
4286         type_t *const orig_type = compound->base.type;
4287         type_t *const type      = skip_typeref(orig_type);
4288
4289         type_t *type_left = type;
4290         if(is_pointer) {
4291                 if (!is_type_pointer(type)) {
4292                         if (is_type_valid(type)) {
4293                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
4294                         }
4295                         return create_invalid_expression();
4296                 }
4297                 type_left = type->pointer.points_to;
4298         }
4299         type_left = skip_typeref(type_left);
4300
4301         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
4302             type_left->kind != TYPE_COMPOUND_UNION) {
4303                 if (is_type_valid(type_left)) {
4304                         errorf(HERE, "request for member '%Y' in something not a struct or "
4305                                "union, but '%T'", symbol, type_left);
4306                 }
4307                 return create_invalid_expression();
4308         }
4309
4310         declaration_t *const declaration = type_left->compound.declaration;
4311
4312         if(!declaration->init.is_defined) {
4313                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
4314                        symbol, type_left);
4315                 return create_invalid_expression();
4316         }
4317
4318         declaration_t *iter = find_compound_entry(declaration, symbol);
4319         if(iter == NULL) {
4320                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
4321                 return create_invalid_expression();
4322         }
4323
4324         /* we always do the auto-type conversions; the & and sizeof parser contains
4325          * code to revert this! */
4326         type_t *expression_type = automatic_type_conversion(iter->type);
4327
4328         select->select.compound_entry = iter;
4329         select->base.type             = expression_type;
4330
4331         if(expression_type->kind == TYPE_BITFIELD) {
4332                 expression_t *extract
4333                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
4334                 extract->unary.value = select;
4335                 extract->base.type   = expression_type->bitfield.base;
4336
4337                 return extract;
4338         }
4339
4340         return select;
4341 }
4342
4343 /**
4344  * Parse a call expression, ie. expression '( ... )'.
4345  *
4346  * @param expression  the function address
4347  */
4348 static expression_t *parse_call_expression(unsigned precedence,
4349                                            expression_t *expression)
4350 {
4351         (void) precedence;
4352         expression_t *result = allocate_expression_zero(EXPR_CALL);
4353
4354         call_expression_t *call = &result->call;
4355         call->function          = expression;
4356
4357         type_t *const orig_type = expression->base.type;
4358         type_t *const type      = skip_typeref(orig_type);
4359
4360         function_type_t *function_type = NULL;
4361         if (is_type_pointer(type)) {
4362                 type_t *const to_type = skip_typeref(type->pointer.points_to);
4363
4364                 if (is_type_function(to_type)) {
4365                         function_type   = &to_type->function;
4366                         call->base.type = function_type->return_type;
4367                 }
4368         }
4369
4370         if (function_type == NULL && is_type_valid(type)) {
4371                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
4372         }
4373
4374         /* parse arguments */
4375         eat('(');
4376
4377         if(token.type != ')') {
4378                 call_argument_t *last_argument = NULL;
4379
4380                 while(true) {
4381                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
4382
4383                         argument->expression = parse_assignment_expression();
4384                         if(last_argument == NULL) {
4385                                 call->arguments = argument;
4386                         } else {
4387                                 last_argument->next = argument;
4388                         }
4389                         last_argument = argument;
4390
4391                         if(token.type != ',')
4392                                 break;
4393                         next_token();
4394                 }
4395         }
4396         expect(')');
4397
4398         if(function_type != NULL) {
4399                 function_parameter_t *parameter = function_type->parameters;
4400                 call_argument_t      *argument  = call->arguments;
4401                 for( ; parameter != NULL && argument != NULL;
4402                                 parameter = parameter->next, argument = argument->next) {
4403                         type_t *expected_type = parameter->type;
4404                         /* TODO report scope in error messages */
4405                         expression_t *const arg_expr = argument->expression;
4406                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
4407                         if (res_type == NULL) {
4408                                 /* TODO improve error message */
4409                                 errorf(arg_expr->base.source_position,
4410                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
4411                                         arg_expr, arg_expr->base.type, expected_type);
4412                         } else {
4413                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
4414                         }
4415                 }
4416                 /* too few parameters */
4417                 if(parameter != NULL) {
4418                         errorf(HERE, "too few arguments to function '%E'", expression);
4419                 } else if(argument != NULL) {
4420                         /* too many parameters */
4421                         if(!function_type->variadic
4422                                         && !function_type->unspecified_parameters) {
4423                                 errorf(HERE, "too many arguments to function '%E'", expression);
4424                         } else {
4425                                 /* do default promotion */
4426                                 for( ; argument != NULL; argument = argument->next) {
4427                                         type_t *type = argument->expression->base.type;
4428
4429                                         type = skip_typeref(type);
4430                                         if(is_type_integer(type)) {
4431                                                 type = promote_integer(type);
4432                                         } else if(type == type_float) {
4433                                                 type = type_double;
4434                                         }
4435
4436                                         argument->expression
4437                                                 = create_implicit_cast(argument->expression, type);
4438                                 }
4439
4440                                 check_format(&result->call);
4441                         }
4442                 } else {
4443                         check_format(&result->call);
4444                 }
4445         }
4446
4447         return result;
4448 }
4449
4450 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
4451
4452 static bool same_compound_type(const type_t *type1, const type_t *type2)
4453 {
4454         return
4455                 is_type_compound(type1) &&
4456                 type1->kind == type2->kind &&
4457                 type1->compound.declaration == type2->compound.declaration;
4458 }
4459
4460 /**
4461  * Parse a conditional expression, ie. 'expression ? ... : ...'.
4462  *
4463  * @param expression  the conditional expression
4464  */
4465 static expression_t *parse_conditional_expression(unsigned precedence,
4466                                                   expression_t *expression)
4467 {
4468         eat('?');
4469
4470         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
4471
4472         conditional_expression_t *conditional = &result->conditional;
4473         conditional->condition = expression;
4474
4475         /* 6.5.15.2 */
4476         type_t *const condition_type_orig = expression->base.type;
4477         type_t *const condition_type      = skip_typeref(condition_type_orig);
4478         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
4479                 type_error("expected a scalar type in conditional condition",
4480                            expression->base.source_position, condition_type_orig);
4481         }
4482
4483         expression_t *true_expression = parse_expression();
4484         expect(':');
4485         expression_t *false_expression = parse_sub_expression(precedence);
4486
4487         type_t *const orig_true_type  = true_expression->base.type;
4488         type_t *const orig_false_type = false_expression->base.type;
4489         type_t *const true_type       = skip_typeref(orig_true_type);
4490         type_t *const false_type      = skip_typeref(orig_false_type);
4491
4492         /* 6.5.15.3 */
4493         type_t *result_type;
4494         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
4495                 result_type = semantic_arithmetic(true_type, false_type);
4496
4497                 true_expression  = create_implicit_cast(true_expression, result_type);
4498                 false_expression = create_implicit_cast(false_expression, result_type);
4499
4500                 conditional->true_expression  = true_expression;
4501                 conditional->false_expression = false_expression;
4502                 conditional->base.type        = result_type;
4503         } else if (same_compound_type(true_type, false_type) || (
4504             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
4505             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
4506                 )) {
4507                 /* just take 1 of the 2 types */
4508                 result_type = true_type;
4509         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
4510                         && pointers_compatible(true_type, false_type)) {
4511                 /* ok */
4512                 result_type = true_type;
4513         } else if (is_type_pointer(true_type)
4514                         && is_null_pointer_constant(false_expression)) {
4515                 result_type = true_type;
4516         } else if (is_type_pointer(false_type)
4517                         && is_null_pointer_constant(true_expression)) {
4518                 result_type = false_type;
4519         } else {
4520                 /* TODO: one pointer to void*, other some pointer */
4521
4522                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
4523                         type_error_incompatible("while parsing conditional",
4524                                                 expression->base.source_position, true_type,
4525                                                 false_type);
4526                 }
4527                 result_type = type_error_type;
4528         }
4529
4530         conditional->true_expression
4531                 = create_implicit_cast(true_expression, result_type);
4532         conditional->false_expression
4533                 = create_implicit_cast(false_expression, result_type);
4534         conditional->base.type = result_type;
4535         return result;
4536 }
4537
4538 /**
4539  * Parse an extension expression.
4540  */
4541 static expression_t *parse_extension(unsigned precedence)
4542 {
4543         eat(T___extension__);
4544
4545         /* TODO enable extensions */
4546         expression_t *expression = parse_sub_expression(precedence);
4547         /* TODO disable extensions */
4548         return expression;
4549 }
4550
4551 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4552 {
4553         eat(T___builtin_classify_type);
4554
4555         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4556         result->base.type    = type_int;
4557
4558         expect('(');
4559         expression_t *expression = parse_sub_expression(precedence);
4560         expect(')');
4561         result->classify_type.type_expression = expression;
4562
4563         return result;
4564 }
4565
4566 static void semantic_incdec(unary_expression_t *expression)
4567 {
4568         type_t *const orig_type = expression->value->base.type;
4569         type_t *const type      = skip_typeref(orig_type);
4570         /* TODO !is_type_real && !is_type_pointer */
4571         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4572                 if (is_type_valid(type)) {
4573                         /* TODO: improve error message */
4574                         errorf(HERE, "operation needs an arithmetic or pointer type");
4575                 }
4576                 return;
4577         }
4578
4579         expression->base.type = orig_type;
4580 }
4581
4582 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4583 {
4584         type_t *const orig_type = expression->value->base.type;
4585         type_t *const type      = skip_typeref(orig_type);
4586         if(!is_type_arithmetic(type)) {
4587                 if (is_type_valid(type)) {
4588                         /* TODO: improve error message */
4589                         errorf(HERE, "operation needs an arithmetic type");
4590                 }
4591                 return;
4592         }
4593
4594         expression->base.type = orig_type;
4595 }
4596
4597 static void semantic_unexpr_scalar(unary_expression_t *expression)
4598 {
4599         type_t *const orig_type = expression->value->base.type;
4600         type_t *const type      = skip_typeref(orig_type);
4601         if (!is_type_scalar(type)) {
4602                 if (is_type_valid(type)) {
4603                         errorf(HERE, "operand of ! must be of scalar type");
4604                 }
4605                 return;
4606         }
4607
4608         expression->base.type = orig_type;
4609 }
4610
4611 static void semantic_unexpr_integer(unary_expression_t *expression)
4612 {
4613         type_t *const orig_type = expression->value->base.type;
4614         type_t *const type      = skip_typeref(orig_type);
4615         if (!is_type_integer(type)) {
4616                 if (is_type_valid(type)) {
4617                         errorf(HERE, "operand of ~ must be of integer type");
4618                 }
4619                 return;
4620         }
4621
4622         expression->base.type = orig_type;
4623 }
4624
4625 static void semantic_dereference(unary_expression_t *expression)
4626 {
4627         type_t *const orig_type = expression->value->base.type;
4628         type_t *const type      = skip_typeref(orig_type);
4629         if(!is_type_pointer(type)) {
4630                 if (is_type_valid(type)) {
4631                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4632                 }
4633                 return;
4634         }
4635
4636         type_t *result_type   = type->pointer.points_to;
4637         result_type           = automatic_type_conversion(result_type);
4638         expression->base.type = result_type;
4639 }
4640
4641 /**
4642  * Check the semantic of the address taken expression.
4643  */
4644 static void semantic_take_addr(unary_expression_t *expression)
4645 {
4646         expression_t *value = expression->value;
4647         value->base.type    = revert_automatic_type_conversion(value);
4648
4649         type_t *orig_type = value->base.type;
4650         if(!is_type_valid(orig_type))
4651                 return;
4652
4653         if(value->kind == EXPR_REFERENCE) {
4654                 declaration_t *const declaration = value->reference.declaration;
4655                 if(declaration != NULL) {
4656                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4657                                 errorf(expression->base.source_position,
4658                                         "address of register variable '%Y' requested",
4659                                         declaration->symbol);
4660                         }
4661                         declaration->address_taken = 1;
4662                 }
4663         }
4664
4665         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4666 }
4667
4668 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4669 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4670 {                                                                              \
4671         eat(token_type);                                                           \
4672                                                                                    \
4673         expression_t *unary_expression                                             \
4674                 = allocate_expression_zero(unexpression_type);                         \
4675         unary_expression->base.source_position = HERE;                             \
4676         unary_expression->unary.value = parse_sub_expression(precedence);          \
4677                                                                                    \
4678         sfunc(&unary_expression->unary);                                           \
4679                                                                                    \
4680         return unary_expression;                                                   \
4681 }
4682
4683 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4684                                semantic_unexpr_arithmetic)
4685 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4686                                semantic_unexpr_arithmetic)
4687 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4688                                semantic_unexpr_scalar)
4689 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4690                                semantic_dereference)
4691 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4692                                semantic_take_addr)
4693 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4694                                semantic_unexpr_integer)
4695 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4696                                semantic_incdec)
4697 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4698                                semantic_incdec)
4699
4700 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4701                                                sfunc)                         \
4702 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4703                                                expression_t *left)            \
4704 {                                                                             \
4705         (void) precedence;                                                        \
4706         eat(token_type);                                                          \
4707                                                                               \
4708         expression_t *unary_expression                                            \
4709                 = allocate_expression_zero(unexpression_type);                        \
4710         unary_expression->unary.value = left;                                     \
4711                                                                                   \
4712         sfunc(&unary_expression->unary);                                          \
4713                                                                               \
4714         return unary_expression;                                                  \
4715 }
4716
4717 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4718                                        EXPR_UNARY_POSTFIX_INCREMENT,
4719                                        semantic_incdec)
4720 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4721                                        EXPR_UNARY_POSTFIX_DECREMENT,
4722                                        semantic_incdec)
4723
4724 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4725 {
4726         /* TODO: handle complex + imaginary types */
4727
4728         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4729         if(type_left == type_long_double || type_right == type_long_double) {
4730                 return type_long_double;
4731         } else if(type_left == type_double || type_right == type_double) {
4732                 return type_double;
4733         } else if(type_left == type_float || type_right == type_float) {
4734                 return type_float;
4735         }
4736
4737         type_right = promote_integer(type_right);
4738         type_left  = promote_integer(type_left);
4739
4740         if(type_left == type_right)
4741                 return type_left;
4742
4743         bool signed_left  = is_type_signed(type_left);
4744         bool signed_right = is_type_signed(type_right);
4745         int  rank_left    = get_rank(type_left);
4746         int  rank_right   = get_rank(type_right);
4747         if(rank_left < rank_right) {
4748                 if(signed_left == signed_right || !signed_right) {
4749                         return type_right;
4750                 } else {
4751                         return type_left;
4752                 }
4753         } else {
4754                 if(signed_left == signed_right || !signed_left) {
4755                         return type_left;
4756                 } else {
4757                         return type_right;
4758                 }
4759         }
4760 }
4761
4762 /**
4763  * Check the semantic restrictions for a binary expression.
4764  */
4765 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4766 {
4767         expression_t *const left            = expression->left;
4768         expression_t *const right           = expression->right;
4769         type_t       *const orig_type_left  = left->base.type;
4770         type_t       *const orig_type_right = right->base.type;
4771         type_t       *const type_left       = skip_typeref(orig_type_left);
4772         type_t       *const type_right      = skip_typeref(orig_type_right);
4773
4774         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4775                 /* TODO: improve error message */
4776                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4777                         errorf(HERE, "operation needs arithmetic types");
4778                 }
4779                 return;
4780         }
4781
4782         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4783         expression->left      = create_implicit_cast(left, arithmetic_type);
4784         expression->right     = create_implicit_cast(right, arithmetic_type);
4785         expression->base.type = arithmetic_type;
4786 }
4787
4788 static void semantic_shift_op(binary_expression_t *expression)
4789 {
4790         expression_t *const left            = expression->left;
4791         expression_t *const right           = expression->right;
4792         type_t       *const orig_type_left  = left->base.type;
4793         type_t       *const orig_type_right = right->base.type;
4794         type_t       *      type_left       = skip_typeref(orig_type_left);
4795         type_t       *      type_right      = skip_typeref(orig_type_right);
4796
4797         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4798                 /* TODO: improve error message */
4799                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4800                         errorf(HERE, "operation needs integer types");
4801                 }
4802                 return;
4803         }
4804
4805         type_left  = promote_integer(type_left);
4806         type_right = promote_integer(type_right);
4807
4808         expression->left      = create_implicit_cast(left, type_left);
4809         expression->right     = create_implicit_cast(right, type_right);
4810         expression->base.type = type_left;
4811 }
4812
4813 static void semantic_add(binary_expression_t *expression)
4814 {
4815         expression_t *const left            = expression->left;
4816         expression_t *const right           = expression->right;
4817         type_t       *const orig_type_left  = left->base.type;
4818         type_t       *const orig_type_right = right->base.type;
4819         type_t       *const type_left       = skip_typeref(orig_type_left);
4820         type_t       *const type_right      = skip_typeref(orig_type_right);
4821
4822         /* Â§ 5.6.5 */
4823         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4824                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4825                 expression->left  = create_implicit_cast(left, arithmetic_type);
4826                 expression->right = create_implicit_cast(right, arithmetic_type);
4827                 expression->base.type = arithmetic_type;
4828                 return;
4829         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4830                 expression->base.type = type_left;
4831         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4832                 expression->base.type = type_right;
4833         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4834                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4835         }
4836 }
4837
4838 static void semantic_sub(binary_expression_t *expression)
4839 {
4840         expression_t *const left            = expression->left;
4841         expression_t *const right           = expression->right;
4842         type_t       *const orig_type_left  = left->base.type;
4843         type_t       *const orig_type_right = right->base.type;
4844         type_t       *const type_left       = skip_typeref(orig_type_left);
4845         type_t       *const type_right      = skip_typeref(orig_type_right);
4846
4847         /* Â§ 5.6.5 */
4848         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4849                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4850                 expression->left        = create_implicit_cast(left, arithmetic_type);
4851                 expression->right       = create_implicit_cast(right, arithmetic_type);
4852                 expression->base.type =  arithmetic_type;
4853                 return;
4854         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4855                 expression->base.type = type_left;
4856         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4857                 if(!pointers_compatible(type_left, type_right)) {
4858                         errorf(HERE,
4859                                "pointers to incompatible objects to binary '-' ('%T', '%T')",
4860                                orig_type_left, orig_type_right);
4861                 } else {
4862                         expression->base.type = type_ptrdiff_t;
4863                 }
4864         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4865                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')",
4866                        orig_type_left, orig_type_right);
4867         }
4868 }
4869
4870 /**
4871  * Check the semantics of comparison expressions.
4872  *
4873  * @param expression   The expression to check.
4874  */
4875 static void semantic_comparison(binary_expression_t *expression)
4876 {
4877         expression_t *left            = expression->left;
4878         expression_t *right           = expression->right;
4879         type_t       *orig_type_left  = left->base.type;
4880         type_t       *orig_type_right = right->base.type;
4881
4882         type_t *type_left  = skip_typeref(orig_type_left);
4883         type_t *type_right = skip_typeref(orig_type_right);
4884
4885         /* TODO non-arithmetic types */
4886         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4887                 if (warning.sign_compare &&
4888                     (expression->base.kind != EXPR_BINARY_EQUAL &&
4889                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
4890                     (is_type_signed(type_left) != is_type_signed(type_right))) {
4891                         warningf(expression->base.source_position,
4892                                  "comparison between signed and unsigned");
4893                 }
4894                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4895                 expression->left        = create_implicit_cast(left, arithmetic_type);
4896                 expression->right       = create_implicit_cast(right, arithmetic_type);
4897                 expression->base.type   = arithmetic_type;
4898                 if (warning.float_equal &&
4899                     (expression->base.kind == EXPR_BINARY_EQUAL ||
4900                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
4901                     is_type_float(arithmetic_type)) {
4902                         warningf(expression->base.source_position,
4903                                  "comparing floating point with == or != is unsafe");
4904                 }
4905         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4906                 /* TODO check compatibility */
4907         } else if (is_type_pointer(type_left)) {
4908                 expression->right = create_implicit_cast(right, type_left);
4909         } else if (is_type_pointer(type_right)) {
4910                 expression->left = create_implicit_cast(left, type_right);
4911         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4912                 type_error_incompatible("invalid operands in comparison",
4913                                         expression->base.source_position,
4914                                         type_left, type_right);
4915         }
4916         expression->base.type = type_int;
4917 }
4918
4919 static void semantic_arithmetic_assign(binary_expression_t *expression)
4920 {
4921         expression_t *left            = expression->left;
4922         expression_t *right           = expression->right;
4923         type_t       *orig_type_left  = left->base.type;
4924         type_t       *orig_type_right = right->base.type;
4925
4926         type_t *type_left  = skip_typeref(orig_type_left);
4927         type_t *type_right = skip_typeref(orig_type_right);
4928
4929         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4930                 /* TODO: improve error message */
4931                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4932                         errorf(HERE, "operation needs arithmetic types");
4933                 }
4934                 return;
4935         }
4936
4937         /* combined instructions are tricky. We can't create an implicit cast on
4938          * the left side, because we need the uncasted form for the store.
4939          * The ast2firm pass has to know that left_type must be right_type
4940          * for the arithmetic operation and create a cast by itself */
4941         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4942         expression->right       = create_implicit_cast(right, arithmetic_type);
4943         expression->base.type   = type_left;
4944 }
4945
4946 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4947 {
4948         expression_t *const left            = expression->left;
4949         expression_t *const right           = expression->right;
4950         type_t       *const orig_type_left  = left->base.type;
4951         type_t       *const orig_type_right = right->base.type;
4952         type_t       *const type_left       = skip_typeref(orig_type_left);
4953         type_t       *const type_right      = skip_typeref(orig_type_right);
4954
4955         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4956                 /* combined instructions are tricky. We can't create an implicit cast on
4957                  * the left side, because we need the uncasted form for the store.
4958                  * The ast2firm pass has to know that left_type must be right_type
4959                  * for the arithmetic operation and create a cast by itself */
4960                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4961                 expression->right     = create_implicit_cast(right, arithmetic_type);
4962                 expression->base.type = type_left;
4963         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4964                 expression->base.type = type_left;
4965         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4966                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4967         }
4968 }
4969
4970 /**
4971  * Check the semantic restrictions of a logical expression.
4972  */
4973 static void semantic_logical_op(binary_expression_t *expression)
4974 {
4975         expression_t *const left            = expression->left;
4976         expression_t *const right           = expression->right;
4977         type_t       *const orig_type_left  = left->base.type;
4978         type_t       *const orig_type_right = right->base.type;
4979         type_t       *const type_left       = skip_typeref(orig_type_left);
4980         type_t       *const type_right      = skip_typeref(orig_type_right);
4981
4982         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4983                 /* TODO: improve error message */
4984                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4985                         errorf(HERE, "operation needs scalar types");
4986                 }
4987                 return;
4988         }
4989
4990         expression->base.type = type_int;
4991 }
4992
4993 /**
4994  * Checks if a compound type has constant fields.
4995  */
4996 static bool has_const_fields(const compound_type_t *type)
4997 {
4998         const scope_t       *scope       = &type->declaration->scope;
4999         const declaration_t *declaration = scope->declarations;
5000
5001         for (; declaration != NULL; declaration = declaration->next) {
5002                 if (declaration->namespc != NAMESPACE_NORMAL)
5003                         continue;
5004
5005                 const type_t *decl_type = skip_typeref(declaration->type);
5006                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
5007                         return true;
5008         }
5009         /* TODO */
5010         return false;
5011 }
5012
5013 /**
5014  * Check the semantic restrictions of a binary assign expression.
5015  */
5016 static void semantic_binexpr_assign(binary_expression_t *expression)
5017 {
5018         expression_t *left           = expression->left;
5019         type_t       *orig_type_left = left->base.type;
5020
5021         type_t *type_left = revert_automatic_type_conversion(left);
5022         type_left         = skip_typeref(orig_type_left);
5023
5024         /* must be a modifiable lvalue */
5025         if (is_type_array(type_left)) {
5026                 errorf(HERE, "cannot assign to arrays ('%E')", left);
5027                 return;
5028         }
5029         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
5030                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
5031                        orig_type_left);
5032                 return;
5033         }
5034         if(is_type_incomplete(type_left)) {
5035                 errorf(HERE,
5036                        "left-hand side of assignment '%E' has incomplete type '%T'",
5037                        left, orig_type_left);
5038                 return;
5039         }
5040         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
5041                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
5042                        left, orig_type_left);
5043                 return;
5044         }
5045
5046         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
5047                                                  "assignment");
5048         if (res_type == NULL) {
5049                 errorf(expression->base.source_position,
5050                         "cannot assign to '%T' from '%T'",
5051                         orig_type_left, expression->right->base.type);
5052         } else {
5053                 expression->right = create_implicit_cast(expression->right, res_type);
5054         }
5055
5056         expression->base.type = orig_type_left;
5057 }
5058
5059 static bool expression_has_effect(const expression_t *const expr)
5060 {
5061         switch (expr->kind) {
5062                 case EXPR_UNKNOWN:                   break;
5063                 case EXPR_INVALID:                   break;
5064                 case EXPR_REFERENCE:                 return false;
5065                 case EXPR_CONST:                     return false;
5066                 case EXPR_CHAR_CONST:                return false;
5067                 case EXPR_STRING_LITERAL:            return false;
5068                 case EXPR_WIDE_STRING_LITERAL:       return false;
5069                 case EXPR_CALL: {
5070                         const call_expression_t *const call = &expr->call;
5071                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
5072                                 return true;
5073
5074                         switch (call->function->builtin_symbol.symbol->ID) {
5075                                 case T___builtin_va_end: return true;
5076                                 default:                 return false;
5077                         }
5078                 }
5079                 case EXPR_CONDITIONAL: {
5080                         const conditional_expression_t *const cond = &expr->conditional;
5081                         return
5082                                 expression_has_effect(cond->true_expression) &&
5083                                 expression_has_effect(cond->false_expression);
5084                 }
5085                 case EXPR_SELECT:                    return false;
5086                 case EXPR_ARRAY_ACCESS:              return false;
5087                 case EXPR_SIZEOF:                    return false;
5088                 case EXPR_CLASSIFY_TYPE:             return false;
5089                 case EXPR_ALIGNOF:                   return false;
5090
5091                 case EXPR_FUNCTION:                  return false;
5092                 case EXPR_PRETTY_FUNCTION:           return false;
5093                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
5094                 case EXPR_BUILTIN_CONSTANT_P:        return false;
5095                 case EXPR_BUILTIN_PREFETCH:          return true;
5096                 case EXPR_OFFSETOF:                  return false;
5097                 case EXPR_VA_START:                  return true;
5098                 case EXPR_VA_ARG:                    return true;
5099                 case EXPR_STATEMENT:                 return true; // TODO
5100                 case EXPR_COMPOUND_LITERAL:          return false;
5101
5102                 case EXPR_UNARY_NEGATE:              return false;
5103                 case EXPR_UNARY_PLUS:                return false;
5104                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
5105                 case EXPR_UNARY_NOT:                 return false;
5106                 case EXPR_UNARY_DEREFERENCE:         return false;
5107                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
5108                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
5109                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
5110                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
5111                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
5112                 case EXPR_UNARY_CAST: {
5113                         type_t *type = skip_typeref(expr->base.type);
5114                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
5115                 }
5116                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
5117                 case EXPR_UNARY_ASSUME:              return true;
5118                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
5119
5120                 case EXPR_BINARY_ADD:                return false;
5121                 case EXPR_BINARY_SUB:                return false;
5122                 case EXPR_BINARY_MUL:                return false;
5123                 case EXPR_BINARY_DIV:                return false;
5124                 case EXPR_BINARY_MOD:                return false;
5125                 case EXPR_BINARY_EQUAL:              return false;
5126                 case EXPR_BINARY_NOTEQUAL:           return false;
5127                 case EXPR_BINARY_LESS:               return false;
5128                 case EXPR_BINARY_LESSEQUAL:          return false;
5129                 case EXPR_BINARY_GREATER:            return false;
5130                 case EXPR_BINARY_GREATEREQUAL:       return false;
5131                 case EXPR_BINARY_BITWISE_AND:        return false;
5132                 case EXPR_BINARY_BITWISE_OR:         return false;
5133                 case EXPR_BINARY_BITWISE_XOR:        return false;
5134                 case EXPR_BINARY_SHIFTLEFT:          return false;
5135                 case EXPR_BINARY_SHIFTRIGHT:         return false;
5136                 case EXPR_BINARY_ASSIGN:             return true;
5137                 case EXPR_BINARY_MUL_ASSIGN:         return true;
5138                 case EXPR_BINARY_DIV_ASSIGN:         return true;
5139                 case EXPR_BINARY_MOD_ASSIGN:         return true;
5140                 case EXPR_BINARY_ADD_ASSIGN:         return true;
5141                 case EXPR_BINARY_SUB_ASSIGN:         return true;
5142                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
5143                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
5144                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
5145                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
5146                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
5147                 case EXPR_BINARY_LOGICAL_AND:
5148                 case EXPR_BINARY_LOGICAL_OR:
5149                 case EXPR_BINARY_COMMA:
5150                         return expression_has_effect(expr->binary.right);
5151
5152                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
5153                 case EXPR_BINARY_ISGREATER:          return false;
5154                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
5155                 case EXPR_BINARY_ISLESS:             return false;
5156                 case EXPR_BINARY_ISLESSEQUAL:        return false;
5157                 case EXPR_BINARY_ISLESSGREATER:      return false;
5158                 case EXPR_BINARY_ISUNORDERED:        return false;
5159         }
5160
5161         panic("unexpected statement");
5162 }
5163
5164 static void semantic_comma(binary_expression_t *expression)
5165 {
5166         if (warning.unused_value) {
5167                 const expression_t *const left = expression->left;
5168                 if (!expression_has_effect(left)) {
5169                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
5170                 }
5171         }
5172         expression->base.type = expression->right->base.type;
5173 }
5174
5175 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
5176 static expression_t *parse_##binexpression_type(unsigned precedence,      \
5177                                                 expression_t *left)       \
5178 {                                                                         \
5179         eat(token_type);                                                      \
5180         source_position_t pos = HERE;                                         \
5181                                                                           \
5182         expression_t *right = parse_sub_expression(precedence + lr);          \
5183                                                                           \
5184         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
5185         binexpr->base.source_position = pos;                                  \
5186         binexpr->binary.left  = left;                                         \
5187         binexpr->binary.right = right;                                        \
5188         sfunc(&binexpr->binary);                                              \
5189                                                                           \
5190         return binexpr;                                                       \
5191 }
5192
5193 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
5194 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
5195 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
5196 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
5197 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
5198 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
5199 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
5200 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
5201 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
5202
5203 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
5204                       semantic_comparison, 1)
5205 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
5206                       semantic_comparison, 1)
5207 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
5208                       semantic_comparison, 1)
5209 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
5210                       semantic_comparison, 1)
5211
5212 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
5213                       semantic_binexpr_arithmetic, 1)
5214 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
5215                       semantic_binexpr_arithmetic, 1)
5216 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
5217                       semantic_binexpr_arithmetic, 1)
5218 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
5219                       semantic_logical_op, 1)
5220 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
5221                       semantic_logical_op, 1)
5222 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
5223                       semantic_shift_op, 1)
5224 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
5225                       semantic_shift_op, 1)
5226 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
5227                       semantic_arithmetic_addsubb_assign, 0)
5228 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
5229                       semantic_arithmetic_addsubb_assign, 0)
5230 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
5231                       semantic_arithmetic_assign, 0)
5232 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
5233                       semantic_arithmetic_assign, 0)
5234 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
5235                       semantic_arithmetic_assign, 0)
5236 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
5237                       semantic_arithmetic_assign, 0)
5238 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5239                       semantic_arithmetic_assign, 0)
5240 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
5241                       semantic_arithmetic_assign, 0)
5242 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
5243                       semantic_arithmetic_assign, 0)
5244 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
5245                       semantic_arithmetic_assign, 0)
5246
5247 static expression_t *parse_sub_expression(unsigned precedence)
5248 {
5249         if(token.type < 0) {
5250                 return expected_expression_error();
5251         }
5252
5253         expression_parser_function_t *parser
5254                 = &expression_parsers[token.type];
5255         source_position_t             source_position = token.source_position;
5256         expression_t                 *left;
5257
5258         if(parser->parser != NULL) {
5259                 left = parser->parser(parser->precedence);
5260         } else {
5261                 left = parse_primary_expression();
5262         }
5263         assert(left != NULL);
5264         left->base.source_position = source_position;
5265
5266         while(true) {
5267                 if(token.type < 0) {
5268                         return expected_expression_error();
5269                 }
5270
5271                 parser = &expression_parsers[token.type];
5272                 if(parser->infix_parser == NULL)
5273                         break;
5274                 if(parser->infix_precedence < precedence)
5275                         break;
5276
5277                 left = parser->infix_parser(parser->infix_precedence, left);
5278
5279                 assert(left != NULL);
5280                 assert(left->kind != EXPR_UNKNOWN);
5281                 left->base.source_position = source_position;
5282         }
5283
5284         return left;
5285 }
5286
5287 /**
5288  * Parse an expression.
5289  */
5290 static expression_t *parse_expression(void)
5291 {
5292         return parse_sub_expression(1);
5293 }
5294
5295 /**
5296  * Register a parser for a prefix-like operator with given precedence.
5297  *
5298  * @param parser      the parser function
5299  * @param token_type  the token type of the prefix token
5300  * @param precedence  the precedence of the operator
5301  */
5302 static void register_expression_parser(parse_expression_function parser,
5303                                        int token_type, unsigned precedence)
5304 {
5305         expression_parser_function_t *entry = &expression_parsers[token_type];
5306
5307         if(entry->parser != NULL) {
5308                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5309                 panic("trying to register multiple expression parsers for a token");
5310         }
5311         entry->parser     = parser;
5312         entry->precedence = precedence;
5313 }
5314
5315 /**
5316  * Register a parser for an infix operator with given precedence.
5317  *
5318  * @param parser      the parser function
5319  * @param token_type  the token type of the infix operator
5320  * @param precedence  the precedence of the operator
5321  */
5322 static void register_infix_parser(parse_expression_infix_function parser,
5323                 int token_type, unsigned precedence)
5324 {
5325         expression_parser_function_t *entry = &expression_parsers[token_type];
5326
5327         if(entry->infix_parser != NULL) {
5328                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
5329                 panic("trying to register multiple infix expression parsers for a "
5330                       "token");
5331         }
5332         entry->infix_parser     = parser;
5333         entry->infix_precedence = precedence;
5334 }
5335
5336 /**
5337  * Initialize the expression parsers.
5338  */
5339 static void init_expression_parsers(void)
5340 {
5341         memset(&expression_parsers, 0, sizeof(expression_parsers));
5342
5343         register_infix_parser(parse_array_expression,         '[',              30);
5344         register_infix_parser(parse_call_expression,          '(',              30);
5345         register_infix_parser(parse_select_expression,        '.',              30);
5346         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
5347         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
5348                                                               T_PLUSPLUS,       30);
5349         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
5350                                                               T_MINUSMINUS,     30);
5351
5352         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
5353         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
5354         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
5355         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
5356         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
5357         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
5358         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
5359         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
5360         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
5361         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
5362         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
5363         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
5364         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
5365                                                     T_EXCLAMATIONMARKEQUAL, 13);
5366         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
5367         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
5368         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
5369         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
5370         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
5371         register_infix_parser(parse_conditional_expression,   '?',               7);
5372         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
5373         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
5374         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
5375         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
5376         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
5377         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
5378         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
5379                                                                 T_LESSLESSEQUAL, 2);
5380         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
5381                                                           T_GREATERGREATEREQUAL, 2);
5382         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
5383                                                                      T_ANDEQUAL, 2);
5384         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
5385                                                                     T_PIPEEQUAL, 2);
5386         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
5387                                                                    T_CARETEQUAL, 2);
5388
5389         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
5390
5391         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
5392         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
5393         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
5394         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
5395         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
5396         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
5397         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
5398                                                                   T_PLUSPLUS,   25);
5399         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
5400                                                                   T_MINUSMINUS, 25);
5401         register_expression_parser(parse_sizeof,                      T_sizeof, 25);
5402         register_expression_parser(parse_alignof,                T___alignof__, 25);
5403         register_expression_parser(parse_extension,            T___extension__, 25);
5404         register_expression_parser(parse_builtin_classify_type,
5405                                                      T___builtin_classify_type, 25);
5406 }
5407
5408 /**
5409  * Parse a asm statement constraints specification.
5410  */
5411 static asm_constraint_t *parse_asm_constraints(void)
5412 {
5413         asm_constraint_t *result = NULL;
5414         asm_constraint_t *last   = NULL;
5415
5416         while(token.type == T_STRING_LITERAL || token.type == '[') {
5417                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
5418                 memset(constraint, 0, sizeof(constraint[0]));
5419
5420                 if(token.type == '[') {
5421                         eat('[');
5422                         if(token.type != T_IDENTIFIER) {
5423                                 parse_error_expected("while parsing asm constraint",
5424                                                      T_IDENTIFIER, 0);
5425                                 return NULL;
5426                         }
5427                         constraint->symbol = token.v.symbol;
5428
5429                         expect(']');
5430                 }
5431
5432                 constraint->constraints = parse_string_literals();
5433                 expect('(');
5434                 constraint->expression = parse_expression();
5435                 expect(')');
5436
5437                 if(last != NULL) {
5438                         last->next = constraint;
5439                 } else {
5440                         result = constraint;
5441                 }
5442                 last = constraint;
5443
5444                 if(token.type != ',')
5445                         break;
5446                 eat(',');
5447         }
5448
5449         return result;
5450 }
5451
5452 /**
5453  * Parse a asm statement clobber specification.
5454  */
5455 static asm_clobber_t *parse_asm_clobbers(void)
5456 {
5457         asm_clobber_t *result = NULL;
5458         asm_clobber_t *last   = NULL;
5459
5460         while(token.type == T_STRING_LITERAL) {
5461                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
5462                 clobber->clobber       = parse_string_literals();
5463
5464                 if(last != NULL) {
5465                         last->next = clobber;
5466                 } else {
5467                         result = clobber;
5468                 }
5469                 last = clobber;
5470
5471                 if(token.type != ',')
5472                         break;
5473                 eat(',');
5474         }
5475
5476         return result;
5477 }
5478
5479 /**
5480  * Parse an asm statement.
5481  */
5482 static statement_t *parse_asm_statement(void)
5483 {
5484         eat(T_asm);
5485
5486         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
5487         statement->base.source_position = token.source_position;
5488
5489         asm_statement_t *asm_statement = &statement->asms;
5490
5491         if(token.type == T_volatile) {
5492                 next_token();
5493                 asm_statement->is_volatile = true;
5494         }
5495
5496         expect('(');
5497         asm_statement->asm_text = parse_string_literals();
5498
5499         if(token.type != ':')
5500                 goto end_of_asm;
5501         eat(':');
5502
5503         asm_statement->inputs = parse_asm_constraints();
5504         if(token.type != ':')
5505                 goto end_of_asm;
5506         eat(':');
5507
5508         asm_statement->outputs = parse_asm_constraints();
5509         if(token.type != ':')
5510                 goto end_of_asm;
5511         eat(':');
5512
5513         asm_statement->clobbers = parse_asm_clobbers();
5514
5515 end_of_asm:
5516         expect(')');
5517         expect(';');
5518         return statement;
5519 }
5520
5521 /**
5522  * Parse a case statement.
5523  */
5524 static statement_t *parse_case_statement(void)
5525 {
5526         eat(T_case);
5527
5528         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5529
5530         statement->base.source_position  = token.source_position;
5531         statement->case_label.expression = parse_expression();
5532
5533         if (c_mode & _GNUC) {
5534                 if (token.type == T_DOTDOTDOT) {
5535                         next_token();
5536                         statement->case_label.end_range = parse_expression();
5537                 }
5538         }
5539
5540         expect(':');
5541
5542         if (! is_constant_expression(statement->case_label.expression)) {
5543                 errorf(statement->base.source_position,
5544                         "case label does not reduce to an integer constant");
5545         } else {
5546                 /* TODO: check if the case label is already known */
5547                 if (current_switch != NULL) {
5548                         /* link all cases into the switch statement */
5549                         if (current_switch->last_case == NULL) {
5550                                 current_switch->first_case =
5551                                 current_switch->last_case  = &statement->case_label;
5552                         } else {
5553                                 current_switch->last_case->next = &statement->case_label;
5554                         }
5555                 } else {
5556                         errorf(statement->base.source_position,
5557                                 "case label not within a switch statement");
5558                 }
5559         }
5560         statement->case_label.statement = parse_statement();
5561
5562         return statement;
5563 }
5564
5565 /**
5566  * Finds an existing default label of a switch statement.
5567  */
5568 static case_label_statement_t *
5569 find_default_label(const switch_statement_t *statement)
5570 {
5571         case_label_statement_t *label = statement->first_case;
5572         for ( ; label != NULL; label = label->next) {
5573                 if (label->expression == NULL)
5574                         return label;
5575         }
5576         return NULL;
5577 }
5578
5579 /**
5580  * Parse a default statement.
5581  */
5582 static statement_t *parse_default_statement(void)
5583 {
5584         eat(T_default);
5585
5586         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
5587
5588         statement->base.source_position = token.source_position;
5589
5590         expect(':');
5591         if (current_switch != NULL) {
5592                 const case_label_statement_t *def_label = find_default_label(current_switch);
5593                 if (def_label != NULL) {
5594                         errorf(HERE, "multiple default labels in one switch");
5595                         errorf(def_label->base.source_position,
5596                                 "this is the first default label");
5597                 } else {
5598                         /* link all cases into the switch statement */
5599                         if (current_switch->last_case == NULL) {
5600                                 current_switch->first_case =
5601                                         current_switch->last_case  = &statement->case_label;
5602                         } else {
5603                                 current_switch->last_case->next = &statement->case_label;
5604                         }
5605                 }
5606         } else {
5607                 errorf(statement->base.source_position,
5608                         "'default' label not within a switch statement");
5609         }
5610         statement->case_label.statement = parse_statement();
5611
5612         return statement;
5613 }
5614
5615 /**
5616  * Return the declaration for a given label symbol or create a new one.
5617  */
5618 static declaration_t *get_label(symbol_t *symbol)
5619 {
5620         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
5621         assert(current_function != NULL);
5622         /* if we found a label in the same function, then we already created the
5623          * declaration */
5624         if(candidate != NULL
5625                         && candidate->parent_scope == &current_function->scope) {
5626                 return candidate;
5627         }
5628
5629         /* otherwise we need to create a new one */
5630         declaration_t *const declaration = allocate_declaration_zero();
5631         declaration->namespc       = NAMESPACE_LABEL;
5632         declaration->symbol        = symbol;
5633
5634         label_push(declaration);
5635
5636         return declaration;
5637 }
5638
5639 /**
5640  * Parse a label statement.
5641  */
5642 static statement_t *parse_label_statement(void)
5643 {
5644         assert(token.type == T_IDENTIFIER);
5645         symbol_t *symbol = token.v.symbol;
5646         next_token();
5647
5648         declaration_t *label = get_label(symbol);
5649
5650         /* if source position is already set then the label is defined twice,
5651          * otherwise it was just mentioned in a goto so far */
5652         if(label->source_position.input_name != NULL) {
5653                 errorf(HERE, "duplicate label '%Y'", symbol);
5654                 errorf(label->source_position, "previous definition of '%Y' was here",
5655                        symbol);
5656         } else {
5657                 label->source_position = token.source_position;
5658         }
5659
5660         statement_t *statement = allocate_statement_zero(STATEMENT_LABEL);
5661
5662         statement->base.source_position = token.source_position;
5663         statement->label.label          = label;
5664
5665         eat(':');
5666
5667         if(token.type == '}') {
5668                 /* TODO only warn? */
5669                 errorf(HERE, "label at end of compound statement");
5670                 return statement;
5671         } else {
5672                 if (token.type == ';') {
5673                         /* eat an empty statement here, to avoid the warning about an empty
5674                          * after a label.  label:; is commonly used to have a label before
5675                          * a }. */
5676                         next_token();
5677                 } else {
5678                         statement->label.statement = parse_statement();
5679                 }
5680         }
5681
5682         /* remember the labels's in a list for later checking */
5683         if (label_last == NULL) {
5684                 label_first = &statement->label;
5685         } else {
5686                 label_last->next = &statement->label;
5687         }
5688         label_last = &statement->label;
5689
5690         return statement;
5691 }
5692
5693 /**
5694  * Parse an if statement.
5695  */
5696 static statement_t *parse_if(void)
5697 {
5698         eat(T_if);
5699
5700         statement_t *statement          = allocate_statement_zero(STATEMENT_IF);
5701         statement->base.source_position = token.source_position;
5702
5703         expect('(');
5704         statement->ifs.condition = parse_expression();
5705         expect(')');
5706
5707         statement->ifs.true_statement = parse_statement();
5708         if(token.type == T_else) {
5709                 next_token();
5710                 statement->ifs.false_statement = parse_statement();
5711         }
5712
5713         return statement;
5714 }
5715
5716 /**
5717  * Parse a switch statement.
5718  */
5719 static statement_t *parse_switch(void)
5720 {
5721         eat(T_switch);
5722
5723         statement_t *statement          = allocate_statement_zero(STATEMENT_SWITCH);
5724         statement->base.source_position = token.source_position;
5725
5726         expect('(');
5727         expression_t *const expr = parse_expression();
5728         type_t       *      type = skip_typeref(expr->base.type);
5729         if (is_type_integer(type)) {
5730                 type = promote_integer(type);
5731         } else if (is_type_valid(type)) {
5732                 errorf(expr->base.source_position,
5733                        "switch quantity is not an integer, but '%T'", type);
5734                 type = type_error_type;
5735         }
5736         statement->switchs.expression = create_implicit_cast(expr, type);
5737         expect(')');
5738
5739         switch_statement_t *rem = current_switch;
5740         current_switch          = &statement->switchs;
5741         statement->switchs.body = parse_statement();
5742         current_switch          = rem;
5743
5744         if (warning.switch_default
5745                         && find_default_label(&statement->switchs) == NULL) {
5746                 warningf(statement->base.source_position, "switch has no default case");
5747         }
5748
5749         return statement;
5750 }
5751
5752 static statement_t *parse_loop_body(statement_t *const loop)
5753 {
5754         statement_t *const rem = current_loop;
5755         current_loop = loop;
5756
5757         statement_t *const body = parse_statement();
5758
5759         current_loop = rem;
5760         return body;
5761 }
5762
5763 /**
5764  * Parse a while statement.
5765  */
5766 static statement_t *parse_while(void)
5767 {
5768         eat(T_while);
5769
5770         statement_t *statement          = allocate_statement_zero(STATEMENT_WHILE);
5771         statement->base.source_position = token.source_position;
5772
5773         expect('(');
5774         statement->whiles.condition = parse_expression();
5775         expect(')');
5776
5777         statement->whiles.body = parse_loop_body(statement);
5778
5779         return statement;
5780 }
5781
5782 /**
5783  * Parse a do statement.
5784  */
5785 static statement_t *parse_do(void)
5786 {
5787         eat(T_do);
5788
5789         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
5790
5791         statement->base.source_position = token.source_position;
5792
5793         statement->do_while.body = parse_loop_body(statement);
5794
5795         expect(T_while);
5796         expect('(');
5797         statement->do_while.condition = parse_expression();
5798         expect(')');
5799         expect(';');
5800
5801         return statement;
5802 }
5803
5804 /**
5805  * Parse a for statement.
5806  */
5807 static statement_t *parse_for(void)
5808 {
5809         eat(T_for);
5810
5811         statement_t *statement          = allocate_statement_zero(STATEMENT_FOR);
5812         statement->base.source_position = token.source_position;
5813
5814         expect('(');
5815
5816         int      top        = environment_top();
5817         scope_t *last_scope = scope;
5818         set_scope(&statement->fors.scope);
5819
5820         if(token.type != ';') {
5821                 if(is_declaration_specifier(&token, false)) {
5822                         parse_declaration(record_declaration);
5823                 } else {
5824                         expression_t *const init = parse_expression();
5825                         statement->fors.initialisation = init;
5826                         if (warning.unused_value  && !expression_has_effect(init)) {
5827                                 warningf(init->base.source_position, "initialisation of 'for'-statement has no effect");
5828                         }
5829                         expect(';');
5830                 }
5831         } else {
5832                 expect(';');
5833         }
5834
5835         if(token.type != ';') {
5836                 statement->fors.condition = parse_expression();
5837         }
5838         expect(';');
5839         if(token.type != ')') {
5840                 expression_t *const step = parse_expression();
5841                 statement->fors.step = step;
5842                 if (warning.unused_value  && !expression_has_effect(step)) {
5843                         warningf(step->base.source_position, "step of 'for'-statement has no effect");
5844                 }
5845         }
5846         expect(')');
5847         statement->fors.body = parse_loop_body(statement);
5848
5849         assert(scope == &statement->fors.scope);
5850         set_scope(last_scope);
5851         environment_pop_to(top);
5852
5853         return statement;
5854 }
5855
5856 /**
5857  * Parse a goto statement.
5858  */
5859 static statement_t *parse_goto(void)
5860 {
5861         eat(T_goto);
5862
5863         if(token.type != T_IDENTIFIER) {
5864                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5865                 eat_statement();
5866                 return NULL;
5867         }
5868         symbol_t *symbol = token.v.symbol;
5869         next_token();
5870
5871         declaration_t *label = get_label(symbol);
5872
5873         statement_t *statement          = allocate_statement_zero(STATEMENT_GOTO);
5874         statement->base.source_position = token.source_position;
5875
5876         statement->gotos.label = label;
5877
5878         /* remember the goto's in a list for later checking */
5879         if (goto_last == NULL) {
5880                 goto_first = &statement->gotos;
5881         } else {
5882                 goto_last->next = &statement->gotos;
5883         }
5884         goto_last = &statement->gotos;
5885
5886         expect(';');
5887
5888         return statement;
5889 }
5890
5891 /**
5892  * Parse a continue statement.
5893  */
5894 static statement_t *parse_continue(void)
5895 {
5896         statement_t *statement;
5897         if (current_loop == NULL) {
5898                 errorf(HERE, "continue statement not within loop");
5899                 statement = NULL;
5900         } else {
5901                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5902
5903                 statement->base.source_position = token.source_position;
5904         }
5905
5906         eat(T_continue);
5907         expect(';');
5908
5909         return statement;
5910 }
5911
5912 /**
5913  * Parse a break statement.
5914  */
5915 static statement_t *parse_break(void)
5916 {
5917         statement_t *statement;
5918         if (current_switch == NULL && current_loop == NULL) {
5919                 errorf(HERE, "break statement not within loop or switch");
5920                 statement = NULL;
5921         } else {
5922                 statement = allocate_statement_zero(STATEMENT_BREAK);
5923
5924                 statement->base.source_position = token.source_position;
5925         }
5926
5927         eat(T_break);
5928         expect(';');
5929
5930         return statement;
5931 }
5932
5933 /**
5934  * Check if a given declaration represents a local variable.
5935  */
5936 static bool is_local_var_declaration(const declaration_t *declaration) {
5937         switch ((storage_class_tag_t) declaration->storage_class) {
5938         case STORAGE_CLASS_NONE:
5939         case STORAGE_CLASS_AUTO:
5940         case STORAGE_CLASS_REGISTER: {
5941                 const type_t *type = skip_typeref(declaration->type);
5942                 if(is_type_function(type)) {
5943                         return false;
5944                 } else {
5945                         return true;
5946                 }
5947         }
5948         default:
5949                 return false;
5950         }
5951 }
5952
5953 /**
5954  * Check if a given declaration represents a variable.
5955  */
5956 static bool is_var_declaration(const declaration_t *declaration) {
5957         switch ((storage_class_tag_t) declaration->storage_class) {
5958         case STORAGE_CLASS_NONE:
5959         case STORAGE_CLASS_EXTERN:
5960         case STORAGE_CLASS_STATIC:
5961         case STORAGE_CLASS_AUTO:
5962         case STORAGE_CLASS_REGISTER:
5963         case STORAGE_CLASS_THREAD:
5964         case STORAGE_CLASS_THREAD_EXTERN:
5965         case STORAGE_CLASS_THREAD_STATIC: {
5966                 const type_t *type = skip_typeref(declaration->type);
5967                 if(is_type_function(type)) {
5968                         return false;
5969                 } else {
5970                         return true;
5971                 }
5972         }
5973         default:
5974                 return false;
5975         }
5976 }
5977
5978 /**
5979  * Check if a given expression represents a local variable.
5980  */
5981 static bool is_local_variable(const expression_t *expression)
5982 {
5983         if (expression->base.kind != EXPR_REFERENCE) {
5984                 return false;
5985         }
5986         const declaration_t *declaration = expression->reference.declaration;
5987         return is_local_var_declaration(declaration);
5988 }
5989
5990 /**
5991  * Check if a given expression represents a local variable and
5992  * return its declaration then, else return NULL.
5993  */
5994 declaration_t *expr_is_variable(const expression_t *expression)
5995 {
5996         if (expression->base.kind != EXPR_REFERENCE) {
5997                 return NULL;
5998         }
5999         declaration_t *declaration = expression->reference.declaration;
6000         if (is_var_declaration(declaration))
6001                 return declaration;
6002         return NULL;
6003 }
6004
6005 /**
6006  * Parse a return statement.
6007  */
6008 static statement_t *parse_return(void)
6009 {
6010         eat(T_return);
6011
6012         statement_t *statement          = allocate_statement_zero(STATEMENT_RETURN);
6013         statement->base.source_position = token.source_position;
6014
6015         expression_t *return_value = NULL;
6016         if(token.type != ';') {
6017                 return_value = parse_expression();
6018         }
6019         expect(';');
6020
6021         const type_t *const func_type = current_function->type;
6022         assert(is_type_function(func_type));
6023         type_t *const return_type = skip_typeref(func_type->function.return_type);
6024
6025         if(return_value != NULL) {
6026                 type_t *return_value_type = skip_typeref(return_value->base.type);
6027
6028                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
6029                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
6030                         warningf(statement->base.source_position,
6031                                  "'return' with a value, in function returning void");
6032                         return_value = NULL;
6033                 } else {
6034                         type_t *const res_type = semantic_assign(return_type,
6035                                 return_value, "'return'");
6036                         if (res_type == NULL) {
6037                                 errorf(statement->base.source_position,
6038                                        "cannot return something of type '%T' in function returning '%T'",
6039                                        return_value->base.type, return_type);
6040                         } else {
6041                                 return_value = create_implicit_cast(return_value, res_type);
6042                         }
6043                 }
6044                 /* check for returning address of a local var */
6045                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
6046                         const expression_t *expression = return_value->unary.value;
6047                         if (is_local_variable(expression)) {
6048                                 warningf(statement->base.source_position,
6049                                          "function returns address of local variable");
6050                         }
6051                 }
6052         } else {
6053                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
6054                         warningf(statement->base.source_position,
6055                                  "'return' without value, in function returning non-void");
6056                 }
6057         }
6058         statement->returns.value = return_value;
6059
6060         return statement;
6061 }
6062
6063 /**
6064  * Parse a declaration statement.
6065  */
6066 static statement_t *parse_declaration_statement(void)
6067 {
6068         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
6069
6070         statement->base.source_position = token.source_position;
6071
6072         declaration_t *before = last_declaration;
6073         parse_declaration(record_declaration);
6074
6075         if(before == NULL) {
6076                 statement->declaration.declarations_begin = scope->declarations;
6077         } else {
6078                 statement->declaration.declarations_begin = before->next;
6079         }
6080         statement->declaration.declarations_end = last_declaration;
6081
6082         return statement;
6083 }
6084
6085 /**
6086  * Parse an expression statement, ie. expr ';'.
6087  */
6088 static statement_t *parse_expression_statement(void)
6089 {
6090         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
6091
6092         statement->base.source_position  = token.source_position;
6093         expression_t *const expr         = parse_expression();
6094         statement->expression.expression = expr;
6095
6096         if (warning.unused_value  && !expression_has_effect(expr)) {
6097                 warningf(expr->base.source_position, "statement has no effect");
6098         }
6099
6100         expect(';');
6101
6102         return statement;
6103 }
6104
6105 /**
6106  * Parse a statement.
6107  */
6108 static statement_t *parse_statement(void)
6109 {
6110         statement_t   *statement = NULL;
6111
6112         /* declaration or statement */
6113         switch(token.type) {
6114         case T_asm:
6115                 statement = parse_asm_statement();
6116                 break;
6117
6118         case T_case:
6119                 statement = parse_case_statement();
6120                 break;
6121
6122         case T_default:
6123                 statement = parse_default_statement();
6124                 break;
6125
6126         case '{':
6127                 statement = parse_compound_statement();
6128                 break;
6129
6130         case T_if:
6131                 statement = parse_if();
6132                 break;
6133
6134         case T_switch:
6135                 statement = parse_switch();
6136                 break;
6137
6138         case T_while:
6139                 statement = parse_while();
6140                 break;
6141
6142         case T_do:
6143                 statement = parse_do();
6144                 break;
6145
6146         case T_for:
6147                 statement = parse_for();
6148                 break;
6149
6150         case T_goto:
6151                 statement = parse_goto();
6152                 break;
6153
6154         case T_continue:
6155                 statement = parse_continue();
6156                 break;
6157
6158         case T_break:
6159                 statement = parse_break();
6160                 break;
6161
6162         case T_return:
6163                 statement = parse_return();
6164                 break;
6165
6166         case ';':
6167                 if (warning.empty_statement) {
6168                         warningf(HERE, "statement is empty");
6169                 }
6170                 next_token();
6171                 statement = NULL;
6172                 break;
6173
6174         case T_IDENTIFIER:
6175                 if(look_ahead(1)->type == ':') {
6176                         statement = parse_label_statement();
6177                         break;
6178                 }
6179
6180                 if(is_typedef_symbol(token.v.symbol)) {
6181                         statement = parse_declaration_statement();
6182                         break;
6183                 }
6184
6185                 statement = parse_expression_statement();
6186                 break;
6187
6188         case T___extension__:
6189                 /* this can be a prefix to a declaration or an expression statement */
6190                 /* we simply eat it now and parse the rest with tail recursion */
6191                 do {
6192                         next_token();
6193                 } while(token.type == T___extension__);
6194                 statement = parse_statement();
6195                 break;
6196
6197         DECLARATION_START
6198                 statement = parse_declaration_statement();
6199                 break;
6200
6201         default:
6202                 statement = parse_expression_statement();
6203                 break;
6204         }
6205
6206         assert(statement == NULL
6207                         || statement->base.source_position.input_name != NULL);
6208
6209         return statement;
6210 }
6211
6212 /**
6213  * Parse a compound statement.
6214  */
6215 static statement_t *parse_compound_statement(void)
6216 {
6217         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
6218
6219         statement->base.source_position = token.source_position;
6220
6221         eat('{');
6222
6223         int      top        = environment_top();
6224         scope_t *last_scope = scope;
6225         set_scope(&statement->compound.scope);
6226
6227         statement_t *last_statement = NULL;
6228
6229         while(token.type != '}' && token.type != T_EOF) {
6230                 statement_t *sub_statement = parse_statement();
6231                 if(sub_statement == NULL)
6232                         continue;
6233
6234                 if(last_statement != NULL) {
6235                         last_statement->base.next = sub_statement;
6236                 } else {
6237                         statement->compound.statements = sub_statement;
6238                 }
6239
6240                 while(sub_statement->base.next != NULL)
6241                         sub_statement = sub_statement->base.next;
6242
6243                 last_statement = sub_statement;
6244         }
6245
6246         if(token.type == '}') {
6247                 next_token();
6248         } else {
6249                 errorf(statement->base.source_position,
6250                        "end of file while looking for closing '}'");
6251         }
6252
6253         assert(scope == &statement->compound.scope);
6254         set_scope(last_scope);
6255         environment_pop_to(top);
6256
6257         return statement;
6258 }
6259
6260 /**
6261  * Initialize builtin types.
6262  */
6263 static void initialize_builtin_types(void)
6264 {
6265         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
6266         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
6267         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
6268         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
6269         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
6270         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
6271         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
6272         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
6273
6274         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
6275         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
6276         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
6277         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
6278 }
6279
6280 /**
6281  * Check for unused global static functions and variables
6282  */
6283 static void check_unused_globals(void)
6284 {
6285         if (!warning.unused_function && !warning.unused_variable)
6286                 return;
6287
6288         for (const declaration_t *decl = global_scope->declarations; decl != NULL; decl = decl->next) {
6289                 if (decl->used || decl->storage_class != STORAGE_CLASS_STATIC)
6290                         continue;
6291
6292                 type_t *const type = decl->type;
6293                 const char *s;
6294                 if (is_type_function(skip_typeref(type))) {
6295                         if (!warning.unused_function || decl->is_inline)
6296                                 continue;
6297
6298                         s = (decl->init.statement != NULL ? "defined" : "declared");
6299                 } else {
6300                         if (!warning.unused_variable)
6301                                 continue;
6302
6303                         s = "defined";
6304                 }
6305
6306                 warningf(decl->source_position, "'%#T' %s but not used",
6307                         type, decl->symbol, s);
6308         }
6309 }
6310
6311 /**
6312  * Parse a translation unit.
6313  */
6314 static translation_unit_t *parse_translation_unit(void)
6315 {
6316         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
6317
6318         assert(global_scope == NULL);
6319         global_scope = &unit->scope;
6320
6321         assert(scope == NULL);
6322         set_scope(&unit->scope);
6323
6324         initialize_builtin_types();
6325
6326         while(token.type != T_EOF) {
6327                 if (token.type == ';') {
6328                         /* TODO error in strict mode */
6329                         warningf(HERE, "stray ';' outside of function");
6330                         next_token();
6331                 } else {
6332                         parse_external_declaration();
6333                 }
6334         }
6335
6336         assert(scope == &unit->scope);
6337         scope          = NULL;
6338         last_declaration = NULL;
6339
6340         assert(global_scope == &unit->scope);
6341         check_unused_globals();
6342         global_scope = NULL;
6343
6344         return unit;
6345 }
6346
6347 /**
6348  * Parse the input.
6349  *
6350  * @return  the translation unit or NULL if errors occurred.
6351  */
6352 translation_unit_t *parse(void)
6353 {
6354         environment_stack = NEW_ARR_F(stack_entry_t, 0);
6355         label_stack       = NEW_ARR_F(stack_entry_t, 0);
6356         diagnostic_count  = 0;
6357         error_count       = 0;
6358         warning_count     = 0;
6359
6360         type_set_output(stderr);
6361         ast_set_output(stderr);
6362
6363         lookahead_bufpos = 0;
6364         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
6365                 next_token();
6366         }
6367         translation_unit_t *unit = parse_translation_unit();
6368
6369         DEL_ARR_F(environment_stack);
6370         DEL_ARR_F(label_stack);
6371
6372         if(error_count > 0)
6373                 return NULL;
6374
6375         return unit;
6376 }
6377
6378 /**
6379  * Initialize the parser.
6380  */
6381 void init_parser(void)
6382 {
6383         init_expression_parsers();
6384         obstack_init(&temp_obst);
6385
6386         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
6387         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
6388 }
6389
6390 /**
6391  * Terminate the parser.
6392  */
6393 void exit_parser(void)
6394 {
6395         obstack_free(&temp_obst, NULL);
6396 }