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