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