Remove redundant record_declaration() call.
[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                 } else {
2852                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
2853
2854                         if(token.type == ':') {
2855                                 next_token();
2856                                 expression_t *size = parse_constant_expression();
2857
2858                                 type_t *type = make_bitfield_type(declaration->type, size);
2859                                 declaration->type = type;
2860                         }
2861                 }
2862                 record_declaration(declaration);
2863
2864                 if(token.type != ',')
2865                         break;
2866                 next_token();
2867         }
2868         expect_void(';');
2869 }
2870
2871 static void parse_compound_type_entries(void)
2872 {
2873         eat('{');
2874
2875         while(token.type != '}' && token.type != T_EOF) {
2876                 declaration_specifiers_t specifiers;
2877                 memset(&specifiers, 0, sizeof(specifiers));
2878                 parse_declaration_specifiers(&specifiers);
2879
2880                 parse_struct_declarators(&specifiers);
2881         }
2882         if(token.type == T_EOF) {
2883                 errorf(HERE, "EOF while parsing struct");
2884         }
2885         next_token();
2886 }
2887
2888 static type_t *parse_typename(void)
2889 {
2890         declaration_specifiers_t specifiers;
2891         memset(&specifiers, 0, sizeof(specifiers));
2892         parse_declaration_specifiers(&specifiers);
2893         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2894                 /* TODO: improve error message, user does probably not know what a
2895                  * storage class is...
2896                  */
2897                 errorf(HERE, "typename may not have a storage class");
2898         }
2899
2900         type_t *result = parse_abstract_declarator(specifiers.type);
2901
2902         return result;
2903 }
2904
2905
2906
2907
2908 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2909 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2910                                                           expression_t *left);
2911
2912 typedef struct expression_parser_function_t expression_parser_function_t;
2913 struct expression_parser_function_t {
2914         unsigned                         precedence;
2915         parse_expression_function        parser;
2916         unsigned                         infix_precedence;
2917         parse_expression_infix_function  infix_parser;
2918 };
2919
2920 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2921
2922 /**
2923  * Creates a new invalid expression.
2924  */
2925 static expression_t *create_invalid_expression(void)
2926 {
2927         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2928         expression->base.source_position = token.source_position;
2929         return expression;
2930 }
2931
2932 static expression_t *expected_expression_error(void)
2933 {
2934         errorf(HERE, "expected expression, got token '%K'", &token);
2935
2936         next_token();
2937
2938         return create_invalid_expression();
2939 }
2940
2941 /**
2942  * Parse a string constant.
2943  */
2944 static expression_t *parse_string_const(void)
2945 {
2946         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2947         cnst->base.datatype = type_string;
2948         cnst->string.value  = parse_string_literals();
2949
2950         return cnst;
2951 }
2952
2953 /**
2954  * Parse a wide string constant.
2955  */
2956 static expression_t *parse_wide_string_const(void)
2957 {
2958         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2959         cnst->base.datatype      = type_wchar_t_ptr;
2960         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2961         next_token();
2962         return cnst;
2963 }
2964
2965 /**
2966  * Parse an integer constant.
2967  */
2968 static expression_t *parse_int_const(void)
2969 {
2970         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2971         cnst->base.datatype      = token.datatype;
2972         cnst->conste.v.int_value = token.v.intvalue;
2973
2974         next_token();
2975
2976         return cnst;
2977 }
2978
2979 /**
2980  * Parse a float constant.
2981  */
2982 static expression_t *parse_float_const(void)
2983 {
2984         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2985         cnst->base.datatype        = token.datatype;
2986         cnst->conste.v.float_value = token.v.floatvalue;
2987
2988         next_token();
2989
2990         return cnst;
2991 }
2992
2993 static declaration_t *create_implicit_function(symbol_t *symbol,
2994                 const source_position_t source_position)
2995 {
2996         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2997         ntype->function.return_type            = type_int;
2998         ntype->function.unspecified_parameters = true;
2999
3000         type_t *type = typehash_insert(ntype);
3001         if(type != ntype) {
3002                 free_type(ntype);
3003         }
3004
3005         declaration_t *const declaration = allocate_declaration_zero();
3006         declaration->storage_class   = STORAGE_CLASS_EXTERN;
3007         declaration->type            = type;
3008         declaration->symbol          = symbol;
3009         declaration->source_position = source_position;
3010         declaration->parent_context  = global_context;
3011
3012         context_t *old_context = context;
3013         set_context(global_context);
3014
3015         environment_push(declaration);
3016         /* prepend the declaration to the global declarations list */
3017         declaration->next     = context->declarations;
3018         context->declarations = declaration;
3019
3020         assert(context == global_context);
3021         set_context(old_context);
3022
3023         return declaration;
3024 }
3025
3026 /**
3027  * Creates a return_type (func)(argument_type) function type if not
3028  * already exists.
3029  *
3030  * @param return_type    the return type
3031  * @param argument_type  the argument type
3032  */
3033 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
3034 {
3035         function_parameter_t *parameter
3036                 = obstack_alloc(type_obst, sizeof(parameter[0]));
3037         memset(parameter, 0, sizeof(parameter[0]));
3038         parameter->type = argument_type;
3039
3040         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
3041         type->function.return_type = return_type;
3042         type->function.parameters  = parameter;
3043
3044         type_t *result = typehash_insert(type);
3045         if(result != type) {
3046                 free_type(type);
3047         }
3048
3049         return result;
3050 }
3051
3052 /**
3053  * Creates a function type for some function like builtins.
3054  *
3055  * @param symbol   the symbol describing the builtin
3056  */
3057 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3058 {
3059         switch(symbol->ID) {
3060         case T___builtin_alloca:
3061                 return make_function_1_type(type_void_ptr, type_size_t);
3062         case T___builtin_nan:
3063                 return make_function_1_type(type_double, type_string);
3064         case T___builtin_nanf:
3065                 return make_function_1_type(type_float, type_string);
3066         case T___builtin_nand:
3067                 return make_function_1_type(type_long_double, type_string);
3068         case T___builtin_va_end:
3069                 return make_function_1_type(type_void, type_valist);
3070         default:
3071                 panic("not implemented builtin symbol found");
3072         }
3073 }
3074
3075 /**
3076  * Performs automatic type cast as described in Â§ 6.3.2.1.
3077  *
3078  * @param orig_type  the original type
3079  */
3080 static type_t *automatic_type_conversion(type_t *orig_type)
3081 {
3082         if(orig_type == NULL)
3083                 return NULL;
3084
3085         type_t *type = skip_typeref(orig_type);
3086         if(is_type_array(type)) {
3087                 array_type_t *array_type   = &type->array;
3088                 type_t       *element_type = array_type->element_type;
3089                 unsigned      qualifiers   = array_type->type.qualifiers;
3090
3091                 return make_pointer_type(element_type, qualifiers);
3092         }
3093
3094         if(is_type_function(type)) {
3095                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3096         }
3097
3098         return orig_type;
3099 }
3100
3101 /**
3102  * reverts the automatic casts of array to pointer types and function
3103  * to function-pointer types as defined Â§ 6.3.2.1
3104  */
3105 type_t *revert_automatic_type_conversion(const expression_t *expression)
3106 {
3107         if(expression->base.datatype == NULL)
3108                 return NULL;
3109
3110         switch(expression->kind) {
3111         case EXPR_REFERENCE: {
3112                 const reference_expression_t *ref = &expression->reference;
3113                 return ref->declaration->type;
3114         }
3115         case EXPR_SELECT: {
3116                 const select_expression_t *select = &expression->select;
3117                 return select->compound_entry->type;
3118         }
3119         case EXPR_UNARY_DEREFERENCE: {
3120                 expression_t   *value        = expression->unary.value;
3121                 type_t         *type         = skip_typeref(value->base.datatype);
3122                 pointer_type_t *pointer_type = &type->pointer;
3123
3124                 return pointer_type->points_to;
3125         }
3126         case EXPR_BUILTIN_SYMBOL: {
3127                 const builtin_symbol_expression_t *builtin
3128                         = &expression->builtin_symbol;
3129                 return get_builtin_symbol_type(builtin->symbol);
3130         }
3131         case EXPR_ARRAY_ACCESS: {
3132                 const array_access_expression_t *array_access
3133                         = &expression->array_access;
3134                 const expression_t *array_ref = array_access->array_ref;
3135                 type_t *type_left  = skip_typeref(array_ref->base.datatype);
3136                 assert(is_type_pointer(type_left));
3137                 pointer_type_t *pointer_type = &type_left->pointer;
3138                 return pointer_type->points_to;
3139         }
3140
3141         default:
3142                 break;
3143         }
3144
3145         return expression->base.datatype;
3146 }
3147
3148 static expression_t *parse_reference(void)
3149 {
3150         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3151
3152         reference_expression_t *ref = &expression->reference;
3153         ref->symbol = token.v.symbol;
3154
3155         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3156
3157         source_position_t source_position = token.source_position;
3158         next_token();
3159
3160         if(declaration == NULL) {
3161                 if (! strict_mode && token.type == '(') {
3162                         /* an implicitly defined function */
3163                         warningf(HERE, "implicit declaration of function '%Y'",
3164                                  ref->symbol);
3165
3166                         declaration = create_implicit_function(ref->symbol,
3167                                                                source_position);
3168                 } else {
3169                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3170                         return expression;
3171                 }
3172         }
3173
3174         type_t *type         = declaration->type;
3175
3176         /* we always do the auto-type conversions; the & and sizeof parser contains
3177          * code to revert this! */
3178         type = automatic_type_conversion(type);
3179
3180         ref->declaration         = declaration;
3181         ref->expression.datatype = type;
3182
3183         return expression;
3184 }
3185
3186 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3187 {
3188         (void) expression;
3189         (void) dest_type;
3190         /* TODO check if explicit cast is allowed and issue warnings/errors */
3191 }
3192
3193 static expression_t *parse_cast(void)
3194 {
3195         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3196
3197         cast->base.source_position = token.source_position;
3198
3199         type_t *type  = parse_typename();
3200
3201         expect(')');
3202         expression_t *value = parse_sub_expression(20);
3203
3204         check_cast_allowed(value, type);
3205
3206         cast->base.datatype = type;
3207         cast->unary.value   = value;
3208
3209         return cast;
3210 }
3211
3212 static expression_t *parse_statement_expression(void)
3213 {
3214         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3215
3216         statement_t *statement          = parse_compound_statement();
3217         expression->statement.statement = statement;
3218         if(statement == NULL) {
3219                 expect(')');
3220                 return NULL;
3221         }
3222
3223         assert(statement->kind == STATEMENT_COMPOUND);
3224         compound_statement_t *compound_statement = &statement->compound;
3225
3226         /* find last statement and use it's type */
3227         const statement_t *last_statement = NULL;
3228         const statement_t *iter           = compound_statement->statements;
3229         for( ; iter != NULL; iter = iter->base.next) {
3230                 last_statement = iter;
3231         }
3232
3233         if(last_statement->kind == STATEMENT_EXPRESSION) {
3234                 const expression_statement_t *expression_statement
3235                         = &last_statement->expression;
3236                 expression->base.datatype
3237                         = expression_statement->expression->base.datatype;
3238         } else {
3239                 expression->base.datatype = type_void;
3240         }
3241
3242         expect(')');
3243
3244         return expression;
3245 }
3246
3247 static expression_t *parse_brace_expression(void)
3248 {
3249         eat('(');
3250
3251         switch(token.type) {
3252         case '{':
3253                 /* gcc extension: a statement expression */
3254                 return parse_statement_expression();
3255
3256         TYPE_QUALIFIERS
3257         TYPE_SPECIFIERS
3258                 return parse_cast();
3259         case T_IDENTIFIER:
3260                 if(is_typedef_symbol(token.v.symbol)) {
3261                         return parse_cast();
3262                 }
3263         }
3264
3265         expression_t *result = parse_expression();
3266         expect(')');
3267
3268         return result;
3269 }
3270
3271 static expression_t *parse_function_keyword(void)
3272 {
3273         next_token();
3274         /* TODO */
3275
3276         if (current_function == NULL) {
3277                 errorf(HERE, "'__func__' used outside of a function");
3278         }
3279
3280         string_literal_expression_t *expression
3281                 = allocate_ast_zero(sizeof(expression[0]));
3282
3283         expression->expression.kind     = EXPR_FUNCTION;
3284         expression->expression.datatype = type_string;
3285
3286         return (expression_t*) expression;
3287 }
3288
3289 static expression_t *parse_pretty_function_keyword(void)
3290 {
3291         eat(T___PRETTY_FUNCTION__);
3292         /* TODO */
3293
3294         if (current_function == NULL) {
3295                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3296         }
3297
3298         string_literal_expression_t *expression
3299                 = allocate_ast_zero(sizeof(expression[0]));
3300
3301         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3302         expression->expression.datatype = type_string;
3303
3304         return (expression_t*) expression;
3305 }
3306
3307 static designator_t *parse_designator(void)
3308 {
3309         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3310
3311         if(token.type != T_IDENTIFIER) {
3312                 parse_error_expected("while parsing member designator",
3313                                      T_IDENTIFIER, 0);
3314                 eat_paren();
3315                 return NULL;
3316         }
3317         result->symbol = token.v.symbol;
3318         next_token();
3319
3320         designator_t *last_designator = result;
3321         while(true) {
3322                 if(token.type == '.') {
3323                         next_token();
3324                         if(token.type != T_IDENTIFIER) {
3325                                 parse_error_expected("while parsing member designator",
3326                                                      T_IDENTIFIER, 0);
3327                                 eat_paren();
3328                                 return NULL;
3329                         }
3330                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3331                         designator->symbol       = token.v.symbol;
3332                         next_token();
3333
3334                         last_designator->next = designator;
3335                         last_designator       = designator;
3336                         continue;
3337                 }
3338                 if(token.type == '[') {
3339                         next_token();
3340                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3341                         designator->array_access = parse_expression();
3342                         if(designator->array_access == NULL) {
3343                                 eat_paren();
3344                                 return NULL;
3345                         }
3346                         expect(']');
3347
3348                         last_designator->next = designator;
3349                         last_designator       = designator;
3350                         continue;
3351                 }
3352                 break;
3353         }
3354
3355         return result;
3356 }
3357
3358 static expression_t *parse_offsetof(void)
3359 {
3360         eat(T___builtin_offsetof);
3361
3362         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3363         expression->base.datatype = type_size_t;
3364
3365         expect('(');
3366         expression->offsetofe.type = parse_typename();
3367         expect(',');
3368         expression->offsetofe.designator = parse_designator();
3369         expect(')');
3370
3371         return expression;
3372 }
3373
3374 static expression_t *parse_va_start(void)
3375 {
3376         eat(T___builtin_va_start);
3377
3378         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3379
3380         expect('(');
3381         expression->va_starte.ap = parse_assignment_expression();
3382         expect(',');
3383         expression_t *const expr = parse_assignment_expression();
3384         if (expr->kind == EXPR_REFERENCE) {
3385                 declaration_t *const decl = expr->reference.declaration;
3386                 if (decl->parent_context == &current_function->context &&
3387                     decl->next == NULL) {
3388                         expression->va_starte.parameter = decl;
3389                         expect(')');
3390                         return expression;
3391                 }
3392         }
3393         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3394
3395         return create_invalid_expression();
3396 }
3397
3398 static expression_t *parse_va_arg(void)
3399 {
3400         eat(T___builtin_va_arg);
3401
3402         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3403
3404         expect('(');
3405         expression->va_arge.ap = parse_assignment_expression();
3406         expect(',');
3407         expression->base.datatype = parse_typename();
3408         expect(')');
3409
3410         return expression;
3411 }
3412
3413 static expression_t *parse_builtin_symbol(void)
3414 {
3415         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3416
3417         symbol_t *symbol = token.v.symbol;
3418
3419         expression->builtin_symbol.symbol = symbol;
3420         next_token();
3421
3422         type_t *type = get_builtin_symbol_type(symbol);
3423         type = automatic_type_conversion(type);
3424
3425         expression->base.datatype = type;
3426         return expression;
3427 }
3428
3429 static expression_t *parse_builtin_constant(void)
3430 {
3431         eat(T___builtin_constant_p);
3432
3433         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3434
3435         expect('(');
3436         expression->builtin_constant.value = parse_assignment_expression();
3437         expect(')');
3438         expression->base.datatype = type_int;
3439
3440         return expression;
3441 }
3442
3443 static expression_t *parse_builtin_prefetch(void)
3444 {
3445         eat(T___builtin_prefetch);
3446
3447         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3448
3449         expect('(');
3450         expression->builtin_prefetch.adr = parse_assignment_expression();
3451         if (token.type == ',') {
3452                 next_token();
3453                 expression->builtin_prefetch.rw = parse_assignment_expression();
3454         }
3455         if (token.type == ',') {
3456                 next_token();
3457                 expression->builtin_prefetch.locality = parse_assignment_expression();
3458         }
3459         expect(')');
3460         expression->base.datatype = type_void;
3461
3462         return expression;
3463 }
3464
3465 static expression_t *parse_compare_builtin(void)
3466 {
3467         expression_t *expression;
3468
3469         switch(token.type) {
3470         case T___builtin_isgreater:
3471                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3472                 break;
3473         case T___builtin_isgreaterequal:
3474                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3475                 break;
3476         case T___builtin_isless:
3477                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3478                 break;
3479         case T___builtin_islessequal:
3480                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3481                 break;
3482         case T___builtin_islessgreater:
3483                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3484                 break;
3485         case T___builtin_isunordered:
3486                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3487                 break;
3488         default:
3489                 panic("invalid compare builtin found");
3490                 break;
3491         }
3492         next_token();
3493
3494         expect('(');
3495         expression->binary.left = parse_assignment_expression();
3496         expect(',');
3497         expression->binary.right = parse_assignment_expression();
3498         expect(')');
3499
3500         type_t *orig_type_left  = expression->binary.left->base.datatype;
3501         type_t *orig_type_right = expression->binary.right->base.datatype;
3502         if(orig_type_left == NULL || orig_type_right == NULL)
3503                 return expression;
3504
3505         type_t *type_left  = skip_typeref(orig_type_left);
3506         type_t *type_right = skip_typeref(orig_type_right);
3507         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3508                 type_error_incompatible("invalid operands in comparison",
3509                                         token.source_position, type_left, type_right);
3510         } else {
3511                 semantic_comparison(&expression->binary);
3512         }
3513
3514         return expression;
3515 }
3516
3517 static expression_t *parse_builtin_expect(void)
3518 {
3519         eat(T___builtin_expect);
3520
3521         expression_t *expression
3522                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3523
3524         expect('(');
3525         expression->binary.left = parse_assignment_expression();
3526         expect(',');
3527         expression->binary.right = parse_constant_expression();
3528         expect(')');
3529
3530         expression->base.datatype = expression->binary.left->base.datatype;
3531
3532         return expression;
3533 }
3534
3535 static expression_t *parse_assume(void) {
3536         eat(T_assume);
3537
3538         expression_t *expression
3539                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3540
3541         expect('(');
3542         expression->unary.value = parse_assignment_expression();
3543         expect(')');
3544
3545         expression->base.datatype = type_void;
3546         return expression;
3547 }
3548
3549 static expression_t *parse_alignof(void) {
3550         eat(T___alignof__);
3551
3552         expression_t *expression
3553                 = allocate_expression_zero(EXPR_ALIGNOF);
3554
3555         expect('(');
3556         expression->alignofe.type = parse_typename();
3557         expect(')');
3558
3559         expression->base.datatype = type_size_t;
3560         return expression;
3561 }
3562
3563 static expression_t *parse_primary_expression(void)
3564 {
3565         switch(token.type) {
3566         case T_INTEGER:
3567                 return parse_int_const();
3568         case T_FLOATINGPOINT:
3569                 return parse_float_const();
3570         case T_STRING_LITERAL:
3571                 return parse_string_const();
3572         case T_WIDE_STRING_LITERAL:
3573                 return parse_wide_string_const();
3574         case T_IDENTIFIER:
3575                 return parse_reference();
3576         case T___FUNCTION__:
3577         case T___func__:
3578                 return parse_function_keyword();
3579         case T___PRETTY_FUNCTION__:
3580                 return parse_pretty_function_keyword();
3581         case T___builtin_offsetof:
3582                 return parse_offsetof();
3583         case T___builtin_va_start:
3584                 return parse_va_start();
3585         case T___builtin_va_arg:
3586                 return parse_va_arg();
3587         case T___builtin_expect:
3588                 return parse_builtin_expect();
3589         case T___builtin_nanf:
3590         case T___builtin_alloca:
3591         case T___builtin_va_end:
3592                 return parse_builtin_symbol();
3593         case T___builtin_isgreater:
3594         case T___builtin_isgreaterequal:
3595         case T___builtin_isless:
3596         case T___builtin_islessequal:
3597         case T___builtin_islessgreater:
3598         case T___builtin_isunordered:
3599                 return parse_compare_builtin();
3600         case T___builtin_constant_p:
3601                 return parse_builtin_constant();
3602         case T___builtin_prefetch:
3603                 return parse_builtin_prefetch();
3604         case T___alignof__:
3605                 return parse_alignof();
3606         case T_assume:
3607                 return parse_assume();
3608
3609         case '(':
3610                 return parse_brace_expression();
3611         }
3612
3613         errorf(HERE, "unexpected token '%K'", &token);
3614         eat_statement();
3615
3616         return create_invalid_expression();
3617 }
3618
3619 /**
3620  * Check if the expression has the character type and issue a warning then.
3621  */
3622 static void check_for_char_index_type(const expression_t *expression) {
3623         type_t *type      = expression->base.datatype;
3624         type_t *base_type = skip_typeref(type);
3625
3626         if (base_type->base.kind == TYPE_ATOMIC) {
3627                 if (base_type->atomic.akind == ATOMIC_TYPE_CHAR) {
3628                         warningf(expression->base.source_position,
3629                                 "array subscript has type '%T'", type);
3630                 }
3631         }
3632 }
3633
3634 static expression_t *parse_array_expression(unsigned precedence,
3635                                             expression_t *left)
3636 {
3637         (void) precedence;
3638
3639         eat('[');
3640
3641         expression_t *inside = parse_expression();
3642
3643         array_access_expression_t *array_access
3644                 = allocate_ast_zero(sizeof(array_access[0]));
3645
3646         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3647
3648         type_t *type_left   = left->base.datatype;
3649         type_t *type_inside = inside->base.datatype;
3650         type_t *return_type = NULL;
3651
3652         if(type_left != NULL && type_inside != NULL) {
3653                 type_left   = skip_typeref(type_left);
3654                 type_inside = skip_typeref(type_inside);
3655
3656                 if(is_type_pointer(type_left)) {
3657                         pointer_type_t *pointer = &type_left->pointer;
3658                         return_type             = pointer->points_to;
3659                         array_access->array_ref = left;
3660                         array_access->index     = inside;
3661                         check_for_char_index_type(inside);
3662                 } else if(is_type_pointer(type_inside)) {
3663                         pointer_type_t *pointer = &type_inside->pointer;
3664                         return_type             = pointer->points_to;
3665                         array_access->array_ref = inside;
3666                         array_access->index     = left;
3667                         array_access->flipped   = true;
3668                         check_for_char_index_type(left);
3669                 } else {
3670                         errorf(HERE, "array access on object with non-pointer types '%T', '%T'", type_left, type_inside);
3671                 }
3672         } else {
3673                 array_access->array_ref = left;
3674                 array_access->index     = inside;
3675         }
3676
3677         if(token.type != ']') {
3678                 parse_error_expected("Problem while parsing array access", ']', 0);
3679                 return (expression_t*) array_access;
3680         }
3681         next_token();
3682
3683         return_type = automatic_type_conversion(return_type);
3684         array_access->expression.datatype = return_type;
3685
3686         return (expression_t*) array_access;
3687 }
3688
3689 static expression_t *parse_sizeof(unsigned precedence)
3690 {
3691         eat(T_sizeof);
3692
3693         sizeof_expression_t *sizeof_expression
3694                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3695         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3696         sizeof_expression->expression.datatype = type_size_t;
3697
3698         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3699                 next_token();
3700                 sizeof_expression->type = parse_typename();
3701                 expect(')');
3702         } else {
3703                 expression_t *expression  = parse_sub_expression(precedence);
3704                 expression->base.datatype = revert_automatic_type_conversion(expression);
3705
3706                 sizeof_expression->type            = expression->base.datatype;
3707                 sizeof_expression->size_expression = expression;
3708         }
3709
3710         return (expression_t*) sizeof_expression;
3711 }
3712
3713 static expression_t *parse_select_expression(unsigned precedence,
3714                                              expression_t *compound)
3715 {
3716         (void) precedence;
3717         assert(token.type == '.' || token.type == T_MINUSGREATER);
3718
3719         bool is_pointer = (token.type == T_MINUSGREATER);
3720         next_token();
3721
3722         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3723         select->select.compound = compound;
3724
3725         if(token.type != T_IDENTIFIER) {
3726                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3727                 return select;
3728         }
3729         symbol_t *symbol      = token.v.symbol;
3730         select->select.symbol = symbol;
3731         next_token();
3732
3733         type_t *orig_type = compound->base.datatype;
3734         if(orig_type == NULL)
3735                 return create_invalid_expression();
3736
3737         type_t *type = skip_typeref(orig_type);
3738
3739         type_t *type_left = type;
3740         if(is_pointer) {
3741                 if(type->kind != TYPE_POINTER) {
3742                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
3743                         return create_invalid_expression();
3744                 }
3745                 pointer_type_t *pointer_type = &type->pointer;
3746                 type_left                    = pointer_type->points_to;
3747         }
3748         type_left = skip_typeref(type_left);
3749
3750         if(type_left->kind != TYPE_COMPOUND_STRUCT
3751                         && type_left->kind != TYPE_COMPOUND_UNION) {
3752                 errorf(HERE, "request for member '%Y' in something not a struct or "
3753                        "union, but '%T'", symbol, type_left);
3754                 return create_invalid_expression();
3755         }
3756
3757         compound_type_t *compound_type = &type_left->compound;
3758         declaration_t   *declaration   = compound_type->declaration;
3759
3760         if(!declaration->init.is_defined) {
3761                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
3762                        symbol, type_left);
3763                 return create_invalid_expression();
3764         }
3765
3766         declaration_t *iter = declaration->context.declarations;
3767         for( ; iter != NULL; iter = iter->next) {
3768                 if(iter->symbol == symbol) {
3769                         break;
3770                 }
3771         }
3772         if(iter == NULL) {
3773                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
3774                 return create_invalid_expression();
3775         }
3776
3777         /* we always do the auto-type conversions; the & and sizeof parser contains
3778          * code to revert this! */
3779         type_t *expression_type = automatic_type_conversion(iter->type);
3780
3781         select->select.compound_entry = iter;
3782         select->base.datatype         = expression_type;
3783
3784         if(expression_type->kind == TYPE_BITFIELD) {
3785                 expression_t *extract
3786                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
3787                 extract->unary.value   = select;
3788                 extract->base.datatype = expression_type->bitfield.base;
3789
3790                 return extract;
3791         }
3792
3793         return select;
3794 }
3795
3796 /**
3797  * Parse a call expression, ie. expression '( ... )'.
3798  *
3799  * @param expression  the function address
3800  */
3801 static expression_t *parse_call_expression(unsigned precedence,
3802                                            expression_t *expression)
3803 {
3804         (void) precedence;
3805         expression_t *result = allocate_expression_zero(EXPR_CALL);
3806
3807         call_expression_t *call = &result->call;
3808         call->function          = expression;
3809
3810         function_type_t *function_type = NULL;
3811         type_t          *orig_type     = expression->base.datatype;
3812         if(orig_type != NULL) {
3813                 type_t *type  = skip_typeref(orig_type);
3814
3815                 if(is_type_pointer(type)) {
3816                         pointer_type_t *pointer_type = &type->pointer;
3817
3818                         type = skip_typeref(pointer_type->points_to);
3819
3820                         if (is_type_function(type)) {
3821                                 function_type             = &type->function;
3822                                 call->expression.datatype = function_type->return_type;
3823                         }
3824                 }
3825                 if(function_type == NULL) {
3826                         errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
3827
3828                         function_type             = NULL;
3829                         call->expression.datatype = NULL;
3830                 }
3831         }
3832
3833         /* parse arguments */
3834         eat('(');
3835
3836         if(token.type != ')') {
3837                 call_argument_t *last_argument = NULL;
3838
3839                 while(true) {
3840                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3841
3842                         argument->expression = parse_assignment_expression();
3843                         if(last_argument == NULL) {
3844                                 call->arguments = argument;
3845                         } else {
3846                                 last_argument->next = argument;
3847                         }
3848                         last_argument = argument;
3849
3850                         if(token.type != ',')
3851                                 break;
3852                         next_token();
3853                 }
3854         }
3855         expect(')');
3856
3857         if(function_type != NULL) {
3858                 function_parameter_t *parameter = function_type->parameters;
3859                 call_argument_t      *argument  = call->arguments;
3860                 for( ; parameter != NULL && argument != NULL;
3861                                 parameter = parameter->next, argument = argument->next) {
3862                         type_t *expected_type = parameter->type;
3863                         /* TODO report context in error messages */
3864                         argument->expression = create_implicit_cast(argument->expression,
3865                                                                     expected_type);
3866                 }
3867                 /* too few parameters */
3868                 if(parameter != NULL) {
3869                         errorf(HERE, "too few arguments to function '%E'", expression);
3870                 } else if(argument != NULL) {
3871                         /* too many parameters */
3872                         if(!function_type->variadic
3873                                         && !function_type->unspecified_parameters) {
3874                                 errorf(HERE, "too many arguments to function '%E'", expression);
3875                         } else {
3876                                 /* do default promotion */
3877                                 for( ; argument != NULL; argument = argument->next) {
3878                                         type_t *type = argument->expression->base.datatype;
3879
3880                                         if(type == NULL)
3881                                                 continue;
3882
3883                                         type = skip_typeref(type);
3884                                         if(is_type_integer(type)) {
3885                                                 type = promote_integer(type);
3886                                         } else if(type == type_float) {
3887                                                 type = type_double;
3888                                         }
3889
3890                                         argument->expression
3891                                                 = create_implicit_cast(argument->expression, type);
3892                                 }
3893
3894                                 check_format(&result->call);
3895                         }
3896                 } else {
3897                         check_format(&result->call);
3898                 }
3899         }
3900
3901         return result;
3902 }
3903
3904 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3905
3906 static bool same_compound_type(const type_t *type1, const type_t *type2)
3907 {
3908         if(!is_type_compound(type1))
3909                 return false;
3910         if(type1->kind != type2->kind)
3911                 return false;
3912
3913         const compound_type_t *compound1 = &type1->compound;
3914         const compound_type_t *compound2 = &type2->compound;
3915
3916         return compound1->declaration == compound2->declaration;
3917 }
3918
3919 /**
3920  * Parse a conditional expression, ie. 'expression ? ... : ...'.
3921  *
3922  * @param expression  the conditional expression
3923  */
3924 static expression_t *parse_conditional_expression(unsigned precedence,
3925                                                   expression_t *expression)
3926 {
3927         eat('?');
3928
3929         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3930
3931         conditional_expression_t *conditional = &result->conditional;
3932         conditional->condition = expression;
3933
3934         /* 6.5.15.2 */
3935         type_t *condition_type_orig = expression->base.datatype;
3936         if(condition_type_orig != NULL) {
3937                 type_t *condition_type = skip_typeref(condition_type_orig);
3938                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3939                         type_error("expected a scalar type in conditional condition",
3940                                    expression->base.source_position, condition_type_orig);
3941                 }
3942         }
3943
3944         expression_t *true_expression = parse_expression();
3945         expect(':');
3946         expression_t *false_expression = parse_sub_expression(precedence);
3947
3948         conditional->true_expression  = true_expression;
3949         conditional->false_expression = false_expression;
3950
3951         type_t *orig_true_type  = true_expression->base.datatype;
3952         type_t *orig_false_type = false_expression->base.datatype;
3953         if(orig_true_type == NULL || orig_false_type == NULL)
3954                 return result;
3955
3956         type_t *true_type  = skip_typeref(orig_true_type);
3957         type_t *false_type = skip_typeref(orig_false_type);
3958
3959         /* 6.5.15.3 */
3960         type_t *result_type = NULL;
3961         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3962                 result_type = semantic_arithmetic(true_type, false_type);
3963
3964                 true_expression  = create_implicit_cast(true_expression, result_type);
3965                 false_expression = create_implicit_cast(false_expression, result_type);
3966
3967                 conditional->true_expression     = true_expression;
3968                 conditional->false_expression    = false_expression;
3969                 conditional->expression.datatype = result_type;
3970         } else if (same_compound_type(true_type, false_type)
3971                         || (is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3972                                 is_type_atomic(false_type, ATOMIC_TYPE_VOID))) {
3973                 /* just take 1 of the 2 types */
3974                 result_type = true_type;
3975         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3976                         && pointers_compatible(true_type, false_type)) {
3977                 /* ok */
3978                 result_type = true_type;
3979         } else {
3980                 /* TODO */
3981                 type_error_incompatible("while parsing conditional",
3982                                         expression->base.source_position, true_type,
3983                                         false_type);
3984         }
3985
3986         conditional->expression.datatype = result_type;
3987         return result;
3988 }
3989
3990 /**
3991  * Parse an extension expression.
3992  */
3993 static expression_t *parse_extension(unsigned precedence)
3994 {
3995         eat(T___extension__);
3996
3997         /* TODO enable extensions */
3998         expression_t *expression = parse_sub_expression(precedence);
3999         /* TODO disable extensions */
4000         return expression;
4001 }
4002
4003 static expression_t *parse_builtin_classify_type(const unsigned precedence)
4004 {
4005         eat(T___builtin_classify_type);
4006
4007         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
4008         result->base.datatype = type_int;
4009
4010         expect('(');
4011         expression_t *expression = parse_sub_expression(precedence);
4012         expect(')');
4013         result->classify_type.type_expression = expression;
4014
4015         return result;
4016 }
4017
4018 static void semantic_incdec(unary_expression_t *expression)
4019 {
4020         type_t *orig_type = expression->value->base.datatype;
4021         if(orig_type == NULL)
4022                 return;
4023
4024         type_t *type = skip_typeref(orig_type);
4025         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
4026                 /* TODO: improve error message */
4027                 errorf(HERE, "operation needs an arithmetic or pointer type");
4028                 return;
4029         }
4030
4031         expression->expression.datatype = orig_type;
4032 }
4033
4034 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
4035 {
4036         type_t *orig_type = expression->value->base.datatype;
4037         if(orig_type == NULL)
4038                 return;
4039
4040         type_t *type = skip_typeref(orig_type);
4041         if(!is_type_arithmetic(type)) {
4042                 /* TODO: improve error message */
4043                 errorf(HERE, "operation needs an arithmetic type");
4044                 return;
4045         }
4046
4047         expression->expression.datatype = orig_type;
4048 }
4049
4050 static void semantic_unexpr_scalar(unary_expression_t *expression)
4051 {
4052         type_t *orig_type = expression->value->base.datatype;
4053         if(orig_type == NULL)
4054                 return;
4055
4056         type_t *type = skip_typeref(orig_type);
4057         if (!is_type_scalar(type)) {
4058                 errorf(HERE, "operand of ! must be of scalar type");
4059                 return;
4060         }
4061
4062         expression->expression.datatype = orig_type;
4063 }
4064
4065 static void semantic_unexpr_integer(unary_expression_t *expression)
4066 {
4067         type_t *orig_type = expression->value->base.datatype;
4068         if(orig_type == NULL)
4069                 return;
4070
4071         type_t *type = skip_typeref(orig_type);
4072         if (!is_type_integer(type)) {
4073                 errorf(HERE, "operand of ~ must be of integer type");
4074                 return;
4075         }
4076
4077         expression->expression.datatype = orig_type;
4078 }
4079
4080 static void semantic_dereference(unary_expression_t *expression)
4081 {
4082         type_t *orig_type = expression->value->base.datatype;
4083         if(orig_type == NULL)
4084                 return;
4085
4086         type_t *type = skip_typeref(orig_type);
4087         if(!is_type_pointer(type)) {
4088                 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4089                 return;
4090         }
4091
4092         pointer_type_t *pointer_type = &type->pointer;
4093         type_t         *result_type  = pointer_type->points_to;
4094
4095         result_type = automatic_type_conversion(result_type);
4096         expression->expression.datatype = result_type;
4097 }
4098
4099 /**
4100  * Check the semantic of the address taken expression.
4101  */
4102 static void semantic_take_addr(unary_expression_t *expression)
4103 {
4104         expression_t *value  = expression->value;
4105         value->base.datatype = revert_automatic_type_conversion(value);
4106
4107         type_t *orig_type = value->base.datatype;
4108         if(orig_type == NULL)
4109                 return;
4110
4111         if(value->kind == EXPR_REFERENCE) {
4112                 reference_expression_t *reference   = (reference_expression_t*) value;
4113                 declaration_t          *declaration = reference->declaration;
4114                 if(declaration != NULL) {
4115                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4116                                 errorf(expression->expression.source_position,
4117                                         "address of register variable '%Y' requested",
4118                                         declaration->symbol);
4119                         }
4120                         declaration->address_taken = 1;
4121                 }
4122         }
4123
4124         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4125 }
4126
4127 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4128 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4129 {                                                                              \
4130         eat(token_type);                                                           \
4131                                                                                    \
4132         expression_t *unary_expression                                             \
4133                 = allocate_expression_zero(unexpression_type);                         \
4134         unary_expression->base.source_position = HERE;                             \
4135         unary_expression->unary.value = parse_sub_expression(precedence);          \
4136                                                                                    \
4137         sfunc(&unary_expression->unary);                                           \
4138                                                                                    \
4139         return unary_expression;                                                   \
4140 }
4141
4142 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4143                                semantic_unexpr_arithmetic)
4144 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4145                                semantic_unexpr_arithmetic)
4146 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4147                                semantic_unexpr_scalar)
4148 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4149                                semantic_dereference)
4150 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4151                                semantic_take_addr)
4152 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4153                                semantic_unexpr_integer)
4154 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4155                                semantic_incdec)
4156 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4157                                semantic_incdec)
4158
4159 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4160                                                sfunc)                         \
4161 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4162                                                expression_t *left)            \
4163 {                                                                             \
4164         (void) precedence;                                                        \
4165         eat(token_type);                                                          \
4166                                                                               \
4167         expression_t *unary_expression                                            \
4168                 = allocate_expression_zero(unexpression_type);                        \
4169         unary_expression->unary.value = left;                                     \
4170                                                                                   \
4171         sfunc(&unary_expression->unary);                                          \
4172                                                                               \
4173         return unary_expression;                                                  \
4174 }
4175
4176 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4177                                        EXPR_UNARY_POSTFIX_INCREMENT,
4178                                        semantic_incdec)
4179 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4180                                        EXPR_UNARY_POSTFIX_DECREMENT,
4181                                        semantic_incdec)
4182
4183 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4184 {
4185         /* TODO: handle complex + imaginary types */
4186
4187         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4188         if(type_left == type_long_double || type_right == type_long_double) {
4189                 return type_long_double;
4190         } else if(type_left == type_double || type_right == type_double) {
4191                 return type_double;
4192         } else if(type_left == type_float || type_right == type_float) {
4193                 return type_float;
4194         }
4195
4196         type_right = promote_integer(type_right);
4197         type_left  = promote_integer(type_left);
4198
4199         if(type_left == type_right)
4200                 return type_left;
4201
4202         bool signed_left  = is_type_signed(type_left);
4203         bool signed_right = is_type_signed(type_right);
4204         int  rank_left    = get_rank(type_left);
4205         int  rank_right   = get_rank(type_right);
4206         if(rank_left < rank_right) {
4207                 if(signed_left == signed_right || !signed_right) {
4208                         return type_right;
4209                 } else {
4210                         return type_left;
4211                 }
4212         } else {
4213                 if(signed_left == signed_right || !signed_left) {
4214                         return type_left;
4215                 } else {
4216                         return type_right;
4217                 }
4218         }
4219 }
4220
4221 /**
4222  * Check the semantic restrictions for a binary expression.
4223  */
4224 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4225 {
4226         expression_t *left       = expression->left;
4227         expression_t *right      = expression->right;
4228         type_t       *orig_type_left  = left->base.datatype;
4229         type_t       *orig_type_right = right->base.datatype;
4230
4231         if(orig_type_left == NULL || orig_type_right == NULL)
4232                 return;
4233
4234         type_t *type_left  = skip_typeref(orig_type_left);
4235         type_t *type_right = skip_typeref(orig_type_right);
4236
4237         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4238                 /* TODO: improve error message */
4239                 errorf(HERE, "operation needs arithmetic types");
4240                 return;
4241         }
4242
4243         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4244         expression->left  = create_implicit_cast(left, arithmetic_type);
4245         expression->right = create_implicit_cast(right, arithmetic_type);
4246         expression->expression.datatype = arithmetic_type;
4247 }
4248
4249 static void semantic_shift_op(binary_expression_t *expression)
4250 {
4251         expression_t *left       = expression->left;
4252         expression_t *right      = expression->right;
4253         type_t       *orig_type_left  = left->base.datatype;
4254         type_t       *orig_type_right = right->base.datatype;
4255
4256         if(orig_type_left == NULL || orig_type_right == NULL)
4257                 return;
4258
4259         type_t *type_left  = skip_typeref(orig_type_left);
4260         type_t *type_right = skip_typeref(orig_type_right);
4261
4262         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4263                 /* TODO: improve error message */
4264                 errorf(HERE, "operation needs integer types");
4265                 return;
4266         }
4267
4268         type_left  = promote_integer(type_left);
4269         type_right = promote_integer(type_right);
4270
4271         expression->left  = create_implicit_cast(left, type_left);
4272         expression->right = create_implicit_cast(right, type_right);
4273         expression->expression.datatype = type_left;
4274 }
4275
4276 static void semantic_add(binary_expression_t *expression)
4277 {
4278         expression_t *left            = expression->left;
4279         expression_t *right           = expression->right;
4280         type_t       *orig_type_left  = left->base.datatype;
4281         type_t       *orig_type_right = right->base.datatype;
4282
4283         if(orig_type_left == NULL || orig_type_right == NULL)
4284                 return;
4285
4286         type_t *type_left  = skip_typeref(orig_type_left);
4287         type_t *type_right = skip_typeref(orig_type_right);
4288
4289         /* Â§ 5.6.5 */
4290         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4291                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4292                 expression->left  = create_implicit_cast(left, arithmetic_type);
4293                 expression->right = create_implicit_cast(right, arithmetic_type);
4294                 expression->expression.datatype = arithmetic_type;
4295                 return;
4296         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4297                 expression->expression.datatype = type_left;
4298         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4299                 expression->expression.datatype = type_right;
4300         } else {
4301                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4302         }
4303 }
4304
4305 static void semantic_sub(binary_expression_t *expression)
4306 {
4307         expression_t *left            = expression->left;
4308         expression_t *right           = expression->right;
4309         type_t       *orig_type_left  = left->base.datatype;
4310         type_t       *orig_type_right = right->base.datatype;
4311
4312         if(orig_type_left == NULL || orig_type_right == NULL)
4313                 return;
4314
4315         type_t       *type_left       = skip_typeref(orig_type_left);
4316         type_t       *type_right      = skip_typeref(orig_type_right);
4317
4318         /* Â§ 5.6.5 */
4319         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4320                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4321                 expression->left  = create_implicit_cast(left, arithmetic_type);
4322                 expression->right = create_implicit_cast(right, arithmetic_type);
4323                 expression->expression.datatype = arithmetic_type;
4324                 return;
4325         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4326                 expression->expression.datatype = type_left;
4327         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4328                 if(!pointers_compatible(type_left, type_right)) {
4329                         errorf(HERE, "pointers to incompatible objects to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4330                 } else {
4331                         expression->expression.datatype = type_ptrdiff_t;
4332                 }
4333         } else {
4334                 errorf(HERE, "invalid operands to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4335         }
4336 }
4337
4338 static void semantic_comparison(binary_expression_t *expression)
4339 {
4340         expression_t *left            = expression->left;
4341         expression_t *right           = expression->right;
4342         type_t       *orig_type_left  = left->base.datatype;
4343         type_t       *orig_type_right = right->base.datatype;
4344
4345         if(orig_type_left == NULL || orig_type_right == NULL)
4346                 return;
4347
4348         type_t *type_left  = skip_typeref(orig_type_left);
4349         type_t *type_right = skip_typeref(orig_type_right);
4350
4351         /* TODO non-arithmetic types */
4352         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4353                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4354                 expression->left  = create_implicit_cast(left, arithmetic_type);
4355                 expression->right = create_implicit_cast(right, arithmetic_type);
4356                 expression->expression.datatype = arithmetic_type;
4357         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4358                 /* TODO check compatibility */
4359         } else if (is_type_pointer(type_left)) {
4360                 expression->right = create_implicit_cast(right, type_left);
4361         } else if (is_type_pointer(type_right)) {
4362                 expression->left = create_implicit_cast(left, type_right);
4363         } else {
4364                 type_error_incompatible("invalid operands in comparison",
4365                                         token.source_position, type_left, type_right);
4366         }
4367         expression->expression.datatype = type_int;
4368 }
4369
4370 static void semantic_arithmetic_assign(binary_expression_t *expression)
4371 {
4372         expression_t *left            = expression->left;
4373         expression_t *right           = expression->right;
4374         type_t       *orig_type_left  = left->base.datatype;
4375         type_t       *orig_type_right = right->base.datatype;
4376
4377         if(orig_type_left == NULL || orig_type_right == NULL)
4378                 return;
4379
4380         type_t *type_left  = skip_typeref(orig_type_left);
4381         type_t *type_right = skip_typeref(orig_type_right);
4382
4383         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4384                 /* TODO: improve error message */
4385                 errorf(HERE, "operation needs arithmetic types");
4386                 return;
4387         }
4388
4389         /* combined instructions are tricky. We can't create an implicit cast on
4390          * the left side, because we need the uncasted form for the store.
4391          * The ast2firm pass has to know that left_type must be right_type
4392          * for the arithmetic operation and create a cast by itself */
4393         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4394         expression->right       = create_implicit_cast(right, arithmetic_type);
4395         expression->expression.datatype = type_left;
4396 }
4397
4398 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4399 {
4400         expression_t *left            = expression->left;
4401         expression_t *right           = expression->right;
4402         type_t       *orig_type_left  = left->base.datatype;
4403         type_t       *orig_type_right = right->base.datatype;
4404
4405         if(orig_type_left == NULL || orig_type_right == NULL)
4406                 return;
4407
4408         type_t *type_left  = skip_typeref(orig_type_left);
4409         type_t *type_right = skip_typeref(orig_type_right);
4410
4411         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4412                 /* combined instructions are tricky. We can't create an implicit cast on
4413                  * the left side, because we need the uncasted form for the store.
4414                  * The ast2firm pass has to know that left_type must be right_type
4415                  * for the arithmetic operation and create a cast by itself */
4416                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4417                 expression->right = create_implicit_cast(right, arithmetic_type);
4418                 expression->expression.datatype = type_left;
4419         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4420                 expression->expression.datatype = type_left;
4421         } else {
4422                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4423                 return;
4424         }
4425 }
4426
4427 /**
4428  * Check the semantic restrictions of a logical expression.
4429  */
4430 static void semantic_logical_op(binary_expression_t *expression)
4431 {
4432         expression_t *left            = expression->left;
4433         expression_t *right           = expression->right;
4434         type_t       *orig_type_left  = left->base.datatype;
4435         type_t       *orig_type_right = right->base.datatype;
4436
4437         if(orig_type_left == NULL || orig_type_right == NULL)
4438                 return;
4439
4440         type_t *type_left  = skip_typeref(orig_type_left);
4441         type_t *type_right = skip_typeref(orig_type_right);
4442
4443         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4444                 /* TODO: improve error message */
4445                 errorf(HERE, "operation needs scalar types");
4446                 return;
4447         }
4448
4449         expression->expression.datatype = type_int;
4450 }
4451
4452 /**
4453  * Checks if a compound type has constant fields.
4454  */
4455 static bool has_const_fields(const compound_type_t *type)
4456 {
4457         const context_t     *context = &type->declaration->context;
4458         const declaration_t *declaration = context->declarations;
4459
4460         for (; declaration != NULL; declaration = declaration->next) {
4461                 if (declaration->namespc != NAMESPACE_NORMAL)
4462                         continue;
4463
4464                 const type_t *decl_type = skip_typeref(declaration->type);
4465                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4466                         return true;
4467         }
4468         /* TODO */
4469         return false;
4470 }
4471
4472 /**
4473  * Check the semantic restrictions of a binary assign expression.
4474  */
4475 static void semantic_binexpr_assign(binary_expression_t *expression)
4476 {
4477         expression_t *left           = expression->left;
4478         type_t       *orig_type_left = left->base.datatype;
4479
4480         if(orig_type_left == NULL)
4481                 return;
4482
4483         type_t *type_left = revert_automatic_type_conversion(left);
4484         type_left         = skip_typeref(orig_type_left);
4485
4486         /* must be a modifiable lvalue */
4487         if (is_type_array(type_left)) {
4488                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4489                 return;
4490         }
4491         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4492                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4493                        orig_type_left);
4494                 return;
4495         }
4496         if(is_type_incomplete(type_left)) {
4497                 errorf(HERE,
4498                        "left-hand side of assignment '%E' has incomplete type '%T'",
4499                        left, orig_type_left);
4500                 return;
4501         }
4502         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4503                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4504                        left, orig_type_left);
4505                 return;
4506         }
4507
4508         semantic_assign(orig_type_left, &expression->right, "assignment");
4509
4510         expression->expression.datatype = orig_type_left;
4511 }
4512
4513 static void semantic_comma(binary_expression_t *expression)
4514 {
4515         expression->expression.datatype = expression->right->base.datatype;
4516 }
4517
4518 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4519 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4520                                                 expression_t *left)       \
4521 {                                                                         \
4522         eat(token_type);                                                      \
4523                                                                           \
4524         expression_t *right = parse_sub_expression(precedence + lr);          \
4525                                                                           \
4526         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4527         binexpr->binary.left  = left;                                         \
4528         binexpr->binary.right = right;                                        \
4529         sfunc(&binexpr->binary);                                              \
4530                                                                           \
4531         return binexpr;                                                       \
4532 }
4533
4534 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4535 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4536 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4537 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4538 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4539 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4540 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4541 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4542 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4543
4544 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4545                       semantic_comparison, 1)
4546 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4547                       semantic_comparison, 1)
4548 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4549                       semantic_comparison, 1)
4550 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4551                       semantic_comparison, 1)
4552
4553 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4554                       semantic_binexpr_arithmetic, 1)
4555 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4556                       semantic_binexpr_arithmetic, 1)
4557 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4558                       semantic_binexpr_arithmetic, 1)
4559 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4560                       semantic_logical_op, 1)
4561 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4562                       semantic_logical_op, 1)
4563 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4564                       semantic_shift_op, 1)
4565 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4566                       semantic_shift_op, 1)
4567 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4568                       semantic_arithmetic_addsubb_assign, 0)
4569 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4570                       semantic_arithmetic_addsubb_assign, 0)
4571 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4572                       semantic_arithmetic_assign, 0)
4573 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4574                       semantic_arithmetic_assign, 0)
4575 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4576                       semantic_arithmetic_assign, 0)
4577 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4578                       semantic_arithmetic_assign, 0)
4579 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4580                       semantic_arithmetic_assign, 0)
4581 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4582                       semantic_arithmetic_assign, 0)
4583 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4584                       semantic_arithmetic_assign, 0)
4585 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4586                       semantic_arithmetic_assign, 0)
4587
4588 static expression_t *parse_sub_expression(unsigned precedence)
4589 {
4590         if(token.type < 0) {
4591                 return expected_expression_error();
4592         }
4593
4594         expression_parser_function_t *parser
4595                 = &expression_parsers[token.type];
4596         source_position_t             source_position = token.source_position;
4597         expression_t                 *left;
4598
4599         if(parser->parser != NULL) {
4600                 left = parser->parser(parser->precedence);
4601         } else {
4602                 left = parse_primary_expression();
4603         }
4604         assert(left != NULL);
4605         left->base.source_position = source_position;
4606
4607         while(true) {
4608                 if(token.type < 0) {
4609                         return expected_expression_error();
4610                 }
4611
4612                 parser = &expression_parsers[token.type];
4613                 if(parser->infix_parser == NULL)
4614                         break;
4615                 if(parser->infix_precedence < precedence)
4616                         break;
4617
4618                 left = parser->infix_parser(parser->infix_precedence, left);
4619
4620                 assert(left != NULL);
4621                 assert(left->kind != EXPR_UNKNOWN);
4622                 left->base.source_position = source_position;
4623         }
4624
4625         return left;
4626 }
4627
4628 /**
4629  * Parse an expression.
4630  */
4631 static expression_t *parse_expression(void)
4632 {
4633         return parse_sub_expression(1);
4634 }
4635
4636 /**
4637  * Register a parser for a prefix-like operator with given precedence.
4638  *
4639  * @param parser      the parser function
4640  * @param token_type  the token type of the prefix token
4641  * @param precedence  the precedence of the operator
4642  */
4643 static void register_expression_parser(parse_expression_function parser,
4644                                        int token_type, unsigned precedence)
4645 {
4646         expression_parser_function_t *entry = &expression_parsers[token_type];
4647
4648         if(entry->parser != NULL) {
4649                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4650                 panic("trying to register multiple expression parsers for a token");
4651         }
4652         entry->parser     = parser;
4653         entry->precedence = precedence;
4654 }
4655
4656 /**
4657  * Register a parser for an infix operator with given precedence.
4658  *
4659  * @param parser      the parser function
4660  * @param token_type  the token type of the infix operator
4661  * @param precedence  the precedence of the operator
4662  */
4663 static void register_infix_parser(parse_expression_infix_function parser,
4664                 int token_type, unsigned precedence)
4665 {
4666         expression_parser_function_t *entry = &expression_parsers[token_type];
4667
4668         if(entry->infix_parser != NULL) {
4669                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4670                 panic("trying to register multiple infix expression parsers for a "
4671                       "token");
4672         }
4673         entry->infix_parser     = parser;
4674         entry->infix_precedence = precedence;
4675 }
4676
4677 /**
4678  * Initialize the expression parsers.
4679  */
4680 static void init_expression_parsers(void)
4681 {
4682         memset(&expression_parsers, 0, sizeof(expression_parsers));
4683
4684         register_infix_parser(parse_array_expression,         '[',              30);
4685         register_infix_parser(parse_call_expression,          '(',              30);
4686         register_infix_parser(parse_select_expression,        '.',              30);
4687         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4688         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4689                                                               T_PLUSPLUS,       30);
4690         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4691                                                               T_MINUSMINUS,     30);
4692
4693         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4694         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4695         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4696         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4697         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4698         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4699         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4700         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4701         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4702         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4703         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4704         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4705         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4706                                                     T_EXCLAMATIONMARKEQUAL, 13);
4707         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4708         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4709         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4710         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4711         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4712         register_infix_parser(parse_conditional_expression,   '?',               7);
4713         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4714         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4715         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4716         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4717         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4718         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4719         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4720                                                                 T_LESSLESSEQUAL, 2);
4721         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4722                                                           T_GREATERGREATEREQUAL, 2);
4723         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4724                                                                      T_ANDEQUAL, 2);
4725         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4726                                                                     T_PIPEEQUAL, 2);
4727         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4728                                                                    T_CARETEQUAL, 2);
4729
4730         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4731
4732         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4733         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4734         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4735         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4736         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4737         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4738         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4739                                                                   T_PLUSPLUS,   25);
4740         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4741                                                                   T_MINUSMINUS, 25);
4742         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4743         register_expression_parser(parse_extension,            T___extension__, 25);
4744         register_expression_parser(parse_builtin_classify_type,
4745                                                      T___builtin_classify_type, 25);
4746 }
4747
4748 /**
4749  * Parse a asm statement constraints specification.
4750  */
4751 static asm_constraint_t *parse_asm_constraints(void)
4752 {
4753         asm_constraint_t *result = NULL;
4754         asm_constraint_t *last   = NULL;
4755
4756         while(token.type == T_STRING_LITERAL || token.type == '[') {
4757                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4758                 memset(constraint, 0, sizeof(constraint[0]));
4759
4760                 if(token.type == '[') {
4761                         eat('[');
4762                         if(token.type != T_IDENTIFIER) {
4763                                 parse_error_expected("while parsing asm constraint",
4764                                                      T_IDENTIFIER, 0);
4765                                 return NULL;
4766                         }
4767                         constraint->symbol = token.v.symbol;
4768
4769                         expect(']');
4770                 }
4771
4772                 constraint->constraints = parse_string_literals();
4773                 expect('(');
4774                 constraint->expression = parse_expression();
4775                 expect(')');
4776
4777                 if(last != NULL) {
4778                         last->next = constraint;
4779                 } else {
4780                         result = constraint;
4781                 }
4782                 last = constraint;
4783
4784                 if(token.type != ',')
4785                         break;
4786                 eat(',');
4787         }
4788
4789         return result;
4790 }
4791
4792 /**
4793  * Parse a asm statement clobber specification.
4794  */
4795 static asm_clobber_t *parse_asm_clobbers(void)
4796 {
4797         asm_clobber_t *result = NULL;
4798         asm_clobber_t *last   = NULL;
4799
4800         while(token.type == T_STRING_LITERAL) {
4801                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4802                 clobber->clobber       = parse_string_literals();
4803
4804                 if(last != NULL) {
4805                         last->next = clobber;
4806                 } else {
4807                         result = clobber;
4808                 }
4809                 last = clobber;
4810
4811                 if(token.type != ',')
4812                         break;
4813                 eat(',');
4814         }
4815
4816         return result;
4817 }
4818
4819 /**
4820  * Parse an asm statement.
4821  */
4822 static statement_t *parse_asm_statement(void)
4823 {
4824         eat(T_asm);
4825
4826         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4827         statement->base.source_position = token.source_position;
4828
4829         asm_statement_t *asm_statement = &statement->asms;
4830
4831         if(token.type == T_volatile) {
4832                 next_token();
4833                 asm_statement->is_volatile = true;
4834         }
4835
4836         expect('(');
4837         asm_statement->asm_text = parse_string_literals();
4838
4839         if(token.type != ':')
4840                 goto end_of_asm;
4841         eat(':');
4842
4843         asm_statement->inputs = parse_asm_constraints();
4844         if(token.type != ':')
4845                 goto end_of_asm;
4846         eat(':');
4847
4848         asm_statement->outputs = parse_asm_constraints();
4849         if(token.type != ':')
4850                 goto end_of_asm;
4851         eat(':');
4852
4853         asm_statement->clobbers = parse_asm_clobbers();
4854
4855 end_of_asm:
4856         expect(')');
4857         expect(';');
4858         return statement;
4859 }
4860
4861 /**
4862  * Parse a case statement.
4863  */
4864 static statement_t *parse_case_statement(void)
4865 {
4866         eat(T_case);
4867
4868         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4869
4870         statement->base.source_position  = token.source_position;
4871         statement->case_label.expression = parse_expression();
4872
4873         expect(':');
4874
4875         if (! is_constant_expression(statement->case_label.expression)) {
4876                 errorf(statement->base.source_position,
4877                         "case label does not reduce to an integer constant");
4878         } else {
4879                 /* TODO: check if the case label is already known */
4880                 if (current_switch != NULL) {
4881                         /* link all cases into the switch statement */
4882                         if (current_switch->last_case == NULL) {
4883                                 current_switch->first_case =
4884                                 current_switch->last_case  = &statement->case_label;
4885                         } else {
4886                                 current_switch->last_case->next = &statement->case_label;
4887                         }
4888                 } else {
4889                         errorf(statement->base.source_position,
4890                                 "case label not within a switch statement");
4891                 }
4892         }
4893         statement->case_label.label_statement = parse_statement();
4894
4895         return statement;
4896 }
4897
4898 /**
4899  * Finds an existing default label of a switch statement.
4900  */
4901 static case_label_statement_t *
4902 find_default_label(const switch_statement_t *statement)
4903 {
4904         for (case_label_statement_t *label = statement->first_case;
4905              label != NULL;
4906                  label = label->next) {
4907                 if (label->expression == NULL)
4908                         return label;
4909         }
4910         return NULL;
4911 }
4912
4913 /**
4914  * Parse a default statement.
4915  */
4916 static statement_t *parse_default_statement(void)
4917 {
4918         eat(T_default);
4919
4920         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4921
4922         statement->base.source_position = token.source_position;
4923
4924         expect(':');
4925         if (current_switch != NULL) {
4926                 const case_label_statement_t *def_label = find_default_label(current_switch);
4927                 if (def_label != NULL) {
4928                         errorf(HERE, "multiple default labels in one switch");
4929                         errorf(def_label->statement.source_position,
4930                                 "this is the first default label");
4931                 } else {
4932                         /* link all cases into the switch statement */
4933                         if (current_switch->last_case == NULL) {
4934                                 current_switch->first_case =
4935                                         current_switch->last_case  = &statement->case_label;
4936                         } else {
4937                                 current_switch->last_case->next = &statement->case_label;
4938                         }
4939                 }
4940         } else {
4941                 errorf(statement->base.source_position,
4942                         "'default' label not within a switch statement");
4943         }
4944         statement->label.label_statement = parse_statement();
4945
4946         return statement;
4947 }
4948
4949 /**
4950  * Return the declaration for a given label symbol or create a new one.
4951  */
4952 static declaration_t *get_label(symbol_t *symbol)
4953 {
4954         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4955         assert(current_function != NULL);
4956         /* if we found a label in the same function, then we already created the
4957          * declaration */
4958         if(candidate != NULL
4959                         && candidate->parent_context == &current_function->context) {
4960                 return candidate;
4961         }
4962
4963         /* otherwise we need to create a new one */
4964         declaration_t *const declaration = allocate_declaration_zero();
4965         declaration->namespc       = NAMESPACE_LABEL;
4966         declaration->symbol        = symbol;
4967
4968         label_push(declaration);
4969
4970         return declaration;
4971 }
4972
4973 /**
4974  * Parse a label statement.
4975  */
4976 static statement_t *parse_label_statement(void)
4977 {
4978         assert(token.type == T_IDENTIFIER);
4979         symbol_t *symbol = token.v.symbol;
4980         next_token();
4981
4982         declaration_t *label = get_label(symbol);
4983
4984         /* if source position is already set then the label is defined twice,
4985          * otherwise it was just mentioned in a goto so far */
4986         if(label->source_position.input_name != NULL) {
4987                 errorf(HERE, "duplicate label '%Y'", symbol);
4988                 errorf(label->source_position, "previous definition of '%Y' was here",
4989                        symbol);
4990         } else {
4991                 label->source_position = token.source_position;
4992         }
4993
4994         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4995
4996         label_statement->statement.kind            = STATEMENT_LABEL;
4997         label_statement->statement.source_position = token.source_position;
4998         label_statement->label                     = label;
4999
5000         eat(':');
5001
5002         if(token.type == '}') {
5003                 /* TODO only warn? */
5004                 errorf(HERE, "label at end of compound statement");
5005                 return (statement_t*) label_statement;
5006         } else {
5007                 label_statement->label_statement = parse_statement();
5008         }
5009
5010         return (statement_t*) label_statement;
5011 }
5012
5013 /**
5014  * Parse an if statement.
5015  */
5016 static statement_t *parse_if(void)
5017 {
5018         eat(T_if);
5019
5020         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5021         statement->statement.kind            = STATEMENT_IF;
5022         statement->statement.source_position = token.source_position;
5023
5024         expect('(');
5025         statement->condition = parse_expression();
5026         expect(')');
5027
5028         statement->true_statement = parse_statement();
5029         if(token.type == T_else) {
5030                 next_token();
5031                 statement->false_statement = parse_statement();
5032         }
5033
5034         return (statement_t*) statement;
5035 }
5036
5037 /**
5038  * Parse a switch statement.
5039  */
5040 static statement_t *parse_switch(void)
5041 {
5042         eat(T_switch);
5043
5044         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5045         statement->statement.kind            = STATEMENT_SWITCH;
5046         statement->statement.source_position = token.source_position;
5047
5048         expect('(');
5049         expression_t *const expr = parse_expression();
5050         type_t       *const type = promote_integer(skip_typeref(expr->base.datatype));
5051         statement->expression = create_implicit_cast(expr, type);
5052         expect(')');
5053
5054         switch_statement_t *rem = current_switch;
5055         current_switch  = statement;
5056         statement->body = parse_statement();
5057         current_switch  = rem;
5058
5059         return (statement_t*) statement;
5060 }
5061
5062 static statement_t *parse_loop_body(statement_t *const loop)
5063 {
5064         statement_t *const rem = current_loop;
5065         current_loop = loop;
5066         statement_t *const body = parse_statement();
5067         current_loop = rem;
5068         return body;
5069 }
5070
5071 /**
5072  * Parse a while statement.
5073  */
5074 static statement_t *parse_while(void)
5075 {
5076         eat(T_while);
5077
5078         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5079         statement->statement.kind            = STATEMENT_WHILE;
5080         statement->statement.source_position = token.source_position;
5081
5082         expect('(');
5083         statement->condition = parse_expression();
5084         expect(')');
5085
5086         statement->body = parse_loop_body((statement_t*)statement);
5087
5088         return (statement_t*) statement;
5089 }
5090
5091 /**
5092  * Parse a do statement.
5093  */
5094 static statement_t *parse_do(void)
5095 {
5096         eat(T_do);
5097
5098         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5099         statement->statement.kind            = STATEMENT_DO_WHILE;
5100         statement->statement.source_position = token.source_position;
5101
5102         statement->body = parse_loop_body((statement_t*)statement);
5103         expect(T_while);
5104         expect('(');
5105         statement->condition = parse_expression();
5106         expect(')');
5107         expect(';');
5108
5109         return (statement_t*) statement;
5110 }
5111
5112 /**
5113  * Parse a for statement.
5114  */
5115 static statement_t *parse_for(void)
5116 {
5117         eat(T_for);
5118
5119         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5120         statement->statement.kind            = STATEMENT_FOR;
5121         statement->statement.source_position = token.source_position;
5122
5123         expect('(');
5124
5125         int         top          = environment_top();
5126         context_t  *last_context = context;
5127         set_context(&statement->context);
5128
5129         if(token.type != ';') {
5130                 if(is_declaration_specifier(&token, false)) {
5131                         parse_declaration(record_declaration);
5132                 } else {
5133                         statement->initialisation = parse_expression();
5134                         expect(';');
5135                 }
5136         } else {
5137                 expect(';');
5138         }
5139
5140         if(token.type != ';') {
5141                 statement->condition = parse_expression();
5142         }
5143         expect(';');
5144         if(token.type != ')') {
5145                 statement->step = parse_expression();
5146         }
5147         expect(')');
5148         statement->body = parse_loop_body((statement_t*)statement);
5149
5150         assert(context == &statement->context);
5151         set_context(last_context);
5152         environment_pop_to(top);
5153
5154         return (statement_t*) statement;
5155 }
5156
5157 /**
5158  * Parse a goto statement.
5159  */
5160 static statement_t *parse_goto(void)
5161 {
5162         eat(T_goto);
5163
5164         if(token.type != T_IDENTIFIER) {
5165                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5166                 eat_statement();
5167                 return NULL;
5168         }
5169         symbol_t *symbol = token.v.symbol;
5170         next_token();
5171
5172         declaration_t *label = get_label(symbol);
5173
5174         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5175
5176         statement->statement.kind            = STATEMENT_GOTO;
5177         statement->statement.source_position = token.source_position;
5178
5179         statement->label = label;
5180
5181         /* remember the goto's in a list for later checking */
5182         if (goto_last == NULL) {
5183                 goto_first = goto_last = statement;
5184         } else {
5185                 goto_last->next = statement;
5186         }
5187
5188         expect(';');
5189
5190         return (statement_t*) statement;
5191 }
5192
5193 /**
5194  * Parse a continue statement.
5195  */
5196 static statement_t *parse_continue(void)
5197 {
5198         statement_t *statement;
5199         if (current_loop == NULL) {
5200                 errorf(HERE, "continue statement not within loop");
5201                 statement = NULL;
5202         } else {
5203                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5204
5205                 statement->base.source_position = token.source_position;
5206         }
5207
5208         eat(T_continue);
5209         expect(';');
5210
5211         return statement;
5212 }
5213
5214 /**
5215  * Parse a break statement.
5216  */
5217 static statement_t *parse_break(void)
5218 {
5219         statement_t *statement;
5220         if (current_switch == NULL && current_loop == NULL) {
5221                 errorf(HERE, "break statement not within loop or switch");
5222                 statement = NULL;
5223         } else {
5224                 statement = allocate_statement_zero(STATEMENT_BREAK);
5225
5226                 statement->base.source_position = token.source_position;
5227         }
5228
5229         eat(T_break);
5230         expect(';');
5231
5232         return statement;
5233 }
5234
5235 /**
5236  * Check if a given declaration represents a local variable.
5237  */
5238 static bool is_local_var_declaration(const declaration_t *declaration) {
5239         switch ((storage_class_tag_t) declaration->storage_class) {
5240         case STORAGE_CLASS_NONE:
5241         case STORAGE_CLASS_AUTO:
5242         case STORAGE_CLASS_REGISTER: {
5243                 const type_t *type = skip_typeref(declaration->type);
5244                 if(is_type_function(type)) {
5245                         return false;
5246                 } else {
5247                         return true;
5248                 }
5249         }
5250         default:
5251                 return false;
5252         }
5253 }
5254
5255 /**
5256  * Check if a given expression represents a local variable.
5257  */
5258 static bool is_local_variable(const expression_t *expression)
5259 {
5260         if (expression->base.kind != EXPR_REFERENCE) {
5261                 return false;
5262         }
5263         const declaration_t *declaration = expression->reference.declaration;
5264         return is_local_var_declaration(declaration);
5265 }
5266
5267 /**
5268  * Parse a return statement.
5269  */
5270 static statement_t *parse_return(void)
5271 {
5272         eat(T_return);
5273
5274         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5275
5276         statement->statement.kind            = STATEMENT_RETURN;
5277         statement->statement.source_position = token.source_position;
5278
5279         assert(is_type_function(current_function->type));
5280         function_type_t *function_type = &current_function->type->function;
5281         type_t          *return_type   = function_type->return_type;
5282
5283         expression_t *return_value = NULL;
5284         if(token.type != ';') {
5285                 return_value = parse_expression();
5286         }
5287         expect(';');
5288
5289         if(return_type == NULL)
5290                 return (statement_t*) statement;
5291         if(return_value != NULL && return_value->base.datatype == NULL)
5292                 return (statement_t*) statement;
5293
5294         return_type = skip_typeref(return_type);
5295
5296         if(return_value != NULL) {
5297                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
5298
5299                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5300                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5301                         warningf(statement->statement.source_position,
5302                                 "'return' with a value, in function returning void");
5303                         return_value = NULL;
5304                 } else {
5305                         if(return_type != NULL) {
5306                                 semantic_assign(return_type, &return_value, "'return'");
5307                         }
5308                 }
5309                 /* check for returning address of a local var */
5310                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5311                         const expression_t *expression = return_value->unary.value;
5312                         if (is_local_variable(expression)) {
5313                                 warningf(statement->statement.source_position,
5314                                         "function returns address of local variable");
5315                         }
5316                 }
5317         } else {
5318                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5319                         warningf(statement->statement.source_position,
5320                                 "'return' without value, in function returning non-void");
5321                 }
5322         }
5323         statement->return_value = return_value;
5324
5325         return (statement_t*) statement;
5326 }
5327
5328 /**
5329  * Parse a declaration statement.
5330  */
5331 static statement_t *parse_declaration_statement(void)
5332 {
5333         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5334
5335         statement->base.source_position = token.source_position;
5336
5337         declaration_t *before = last_declaration;
5338         parse_declaration(record_declaration);
5339
5340         if(before == NULL) {
5341                 statement->declaration.declarations_begin = context->declarations;
5342         } else {
5343                 statement->declaration.declarations_begin = before->next;
5344         }
5345         statement->declaration.declarations_end = last_declaration;
5346
5347         return statement;
5348 }
5349
5350 /**
5351  * Parse an expression statement, ie. expr ';'.
5352  */
5353 static statement_t *parse_expression_statement(void)
5354 {
5355         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5356
5357         statement->base.source_position  = token.source_position;
5358         statement->expression.expression = parse_expression();
5359
5360         expect(';');
5361
5362         return statement;
5363 }
5364
5365 /**
5366  * Parse a statement.
5367  */
5368 static statement_t *parse_statement(void)
5369 {
5370         statement_t   *statement = NULL;
5371
5372         /* declaration or statement */
5373         switch(token.type) {
5374         case T_asm:
5375                 statement = parse_asm_statement();
5376                 break;
5377
5378         case T_case:
5379                 statement = parse_case_statement();
5380                 break;
5381
5382         case T_default:
5383                 statement = parse_default_statement();
5384                 break;
5385
5386         case '{':
5387                 statement = parse_compound_statement();
5388                 break;
5389
5390         case T_if:
5391                 statement = parse_if();
5392                 break;
5393
5394         case T_switch:
5395                 statement = parse_switch();
5396                 break;
5397
5398         case T_while:
5399                 statement = parse_while();
5400                 break;
5401
5402         case T_do:
5403                 statement = parse_do();
5404                 break;
5405
5406         case T_for:
5407                 statement = parse_for();
5408                 break;
5409
5410         case T_goto:
5411                 statement = parse_goto();
5412                 break;
5413
5414         case T_continue:
5415                 statement = parse_continue();
5416                 break;
5417
5418         case T_break:
5419                 statement = parse_break();
5420                 break;
5421
5422         case T_return:
5423                 statement = parse_return();
5424                 break;
5425
5426         case ';':
5427                 next_token();
5428                 statement = NULL;
5429                 break;
5430
5431         case T_IDENTIFIER:
5432                 if(look_ahead(1)->type == ':') {
5433                         statement = parse_label_statement();
5434                         break;
5435                 }
5436
5437                 if(is_typedef_symbol(token.v.symbol)) {
5438                         statement = parse_declaration_statement();
5439                         break;
5440                 }
5441
5442                 statement = parse_expression_statement();
5443                 break;
5444
5445         case T___extension__:
5446                 /* this can be a prefix to a declaration or an expression statement */
5447                 /* we simply eat it now and parse the rest with tail recursion */
5448                 do {
5449                         next_token();
5450                 } while(token.type == T___extension__);
5451                 statement = parse_statement();
5452                 break;
5453
5454         DECLARATION_START
5455                 statement = parse_declaration_statement();
5456                 break;
5457
5458         default:
5459                 statement = parse_expression_statement();
5460                 break;
5461         }
5462
5463         assert(statement == NULL
5464                         || statement->base.source_position.input_name != NULL);
5465
5466         return statement;
5467 }
5468
5469 /**
5470  * Parse a compound statement.
5471  */
5472 static statement_t *parse_compound_statement(void)
5473 {
5474         compound_statement_t *compound_statement
5475                 = allocate_ast_zero(sizeof(compound_statement[0]));
5476         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5477         compound_statement->statement.source_position = token.source_position;
5478
5479         eat('{');
5480
5481         int        top          = environment_top();
5482         context_t *last_context = context;
5483         set_context(&compound_statement->context);
5484
5485         statement_t *last_statement = NULL;
5486
5487         while(token.type != '}' && token.type != T_EOF) {
5488                 statement_t *statement = parse_statement();
5489                 if(statement == NULL)
5490                         continue;
5491
5492                 if(last_statement != NULL) {
5493                         last_statement->base.next = statement;
5494                 } else {
5495                         compound_statement->statements = statement;
5496                 }
5497
5498                 while(statement->base.next != NULL)
5499                         statement = statement->base.next;
5500
5501                 last_statement = statement;
5502         }
5503
5504         if(token.type == '}') {
5505                 next_token();
5506         } else {
5507                 errorf(compound_statement->statement.source_position, "end of file while looking for closing '}'");
5508         }
5509
5510         assert(context == &compound_statement->context);
5511         set_context(last_context);
5512         environment_pop_to(top);
5513
5514         return (statement_t*) compound_statement;
5515 }
5516
5517 /**
5518  * Initialize builtin types.
5519  */
5520 static void initialize_builtin_types(void)
5521 {
5522         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5523         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5524         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5525         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5526         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5527         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5528         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5529         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5530
5531         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5532         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5533         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5534         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5535 }
5536
5537 /**
5538  * Parse a translation unit.
5539  */
5540 static translation_unit_t *parse_translation_unit(void)
5541 {
5542         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5543
5544         assert(global_context == NULL);
5545         global_context = &unit->context;
5546
5547         assert(context == NULL);
5548         set_context(&unit->context);
5549
5550         initialize_builtin_types();
5551
5552         while(token.type != T_EOF) {
5553                 if (token.type == ';') {
5554                         /* TODO error in strict mode */
5555                         warningf(HERE, "stray ';' outside of function");
5556                         next_token();
5557                 } else {
5558                         parse_external_declaration();
5559                 }
5560         }
5561
5562         assert(context == &unit->context);
5563         context          = NULL;
5564         last_declaration = NULL;
5565
5566         assert(global_context == &unit->context);
5567         global_context = NULL;
5568
5569         return unit;
5570 }
5571
5572 /**
5573  * Parse the input.
5574  *
5575  * @return  the translation unit or NULL if errors occurred.
5576  */
5577 translation_unit_t *parse(void)
5578 {
5579         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5580         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5581         diagnostic_count  = 0;
5582         error_count       = 0;
5583         warning_count     = 0;
5584
5585         type_set_output(stderr);
5586         ast_set_output(stderr);
5587
5588         lookahead_bufpos = 0;
5589         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5590                 next_token();
5591         }
5592         translation_unit_t *unit = parse_translation_unit();
5593
5594         DEL_ARR_F(environment_stack);
5595         DEL_ARR_F(label_stack);
5596
5597         if(error_count > 0)
5598                 return NULL;
5599
5600         return unit;
5601 }
5602
5603 /**
5604  * Initialize the parser.
5605  */
5606 void init_parser(void)
5607 {
5608         init_expression_parsers();
5609         obstack_init(&temp_obst);
5610
5611         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5612         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5613 }
5614
5615 /**
5616  * Terminate the parser.
5617  */
5618 void exit_parser(void)
5619 {
5620         obstack_free(&temp_obst, NULL);
5621 }