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