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