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