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