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