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