- some doxygen comments added
[cparser] / parser.c
1 #include <config.h>
2
3 #include <assert.h>
4 #include <stdarg.h>
5 #include <stdbool.h>
6
7 #include "diagnostic.h"
8 #include "format_check.h"
9 #include "parser.h"
10 #include "lexer.h"
11 #include "token_t.h"
12 #include "types.h"
13 #include "type_t.h"
14 #include "type_hash.h"
15 #include "ast_t.h"
16 #include "adt/bitfiddle.h"
17 #include "adt/error.h"
18 #include "adt/array.h"
19
20 //#define PRINT_TOKENS
21 //#define ABORT_ON_ERROR
22 #define MAX_LOOKAHEAD 2
23 //#define STRICT_C99
24
25 typedef struct {
26         declaration_t *old_declaration;
27         symbol_t      *symbol;
28         unsigned short namespc;
29 } stack_entry_t;
30
31 typedef struct declaration_specifiers_t  declaration_specifiers_t;
32 struct declaration_specifiers_t {
33         source_position_t  source_position;
34         unsigned char      storage_class;
35         bool               is_inline;
36         decl_modifiers_t   decl_modifiers;
37         type_t            *type;
38 };
39
40 typedef declaration_t* (*parsed_declaration_func) (declaration_t *declaration);
41
42 static token_t         token;
43 static token_t         lookahead_buffer[MAX_LOOKAHEAD];
44 static int             lookahead_bufpos;
45 static stack_entry_t  *environment_stack = NULL;
46 static stack_entry_t  *label_stack       = NULL;
47 static context_t      *global_context    = NULL;
48 static context_t      *context           = NULL;
49 static declaration_t  *last_declaration  = NULL;
50 static declaration_t  *current_function  = NULL;
51 static struct obstack  temp_obst;
52
53 #define HERE token.source_position
54
55 static type_t *type_valist;
56
57 static statement_t *parse_compound_statement(void);
58 static statement_t *parse_statement(void);
59
60 static expression_t *parse_sub_expression(unsigned precedence);
61 static expression_t *parse_expression(void);
62 static type_t       *parse_typename(void);
63
64 static void parse_compound_type_entries(void);
65 static declaration_t *parse_declarator(
66                 const declaration_specifiers_t *specifiers, bool may_be_abstract);
67 static declaration_t *record_declaration(declaration_t *declaration);
68
69 static void semantic_comparison(binary_expression_t *expression);
70
71 #define STORAGE_CLASSES     \
72         case T_typedef:         \
73         case T_extern:          \
74         case T_static:          \
75         case T_auto:            \
76         case T_register:
77
78 #define TYPE_QUALIFIERS     \
79         case T_const:           \
80         case T_restrict:        \
81         case T_volatile:        \
82         case T_inline:          \
83         case T_forceinline:
84
85 #ifdef PROVIDE_COMPLEX
86 #define COMPLEX_SPECIFIERS  \
87         case T__Complex:
88 #define IMAGINARY_SPECIFIERS \
89         case T__Imaginary:
90 #else
91 #define COMPLEX_SPECIFIERS
92 #define IMAGINARY_SPECIFIERS
93 #endif
94
95 #define TYPE_SPECIFIERS       \
96         case T_void:              \
97         case T_char:              \
98         case T_short:             \
99         case T_int:               \
100         case T_long:              \
101         case T_float:             \
102         case T_double:            \
103         case T_signed:            \
104         case T_unsigned:          \
105         case T__Bool:             \
106         case T_struct:            \
107         case T_union:             \
108         case T_enum:              \
109         case T___typeof__:        \
110         case T___builtin_va_list: \
111         COMPLEX_SPECIFIERS        \
112         IMAGINARY_SPECIFIERS
113
114 #define DECLARATION_START   \
115         STORAGE_CLASSES         \
116         TYPE_QUALIFIERS         \
117         TYPE_SPECIFIERS
118
119 #define TYPENAME_START      \
120         TYPE_QUALIFIERS         \
121         TYPE_SPECIFIERS
122
123 /**
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 #ifndef STRICT_C99
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 #endif
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 #ifdef STRICT_C99
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 #endif
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 #ifndef STRICT_C99
3031                 /* an implicitly defined function */
3032                 if(token.type == '(') {
3033                         warningf(HERE, "implicit declaration of function '%s'\n", ref->symbol->string);
3034
3035                         declaration = create_implicit_function(ref->symbol,
3036                                                                source_position);
3037                 } else
3038 #endif
3039                 {
3040                         errorf(HERE, "unknown symbol '%s' found.\n", ref->symbol->string);
3041                         return expression;
3042                 }
3043         }
3044
3045         type_t *type = declaration->type;
3046         /* we always do the auto-type conversions; the & and sizeof parser contains
3047          * code to revert this! */
3048         type = automatic_type_conversion(type);
3049
3050         ref->declaration         = declaration;
3051         ref->expression.datatype = type;
3052
3053         return expression;
3054 }
3055
3056 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3057 {
3058         (void) expression;
3059         (void) dest_type;
3060         /* TODO check if explicit cast is allowed and issue warnings/errors */
3061 }
3062
3063 static expression_t *parse_cast(void)
3064 {
3065         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3066
3067         cast->base.source_position = token.source_position;
3068
3069         type_t *type  = parse_typename();
3070
3071         expect(')');
3072         expression_t *value = parse_sub_expression(20);
3073
3074         check_cast_allowed(value, type);
3075
3076         cast->base.datatype = type;
3077         cast->unary.value   = value;
3078
3079         return cast;
3080 }
3081
3082 static expression_t *parse_statement_expression(void)
3083 {
3084         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3085
3086         statement_t *statement          = parse_compound_statement();
3087         expression->statement.statement = statement;
3088         if(statement == NULL) {
3089                 expect(')');
3090                 return NULL;
3091         }
3092
3093         assert(statement->kind == STATEMENT_COMPOUND);
3094         compound_statement_t *compound_statement = &statement->compound;
3095
3096         /* find last statement and use it's type */
3097         const statement_t *last_statement = NULL;
3098         const statement_t *iter           = compound_statement->statements;
3099         for( ; iter != NULL; iter = iter->base.next) {
3100                 last_statement = iter;
3101         }
3102
3103         if(last_statement->kind == STATEMENT_EXPRESSION) {
3104                 const expression_statement_t *expression_statement
3105                         = &last_statement->expression;
3106                 expression->base.datatype
3107                         = expression_statement->expression->base.datatype;
3108         } else {
3109                 expression->base.datatype = type_void;
3110         }
3111
3112         expect(')');
3113
3114         return expression;
3115 }
3116
3117 static expression_t *parse_brace_expression(void)
3118 {
3119         eat('(');
3120
3121         switch(token.type) {
3122         case '{':
3123                 /* gcc extension: a statement expression */
3124                 return parse_statement_expression();
3125
3126         TYPE_QUALIFIERS
3127         TYPE_SPECIFIERS
3128                 return parse_cast();
3129         case T_IDENTIFIER:
3130                 if(is_typedef_symbol(token.v.symbol)) {
3131                         return parse_cast();
3132                 }
3133         }
3134
3135         expression_t *result = parse_expression();
3136         expect(')');
3137
3138         return result;
3139 }
3140
3141 static expression_t *parse_function_keyword(void)
3142 {
3143         next_token();
3144         /* TODO */
3145
3146         if (current_function == NULL) {
3147                 errorf(HERE, "'__func__' used outside of a function");
3148         }
3149
3150         string_literal_expression_t *expression
3151                 = allocate_ast_zero(sizeof(expression[0]));
3152
3153         expression->expression.kind     = EXPR_FUNCTION;
3154         expression->expression.datatype = type_string;
3155         expression->value               = current_function->symbol->string;
3156
3157         return (expression_t*) expression;
3158 }
3159
3160 static expression_t *parse_pretty_function_keyword(void)
3161 {
3162         eat(T___PRETTY_FUNCTION__);
3163         /* TODO */
3164
3165         if (current_function == NULL) {
3166                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3167         }
3168
3169         string_literal_expression_t *expression
3170                 = allocate_ast_zero(sizeof(expression[0]));
3171
3172         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3173         expression->expression.datatype = type_string;
3174         expression->value               = current_function->symbol->string;
3175
3176         return (expression_t*) expression;
3177 }
3178
3179 static designator_t *parse_designator(void)
3180 {
3181         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3182
3183         if(token.type != T_IDENTIFIER) {
3184                 parse_error_expected("while parsing member designator",
3185                                      T_IDENTIFIER, 0);
3186                 eat_paren();
3187                 return NULL;
3188         }
3189         result->symbol = token.v.symbol;
3190         next_token();
3191
3192         designator_t *last_designator = result;
3193         while(true) {
3194                 if(token.type == '.') {
3195                         next_token();
3196                         if(token.type != T_IDENTIFIER) {
3197                                 parse_error_expected("while parsing member designator",
3198                                                      T_IDENTIFIER, 0);
3199                                 eat_paren();
3200                                 return NULL;
3201                         }
3202                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3203                         designator->symbol       = token.v.symbol;
3204                         next_token();
3205
3206                         last_designator->next = designator;
3207                         last_designator       = designator;
3208                         continue;
3209                 }
3210                 if(token.type == '[') {
3211                         next_token();
3212                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3213                         designator->array_access = parse_expression();
3214                         if(designator->array_access == NULL) {
3215                                 eat_paren();
3216                                 return NULL;
3217                         }
3218                         expect(']');
3219
3220                         last_designator->next = designator;
3221                         last_designator       = designator;
3222                         continue;
3223                 }
3224                 break;
3225         }
3226
3227         return result;
3228 }
3229
3230 static expression_t *parse_offsetof(void)
3231 {
3232         eat(T___builtin_offsetof);
3233
3234         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3235         expression->base.datatype = type_size_t;
3236
3237         expect('(');
3238         expression->offsetofe.type = parse_typename();
3239         expect(',');
3240         expression->offsetofe.designator = parse_designator();
3241         expect(')');
3242
3243         return expression;
3244 }
3245
3246 static expression_t *parse_va_start(void)
3247 {
3248         eat(T___builtin_va_start);
3249
3250         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3251
3252         expect('(');
3253         expression->va_starte.ap = parse_assignment_expression();
3254         expect(',');
3255         expression_t *const expr = parse_assignment_expression();
3256         if (expr->kind == EXPR_REFERENCE) {
3257                 declaration_t *const decl = expr->reference.declaration;
3258                 if (decl->parent_context == &current_function->context &&
3259                     decl->next == NULL) {
3260                         expression->va_starte.parameter = decl;
3261                         expect(')');
3262                         return expression;
3263                 }
3264         }
3265         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3266
3267         return create_invalid_expression();
3268 }
3269
3270 static expression_t *parse_va_arg(void)
3271 {
3272         eat(T___builtin_va_arg);
3273
3274         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3275
3276         expect('(');
3277         expression->va_arge.ap = parse_assignment_expression();
3278         expect(',');
3279         expression->base.datatype = parse_typename();
3280         expect(')');
3281
3282         return expression;
3283 }
3284
3285 static expression_t *parse_builtin_symbol(void)
3286 {
3287         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3288
3289         symbol_t *symbol = token.v.symbol;
3290
3291         expression->builtin_symbol.symbol = symbol;
3292         next_token();
3293
3294         type_t *type = get_builtin_symbol_type(symbol);
3295         type = automatic_type_conversion(type);
3296
3297         expression->base.datatype = type;
3298         return expression;
3299 }
3300
3301 static expression_t *parse_builtin_constant(void)
3302 {
3303         eat(T___builtin_constant_p);
3304
3305         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3306
3307         expect('(');
3308         expression->builtin_constant.value = parse_assignment_expression();
3309         expect(')');
3310         expression->base.datatype = type_int;
3311
3312         return expression;
3313 }
3314
3315 static expression_t *parse_builtin_prefetch(void)
3316 {
3317         eat(T___builtin_prefetch);
3318
3319         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3320
3321         expect('(');
3322         expression->builtin_prefetch.adr = parse_assignment_expression();
3323         if (token.type == ',') {
3324                 next_token();
3325                 expression->builtin_prefetch.rw = parse_assignment_expression();
3326         }
3327         if (token.type == ',') {
3328                 next_token();
3329                 expression->builtin_prefetch.locality = parse_assignment_expression();
3330         }
3331         expect(')');
3332         expression->base.datatype = type_void;
3333
3334         return expression;
3335 }
3336
3337 static expression_t *parse_compare_builtin(void)
3338 {
3339         expression_t *expression;
3340
3341         switch(token.type) {
3342         case T___builtin_isgreater:
3343                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3344                 break;
3345         case T___builtin_isgreaterequal:
3346                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3347                 break;
3348         case T___builtin_isless:
3349                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3350                 break;
3351         case T___builtin_islessequal:
3352                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3353                 break;
3354         case T___builtin_islessgreater:
3355                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3356                 break;
3357         case T___builtin_isunordered:
3358                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3359                 break;
3360         default:
3361                 panic("invalid compare builtin found");
3362                 break;
3363         }
3364         next_token();
3365
3366         expect('(');
3367         expression->binary.left = parse_assignment_expression();
3368         expect(',');
3369         expression->binary.right = parse_assignment_expression();
3370         expect(')');
3371
3372         type_t *orig_type_left  = expression->binary.left->base.datatype;
3373         type_t *orig_type_right = expression->binary.right->base.datatype;
3374         if(orig_type_left == NULL || orig_type_right == NULL)
3375                 return expression;
3376
3377         type_t *type_left  = skip_typeref(orig_type_left);
3378         type_t *type_right = skip_typeref(orig_type_right);
3379         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3380                 type_error_incompatible("invalid operands in comparison",
3381                                         token.source_position, type_left, type_right);
3382         } else {
3383                 semantic_comparison(&expression->binary);
3384         }
3385
3386         return expression;
3387 }
3388
3389 static expression_t *parse_builtin_expect(void)
3390 {
3391         eat(T___builtin_expect);
3392
3393         expression_t *expression
3394                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3395
3396         expect('(');
3397         expression->binary.left = parse_assignment_expression();
3398         expect(',');
3399         expression->binary.right = parse_constant_expression();
3400         expect(')');
3401
3402         expression->base.datatype = expression->binary.left->base.datatype;
3403
3404         return expression;
3405 }
3406
3407 static expression_t *parse_assume(void) {
3408         eat(T_assume);
3409
3410         expression_t *expression
3411                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3412
3413         expect('(');
3414         expression->unary.value = parse_assignment_expression();
3415         expect(')');
3416
3417         expression->base.datatype = type_void;
3418         return expression;
3419 }
3420
3421 static expression_t *parse_alignof(void) {
3422         eat(T___alignof__);
3423
3424         expression_t *expression
3425                 = allocate_expression_zero(EXPR_ALIGNOF);
3426
3427         expect('(');
3428         expression->alignofe.type = parse_typename();
3429         expect(')');
3430
3431         expression->base.datatype = type_size_t;
3432         return expression;
3433 }
3434
3435 static expression_t *parse_primary_expression(void)
3436 {
3437         switch(token.type) {
3438         case T_INTEGER:
3439                 return parse_int_const();
3440         case T_FLOATINGPOINT:
3441                 return parse_float_const();
3442         case T_STRING_LITERAL: /* TODO merge */
3443                 return parse_string_const();
3444         case T_WIDE_STRING_LITERAL:
3445                 return parse_wide_string_const();
3446         case T_IDENTIFIER:
3447                 return parse_reference();
3448         case T___FUNCTION__:
3449         case T___func__:
3450                 return parse_function_keyword();
3451         case T___PRETTY_FUNCTION__:
3452                 return parse_pretty_function_keyword();
3453         case T___builtin_offsetof:
3454                 return parse_offsetof();
3455         case T___builtin_va_start:
3456                 return parse_va_start();
3457         case T___builtin_va_arg:
3458                 return parse_va_arg();
3459         case T___builtin_expect:
3460                 return parse_builtin_expect();
3461         case T___builtin_nanf:
3462         case T___builtin_alloca:
3463         case T___builtin_va_end:
3464                 return parse_builtin_symbol();
3465         case T___builtin_isgreater:
3466         case T___builtin_isgreaterequal:
3467         case T___builtin_isless:
3468         case T___builtin_islessequal:
3469         case T___builtin_islessgreater:
3470         case T___builtin_isunordered:
3471                 return parse_compare_builtin();
3472         case T___builtin_constant_p:
3473                 return parse_builtin_constant();
3474         case T___builtin_prefetch:
3475                 return parse_builtin_prefetch();
3476         case T___alignof__:
3477                 return parse_alignof();
3478         case T_assume:
3479                 return parse_assume();
3480
3481         case '(':
3482                 return parse_brace_expression();
3483         }
3484
3485         errorf(HERE, "unexpected token '%K'", &token);
3486         eat_statement();
3487
3488         return create_invalid_expression();
3489 }
3490
3491 static expression_t *parse_array_expression(unsigned precedence,
3492                                             expression_t *left)
3493 {
3494         (void) precedence;
3495
3496         eat('[');
3497
3498         expression_t *inside = parse_expression();
3499
3500         array_access_expression_t *array_access
3501                 = allocate_ast_zero(sizeof(array_access[0]));
3502
3503         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3504
3505         type_t *type_left   = left->base.datatype;
3506         type_t *type_inside = inside->base.datatype;
3507         type_t *return_type = NULL;
3508
3509         if(type_left != NULL && type_inside != NULL) {
3510                 type_left   = skip_typeref(type_left);
3511                 type_inside = skip_typeref(type_inside);
3512
3513                 if(is_type_pointer(type_left)) {
3514                         pointer_type_t *pointer = &type_left->pointer;
3515                         return_type             = pointer->points_to;
3516                         array_access->array_ref = left;
3517                         array_access->index     = inside;
3518                 } else if(is_type_pointer(type_inside)) {
3519                         pointer_type_t *pointer = &type_inside->pointer;
3520                         return_type             = pointer->points_to;
3521                         array_access->array_ref = inside;
3522                         array_access->index     = left;
3523                         array_access->flipped   = true;
3524                 } else {
3525                         errorf(HERE, "array access on object with non-pointer types '%T', '%T'", type_left, type_inside);
3526                 }
3527         } else {
3528                 array_access->array_ref = left;
3529                 array_access->index     = inside;
3530         }
3531
3532         if(token.type != ']') {
3533                 parse_error_expected("Problem while parsing array access", ']', 0);
3534                 return (expression_t*) array_access;
3535         }
3536         next_token();
3537
3538         return_type = automatic_type_conversion(return_type);
3539         array_access->expression.datatype = return_type;
3540
3541         return (expression_t*) array_access;
3542 }
3543
3544 static expression_t *parse_sizeof(unsigned precedence)
3545 {
3546         eat(T_sizeof);
3547
3548         sizeof_expression_t *sizeof_expression
3549                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3550         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3551         sizeof_expression->expression.datatype = type_size_t;
3552
3553         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3554                 next_token();
3555                 sizeof_expression->type = parse_typename();
3556                 expect(')');
3557         } else {
3558                 expression_t *expression  = parse_sub_expression(precedence);
3559                 expression->base.datatype = revert_automatic_type_conversion(expression);
3560
3561                 sizeof_expression->type            = expression->base.datatype;
3562                 sizeof_expression->size_expression = expression;
3563         }
3564
3565         return (expression_t*) sizeof_expression;
3566 }
3567
3568 static expression_t *parse_select_expression(unsigned precedence,
3569                                              expression_t *compound)
3570 {
3571         (void) precedence;
3572         assert(token.type == '.' || token.type == T_MINUSGREATER);
3573
3574         bool is_pointer = (token.type == T_MINUSGREATER);
3575         next_token();
3576
3577         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3578         select->select.compound = compound;
3579
3580         if(token.type != T_IDENTIFIER) {
3581                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3582                 return select;
3583         }
3584         symbol_t *symbol      = token.v.symbol;
3585         select->select.symbol = symbol;
3586         next_token();
3587
3588         type_t *orig_type = compound->base.datatype;
3589         if(orig_type == NULL)
3590                 return create_invalid_expression();
3591
3592         type_t *type = skip_typeref(orig_type);
3593
3594         type_t *type_left = type;
3595         if(is_pointer) {
3596                 if(type->kind != TYPE_POINTER) {
3597                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
3598                         return create_invalid_expression();
3599                 }
3600                 pointer_type_t *pointer_type = &type->pointer;
3601                 type_left                    = pointer_type->points_to;
3602         }
3603         type_left = skip_typeref(type_left);
3604
3605         if(type_left->kind != TYPE_COMPOUND_STRUCT
3606                         && type_left->kind != TYPE_COMPOUND_UNION) {
3607                 errorf(HERE, "request for member '%s' in something not a struct or union, but '%T'", symbol->string, type_left);
3608                 return create_invalid_expression();
3609         }
3610
3611         compound_type_t *compound_type = &type_left->compound;
3612         declaration_t   *declaration   = compound_type->declaration;
3613
3614         if(!declaration->init.is_defined) {
3615                 errorf(HERE, "request for member '%s' of incomplete type '%T'", symbol->string, type_left);
3616                 return create_invalid_expression();
3617         }
3618
3619         declaration_t *iter = declaration->context.declarations;
3620         for( ; iter != NULL; iter = iter->next) {
3621                 if(iter->symbol == symbol) {
3622                         break;
3623                 }
3624         }
3625         if(iter == NULL) {
3626                 errorf(HERE, "'%T' has no member names '%s'", type_left, symbol->string);
3627                 return create_invalid_expression();
3628         }
3629
3630         /* we always do the auto-type conversions; the & and sizeof parser contains
3631          * code to revert this! */
3632         type_t *expression_type = automatic_type_conversion(iter->type);
3633
3634         select->select.compound_entry = iter;
3635         select->base.datatype         = expression_type;
3636         return select;
3637 }
3638
3639 /**
3640  * Parse a call expression, ie. expression '( ... )'.
3641  *
3642  * @param expression  the function address
3643  */
3644 static expression_t *parse_call_expression(unsigned precedence,
3645                                            expression_t *expression)
3646 {
3647         (void) precedence;
3648         expression_t *result = allocate_expression_zero(EXPR_CALL);
3649
3650         call_expression_t *call  = &result->call;
3651         call->function           = expression;
3652
3653         function_type_t *function_type = NULL;
3654         type_t          *orig_type     = expression->base.datatype;
3655         if(orig_type != NULL) {
3656                 type_t *type  = skip_typeref(orig_type);
3657
3658                 if(is_type_pointer(type)) {
3659                         pointer_type_t *pointer_type = &type->pointer;
3660
3661                         type = skip_typeref(pointer_type->points_to);
3662
3663                         if (is_type_function(type)) {
3664                                 function_type             = &type->function;
3665                                 call->expression.datatype = function_type->return_type;
3666                         }
3667                 }
3668                 if(function_type == NULL) {
3669                         errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
3670
3671                         function_type             = NULL;
3672                         call->expression.datatype = NULL;
3673                 }
3674         }
3675
3676         /* parse arguments */
3677         eat('(');
3678
3679         if(token.type != ')') {
3680                 call_argument_t *last_argument = NULL;
3681
3682                 while(true) {
3683                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3684
3685                         argument->expression = parse_assignment_expression();
3686                         if(last_argument == NULL) {
3687                                 call->arguments = argument;
3688                         } else {
3689                                 last_argument->next = argument;
3690                         }
3691                         last_argument = argument;
3692
3693                         if(token.type != ',')
3694                                 break;
3695                         next_token();
3696                 }
3697         }
3698         expect(')');
3699
3700         if(function_type != NULL) {
3701                 function_parameter_t *parameter = function_type->parameters;
3702                 call_argument_t      *argument  = call->arguments;
3703                 for( ; parameter != NULL && argument != NULL;
3704                                 parameter = parameter->next, argument = argument->next) {
3705                         type_t *expected_type = parameter->type;
3706                         /* TODO report context in error messages */
3707                         argument->expression = create_implicit_cast(argument->expression,
3708                                                                     expected_type);
3709                 }
3710                 /* too few parameters */
3711                 if(parameter != NULL) {
3712                         errorf(HERE, "too few arguments to function '%E'", expression);
3713                 } else if(argument != NULL) {
3714                         /* too many parameters */
3715                         if(!function_type->variadic
3716                                         && !function_type->unspecified_parameters) {
3717                                 errorf(HERE, "too many arguments to function '%E'", expression);
3718                         } else {
3719                                 /* do default promotion */
3720                                 for( ; argument != NULL; argument = argument->next) {
3721                                         type_t *type = argument->expression->base.datatype;
3722
3723                                         if(type == NULL)
3724                                                 continue;
3725
3726                                         type = skip_typeref(type);
3727                                         if(is_type_integer(type)) {
3728                                                 type = promote_integer(type);
3729                                         } else if(type == type_float) {
3730                                                 type = type_double;
3731                                         }
3732
3733                                         argument->expression
3734                                                 = create_implicit_cast(argument->expression, type);
3735                                 }
3736
3737                                 check_format(&result->call);
3738                         }
3739                 } else {
3740                         check_format(&result->call);
3741                 }
3742         }
3743
3744         return result;
3745 }
3746
3747 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3748
3749 static bool same_compound_type(const type_t *type1, const type_t *type2)
3750 {
3751         if(!is_type_compound(type1))
3752                 return false;
3753         if(type1->kind != type2->kind)
3754                 return false;
3755
3756         const compound_type_t *compound1 = &type1->compound;
3757         const compound_type_t *compound2 = &type2->compound;
3758
3759         return compound1->declaration == compound2->declaration;
3760 }
3761
3762 /**
3763  * Parse a conditional expression, ie. 'expression ? ... : ...'.
3764  *
3765  * @param expression  the conditional expression
3766  */
3767 static expression_t *parse_conditional_expression(unsigned precedence,
3768                                                   expression_t *expression)
3769 {
3770         eat('?');
3771
3772         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3773
3774         conditional_expression_t *conditional = &result->conditional;
3775         conditional->condition = expression;
3776
3777         /* 6.5.15.2 */
3778         type_t *condition_type_orig = expression->base.datatype;
3779         if(condition_type_orig != NULL) {
3780                 type_t *condition_type = skip_typeref(condition_type_orig);
3781                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3782                         type_error("expected a scalar type in conditional condition",
3783                                    expression->base.source_position, condition_type_orig);
3784                 }
3785         }
3786
3787         expression_t *true_expression = parse_expression();
3788         expect(':');
3789         expression_t *false_expression = parse_sub_expression(precedence);
3790
3791         conditional->true_expression  = true_expression;
3792         conditional->false_expression = false_expression;
3793
3794         type_t *orig_true_type  = true_expression->base.datatype;
3795         type_t *orig_false_type = false_expression->base.datatype;
3796         if(orig_true_type == NULL || orig_false_type == NULL)
3797                 return result;
3798
3799         type_t *true_type  = skip_typeref(orig_true_type);
3800         type_t *false_type = skip_typeref(orig_false_type);
3801
3802         /* 6.5.15.3 */
3803         type_t *result_type = NULL;
3804         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3805                 result_type = semantic_arithmetic(true_type, false_type);
3806
3807                 true_expression  = create_implicit_cast(true_expression, result_type);
3808                 false_expression = create_implicit_cast(false_expression, result_type);
3809
3810                 conditional->true_expression     = true_expression;
3811                 conditional->false_expression    = false_expression;
3812                 conditional->expression.datatype = result_type;
3813         } else if (same_compound_type(true_type, false_type)
3814                         || (is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3815                                 is_type_atomic(false_type, ATOMIC_TYPE_VOID))) {
3816                 /* just take 1 of the 2 types */
3817                 result_type = true_type;
3818         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3819                         && pointers_compatible(true_type, false_type)) {
3820                 /* ok */
3821                 result_type = true_type;
3822         } else {
3823                 /* TODO */
3824                 type_error_incompatible("while parsing conditional",
3825                                         expression->base.source_position, true_type,
3826                                         false_type);
3827         }
3828
3829         conditional->expression.datatype = result_type;
3830         return result;
3831 }
3832
3833 /**
3834  * Parse an extension expression.
3835  */
3836 static expression_t *parse_extension(unsigned precedence)
3837 {
3838         eat(T___extension__);
3839
3840         /* TODO enable extensions */
3841         expression_t *expression = parse_sub_expression(precedence);
3842         /* TODO disable extensions */
3843         return expression;
3844 }
3845
3846 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3847 {
3848         eat(T___builtin_classify_type);
3849
3850         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
3851         result->base.datatype = type_int;
3852
3853         expect('(');
3854         expression_t *expression = parse_sub_expression(precedence);
3855         expect(')');
3856         result->classify_type.type_expression = expression;
3857
3858         return result;
3859 }
3860
3861 static void semantic_incdec(unary_expression_t *expression)
3862 {
3863         type_t *orig_type = expression->value->base.datatype;
3864         if(orig_type == NULL)
3865                 return;
3866
3867         type_t *type = skip_typeref(orig_type);
3868         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
3869                 /* TODO: improve error message */
3870                 errorf(HERE, "operation needs an arithmetic or pointer type");
3871                 return;
3872         }
3873
3874         expression->expression.datatype = orig_type;
3875 }
3876
3877 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3878 {
3879         type_t *orig_type = expression->value->base.datatype;
3880         if(orig_type == NULL)
3881                 return;
3882
3883         type_t *type = skip_typeref(orig_type);
3884         if(!is_type_arithmetic(type)) {
3885                 /* TODO: improve error message */
3886                 errorf(HERE, "operation needs an arithmetic type");
3887                 return;
3888         }
3889
3890         expression->expression.datatype = orig_type;
3891 }
3892
3893 static void semantic_unexpr_scalar(unary_expression_t *expression)
3894 {
3895         type_t *orig_type = expression->value->base.datatype;
3896         if(orig_type == NULL)
3897                 return;
3898
3899         type_t *type = skip_typeref(orig_type);
3900         if (!is_type_scalar(type)) {
3901                 errorf(HERE, "operand of ! must be of scalar type");
3902                 return;
3903         }
3904
3905         expression->expression.datatype = orig_type;
3906 }
3907
3908 static void semantic_unexpr_integer(unary_expression_t *expression)
3909 {
3910         type_t *orig_type = expression->value->base.datatype;
3911         if(orig_type == NULL)
3912                 return;
3913
3914         type_t *type = skip_typeref(orig_type);
3915         if (!is_type_integer(type)) {
3916                 errorf(HERE, "operand of ~ must be of integer type");
3917                 return;
3918         }
3919
3920         expression->expression.datatype = orig_type;
3921 }
3922
3923 static void semantic_dereference(unary_expression_t *expression)
3924 {
3925         type_t *orig_type = expression->value->base.datatype;
3926         if(orig_type == NULL)
3927                 return;
3928
3929         type_t *type = skip_typeref(orig_type);
3930         if(!is_type_pointer(type)) {
3931                 errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
3932                 return;
3933         }
3934
3935         pointer_type_t *pointer_type = &type->pointer;
3936         type_t         *result_type  = pointer_type->points_to;
3937
3938         result_type = automatic_type_conversion(result_type);
3939         expression->expression.datatype = result_type;
3940 }
3941
3942 static void semantic_take_addr(unary_expression_t *expression)
3943 {
3944         expression_t *value  = expression->value;
3945         value->base.datatype = revert_automatic_type_conversion(value);
3946
3947         type_t *orig_type = value->base.datatype;
3948         if(orig_type == NULL)
3949                 return;
3950
3951         if(value->kind == EXPR_REFERENCE) {
3952                 reference_expression_t *reference   = (reference_expression_t*) value;
3953                 declaration_t          *declaration = reference->declaration;
3954                 if(declaration != NULL) {
3955                         declaration->address_taken = 1;
3956                 }
3957         }
3958
3959         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3960 }
3961
3962 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3963 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3964 {                                                                              \
3965         eat(token_type);                                                           \
3966                                                                                \
3967         expression_t *unary_expression                                             \
3968                 = allocate_expression_zero(unexpression_type);                         \
3969         unary_expression->unary.value = parse_sub_expression(precedence);          \
3970                                                                                    \
3971         sfunc(&unary_expression->unary);                                           \
3972                                                                                \
3973         return unary_expression;                                                   \
3974 }
3975
3976 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
3977                                semantic_unexpr_arithmetic)
3978 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
3979                                semantic_unexpr_arithmetic)
3980 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
3981                                semantic_unexpr_scalar)
3982 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
3983                                semantic_dereference)
3984 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
3985                                semantic_take_addr)
3986 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
3987                                semantic_unexpr_integer)
3988 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
3989                                semantic_incdec)
3990 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
3991                                semantic_incdec)
3992
3993 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3994                                                sfunc)                         \
3995 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3996                                                expression_t *left)            \
3997 {                                                                             \
3998         (void) precedence;                                                        \
3999         eat(token_type);                                                          \
4000                                                                               \
4001         expression_t *unary_expression                                            \
4002                 = allocate_expression_zero(unexpression_type);                        \
4003         unary_expression->unary.value = left;                                     \
4004                                                                                   \
4005         sfunc(&unary_expression->unary);                                          \
4006                                                                               \
4007         return unary_expression;                                                  \
4008 }
4009
4010 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4011                                        EXPR_UNARY_POSTFIX_INCREMENT,
4012                                        semantic_incdec)
4013 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4014                                        EXPR_UNARY_POSTFIX_DECREMENT,
4015                                        semantic_incdec)
4016
4017 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4018 {
4019         /* TODO: handle complex + imaginary types */
4020
4021         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4022         if(type_left == type_long_double || type_right == type_long_double) {
4023                 return type_long_double;
4024         } else if(type_left == type_double || type_right == type_double) {
4025                 return type_double;
4026         } else if(type_left == type_float || type_right == type_float) {
4027                 return type_float;
4028         }
4029
4030         type_right = promote_integer(type_right);
4031         type_left  = promote_integer(type_left);
4032
4033         if(type_left == type_right)
4034                 return type_left;
4035
4036         bool signed_left  = is_type_signed(type_left);
4037         bool signed_right = is_type_signed(type_right);
4038         int  rank_left    = get_rank(type_left);
4039         int  rank_right   = get_rank(type_right);
4040         if(rank_left < rank_right) {
4041                 if(signed_left == signed_right || !signed_right) {
4042                         return type_right;
4043                 } else {
4044                         return type_left;
4045                 }
4046         } else {
4047                 if(signed_left == signed_right || !signed_left) {
4048                         return type_left;
4049                 } else {
4050                         return type_right;
4051                 }
4052         }
4053 }
4054
4055 /**
4056  * Check the semantic restrictions for a binary expression.
4057  */
4058 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4059 {
4060         expression_t *left       = expression->left;
4061         expression_t *right      = expression->right;
4062         type_t       *orig_type_left  = left->base.datatype;
4063         type_t       *orig_type_right = right->base.datatype;
4064
4065         if(orig_type_left == NULL || orig_type_right == NULL)
4066                 return;
4067
4068         type_t *type_left  = skip_typeref(orig_type_left);
4069         type_t *type_right = skip_typeref(orig_type_right);
4070
4071         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4072                 /* TODO: improve error message */
4073                 errorf(HERE, "operation needs arithmetic types");
4074                 return;
4075         }
4076
4077         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4078         expression->left  = create_implicit_cast(left, arithmetic_type);
4079         expression->right = create_implicit_cast(right, arithmetic_type);
4080         expression->expression.datatype = arithmetic_type;
4081 }
4082
4083 static void semantic_shift_op(binary_expression_t *expression)
4084 {
4085         expression_t *left       = expression->left;
4086         expression_t *right      = expression->right;
4087         type_t       *orig_type_left  = left->base.datatype;
4088         type_t       *orig_type_right = right->base.datatype;
4089
4090         if(orig_type_left == NULL || orig_type_right == NULL)
4091                 return;
4092
4093         type_t *type_left  = skip_typeref(orig_type_left);
4094         type_t *type_right = skip_typeref(orig_type_right);
4095
4096         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4097                 /* TODO: improve error message */
4098                 errorf(HERE, "operation needs integer types");
4099                 return;
4100         }
4101
4102         type_left  = promote_integer(type_left);
4103         type_right = promote_integer(type_right);
4104
4105         expression->left  = create_implicit_cast(left, type_left);
4106         expression->right = create_implicit_cast(right, type_right);
4107         expression->expression.datatype = type_left;
4108 }
4109
4110 static void semantic_add(binary_expression_t *expression)
4111 {
4112         expression_t *left            = expression->left;
4113         expression_t *right           = expression->right;
4114         type_t       *orig_type_left  = left->base.datatype;
4115         type_t       *orig_type_right = right->base.datatype;
4116
4117         if(orig_type_left == NULL || orig_type_right == NULL)
4118                 return;
4119
4120         type_t *type_left  = skip_typeref(orig_type_left);
4121         type_t *type_right = skip_typeref(orig_type_right);
4122
4123         /* Â§ 5.6.5 */
4124         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4125                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4126                 expression->left  = create_implicit_cast(left, arithmetic_type);
4127                 expression->right = create_implicit_cast(right, arithmetic_type);
4128                 expression->expression.datatype = arithmetic_type;
4129                 return;
4130         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4131                 expression->expression.datatype = type_left;
4132         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4133                 expression->expression.datatype = type_right;
4134         } else {
4135                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4136         }
4137 }
4138
4139 static void semantic_sub(binary_expression_t *expression)
4140 {
4141         expression_t *left            = expression->left;
4142         expression_t *right           = expression->right;
4143         type_t       *orig_type_left  = left->base.datatype;
4144         type_t       *orig_type_right = right->base.datatype;
4145
4146         if(orig_type_left == NULL || orig_type_right == NULL)
4147                 return;
4148
4149         type_t       *type_left       = skip_typeref(orig_type_left);
4150         type_t       *type_right      = skip_typeref(orig_type_right);
4151
4152         /* Â§ 5.6.5 */
4153         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4154                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4155                 expression->left  = create_implicit_cast(left, arithmetic_type);
4156                 expression->right = create_implicit_cast(right, arithmetic_type);
4157                 expression->expression.datatype = arithmetic_type;
4158                 return;
4159         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4160                 expression->expression.datatype = type_left;
4161         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4162                 if(!pointers_compatible(type_left, type_right)) {
4163                         errorf(HERE, "pointers to incompatible objects to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4164                 } else {
4165                         expression->expression.datatype = type_ptrdiff_t;
4166                 }
4167         } else {
4168                 errorf(HERE, "invalid operands to binary - ('%T', '%T')", orig_type_left, orig_type_right);
4169         }
4170 }
4171
4172 static void semantic_comparison(binary_expression_t *expression)
4173 {
4174         expression_t *left            = expression->left;
4175         expression_t *right           = expression->right;
4176         type_t       *orig_type_left  = left->base.datatype;
4177         type_t       *orig_type_right = right->base.datatype;
4178
4179         if(orig_type_left == NULL || orig_type_right == NULL)
4180                 return;
4181
4182         type_t *type_left  = skip_typeref(orig_type_left);
4183         type_t *type_right = skip_typeref(orig_type_right);
4184
4185         /* TODO non-arithmetic types */
4186         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4187                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4188                 expression->left  = create_implicit_cast(left, arithmetic_type);
4189                 expression->right = create_implicit_cast(right, arithmetic_type);
4190                 expression->expression.datatype = arithmetic_type;
4191         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4192                 /* TODO check compatibility */
4193         } else if (is_type_pointer(type_left)) {
4194                 expression->right = create_implicit_cast(right, type_left);
4195         } else if (is_type_pointer(type_right)) {
4196                 expression->left = create_implicit_cast(left, type_right);
4197         } else {
4198                 type_error_incompatible("invalid operands in comparison",
4199                                         token.source_position, type_left, type_right);
4200         }
4201         expression->expression.datatype = type_int;
4202 }
4203
4204 static void semantic_arithmetic_assign(binary_expression_t *expression)
4205 {
4206         expression_t *left            = expression->left;
4207         expression_t *right           = expression->right;
4208         type_t       *orig_type_left  = left->base.datatype;
4209         type_t       *orig_type_right = right->base.datatype;
4210
4211         if(orig_type_left == NULL || orig_type_right == NULL)
4212                 return;
4213
4214         type_t *type_left  = skip_typeref(orig_type_left);
4215         type_t *type_right = skip_typeref(orig_type_right);
4216
4217         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4218                 /* TODO: improve error message */
4219                 errorf(HERE, "operation needs arithmetic types");
4220                 return;
4221         }
4222
4223         /* combined instructions are tricky. We can't create an implicit cast on
4224          * the left side, because we need the uncasted form for the store.
4225          * The ast2firm pass has to know that left_type must be right_type
4226          * for the arithmetic operation and create a cast by itself */
4227         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4228         expression->right       = create_implicit_cast(right, arithmetic_type);
4229         expression->expression.datatype = type_left;
4230 }
4231
4232 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4233 {
4234         expression_t *left            = expression->left;
4235         expression_t *right           = expression->right;
4236         type_t       *orig_type_left  = left->base.datatype;
4237         type_t       *orig_type_right = right->base.datatype;
4238
4239         if(orig_type_left == NULL || orig_type_right == NULL)
4240                 return;
4241
4242         type_t *type_left  = skip_typeref(orig_type_left);
4243         type_t *type_right = skip_typeref(orig_type_right);
4244
4245         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4246                 /* combined instructions are tricky. We can't create an implicit cast on
4247                  * the left side, because we need the uncasted form for the store.
4248                  * The ast2firm pass has to know that left_type must be right_type
4249                  * for the arithmetic operation and create a cast by itself */
4250                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4251                 expression->right = create_implicit_cast(right, arithmetic_type);
4252                 expression->expression.datatype = type_left;
4253         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4254                 expression->expression.datatype = type_left;
4255         } else {
4256                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4257                 return;
4258         }
4259 }
4260
4261 /**
4262  * Check the semantic restrictions of a logical expression.
4263  */
4264 static void semantic_logical_op(binary_expression_t *expression)
4265 {
4266         expression_t *left            = expression->left;
4267         expression_t *right           = expression->right;
4268         type_t       *orig_type_left  = left->base.datatype;
4269         type_t       *orig_type_right = right->base.datatype;
4270
4271         if(orig_type_left == NULL || orig_type_right == NULL)
4272                 return;
4273
4274         type_t *type_left  = skip_typeref(orig_type_left);
4275         type_t *type_right = skip_typeref(orig_type_right);
4276
4277         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4278                 /* TODO: improve error message */
4279                 errorf(HERE, "operation needs scalar types");
4280                 return;
4281         }
4282
4283         expression->expression.datatype = type_int;
4284 }
4285
4286 /**
4287  * Checks if a compound type has constant fields.
4288  */
4289 static bool has_const_fields(const compound_type_t *type)
4290 {
4291         const context_t     *context = &type->declaration->context;
4292         const declaration_t *declaration = context->declarations;
4293
4294         for (; declaration != NULL; declaration = declaration->next) {
4295                 const type_t *decl_type = skip_typeref(declaration->type);
4296                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4297                         return true;
4298         }
4299         /* TODO */
4300         return false;
4301 }
4302
4303 /**
4304  * Check the semantic restrictions of a binary assign expression.
4305  */
4306 static void semantic_binexpr_assign(binary_expression_t *expression)
4307 {
4308         expression_t *left           = expression->left;
4309         type_t       *orig_type_left = left->base.datatype;
4310
4311         if(orig_type_left == NULL)
4312                 return;
4313
4314         type_t *type_left = revert_automatic_type_conversion(left);
4315         type_left         = skip_typeref(orig_type_left);
4316
4317         /* must be a modifiable lvalue */
4318         if (is_type_array(type_left)) {
4319                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4320                 return;
4321         }
4322         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4323                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left, orig_type_left);
4324                 return;
4325         }
4326         if(is_type_incomplete(type_left)) {
4327                 errorf(HERE, "left-hand side of assignment '%E' has incomplete type '%T'", left, orig_type_left);
4328                 return;
4329         }
4330         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4331                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields", left, orig_type_left);
4332                 return;
4333         }
4334
4335         semantic_assign(orig_type_left, &expression->right, "assignment");
4336
4337         expression->expression.datatype = orig_type_left;
4338 }
4339
4340 static void semantic_comma(binary_expression_t *expression)
4341 {
4342         expression->expression.datatype = expression->right->base.datatype;
4343 }
4344
4345 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4346 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4347                                                 expression_t *left)       \
4348 {                                                                         \
4349         eat(token_type);                                                      \
4350                                                                           \
4351         expression_t *right = parse_sub_expression(precedence + lr);          \
4352                                                                           \
4353         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4354         binexpr->binary.left  = left;                                         \
4355         binexpr->binary.right = right;                                        \
4356         sfunc(&binexpr->binary);                                              \
4357                                                                           \
4358         return binexpr;                                                       \
4359 }
4360
4361 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4362 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4363 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4364 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4365 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4366 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4367 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4368 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4369 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4370
4371 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4372                       semantic_comparison, 1)
4373 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4374                       semantic_comparison, 1)
4375 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4376                       semantic_comparison, 1)
4377 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4378                       semantic_comparison, 1)
4379
4380 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4381                       semantic_binexpr_arithmetic, 1)
4382 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4383                       semantic_binexpr_arithmetic, 1)
4384 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4385                       semantic_binexpr_arithmetic, 1)
4386 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4387                       semantic_logical_op, 1)
4388 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4389                       semantic_logical_op, 1)
4390 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4391                       semantic_shift_op, 1)
4392 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4393                       semantic_shift_op, 1)
4394 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4395                       semantic_arithmetic_addsubb_assign, 0)
4396 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4397                       semantic_arithmetic_addsubb_assign, 0)
4398 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4399                       semantic_arithmetic_assign, 0)
4400 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4401                       semantic_arithmetic_assign, 0)
4402 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4403                       semantic_arithmetic_assign, 0)
4404 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4405                       semantic_arithmetic_assign, 0)
4406 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4407                       semantic_arithmetic_assign, 0)
4408 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4409                       semantic_arithmetic_assign, 0)
4410 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4411                       semantic_arithmetic_assign, 0)
4412 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4413                       semantic_arithmetic_assign, 0)
4414
4415 static expression_t *parse_sub_expression(unsigned precedence)
4416 {
4417         if(token.type < 0) {
4418                 return expected_expression_error();
4419         }
4420
4421         expression_parser_function_t *parser
4422                 = &expression_parsers[token.type];
4423         source_position_t             source_position = token.source_position;
4424         expression_t                 *left;
4425
4426         if(parser->parser != NULL) {
4427                 left = parser->parser(parser->precedence);
4428         } else {
4429                 left = parse_primary_expression();
4430         }
4431         assert(left != NULL);
4432         left->base.source_position = source_position;
4433
4434         while(true) {
4435                 if(token.type < 0) {
4436                         return expected_expression_error();
4437                 }
4438
4439                 parser = &expression_parsers[token.type];
4440                 if(parser->infix_parser == NULL)
4441                         break;
4442                 if(parser->infix_precedence < precedence)
4443                         break;
4444
4445                 left = parser->infix_parser(parser->infix_precedence, left);
4446
4447                 assert(left != NULL);
4448                 assert(left->kind != EXPR_UNKNOWN);
4449                 left->base.source_position = source_position;
4450         }
4451
4452         return left;
4453 }
4454
4455 /**
4456  * Parse an expression.
4457  */
4458 static expression_t *parse_expression(void)
4459 {
4460         return parse_sub_expression(1);
4461 }
4462
4463 /**
4464  * Register a parser for a prefix-like operator with given precedence.
4465  *
4466  * @param parser      the parser function
4467  * @param token_type  the token type of the prefix token
4468  * @param precedence  the precedence of the operator
4469  */
4470 static void register_expression_parser(parse_expression_function parser,
4471                                        int token_type, unsigned precedence)
4472 {
4473         expression_parser_function_t *entry = &expression_parsers[token_type];
4474
4475         if(entry->parser != NULL) {
4476                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4477                 panic("trying to register multiple expression parsers for a token");
4478         }
4479         entry->parser     = parser;
4480         entry->precedence = precedence;
4481 }
4482
4483 /**
4484  * Register a parser for an infix operator with given precedence.
4485  *
4486  * @param parser      the parser function
4487  * @param token_type  the token type of the infix operator
4488  * @param precedence  the precedence of the operator
4489  */
4490 static void register_infix_parser(parse_expression_infix_function parser,
4491                 int token_type, unsigned precedence)
4492 {
4493         expression_parser_function_t *entry = &expression_parsers[token_type];
4494
4495         if(entry->infix_parser != NULL) {
4496                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4497                 panic("trying to register multiple infix expression parsers for a "
4498                       "token");
4499         }
4500         entry->infix_parser     = parser;
4501         entry->infix_precedence = precedence;
4502 }
4503
4504 /**
4505  * Initialize the expression parsers.
4506  */
4507 static void init_expression_parsers(void)
4508 {
4509         memset(&expression_parsers, 0, sizeof(expression_parsers));
4510
4511         register_infix_parser(parse_array_expression,         '[',              30);
4512         register_infix_parser(parse_call_expression,          '(',              30);
4513         register_infix_parser(parse_select_expression,        '.',              30);
4514         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4515         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4516                                                               T_PLUSPLUS,       30);
4517         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4518                                                               T_MINUSMINUS,     30);
4519
4520         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4521         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4522         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4523         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4524         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4525         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4526         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4527         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4528         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4529         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4530         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4531         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4532         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4533                                                     T_EXCLAMATIONMARKEQUAL, 13);
4534         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4535         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4536         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4537         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4538         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4539         register_infix_parser(parse_conditional_expression,   '?',               7);
4540         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4541         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4542         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4543         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4544         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4545         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4546         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4547                                                                 T_LESSLESSEQUAL, 2);
4548         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4549                                                           T_GREATERGREATEREQUAL, 2);
4550         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4551                                                                      T_ANDEQUAL, 2);
4552         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4553                                                                     T_PIPEEQUAL, 2);
4554         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4555                                                                    T_CARETEQUAL, 2);
4556
4557         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4558
4559         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4560         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4561         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4562         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4563         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4564         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4565         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4566                                                                   T_PLUSPLUS,   25);
4567         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4568                                                                   T_MINUSMINUS, 25);
4569         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4570         register_expression_parser(parse_extension,            T___extension__, 25);
4571         register_expression_parser(parse_builtin_classify_type,
4572                                                      T___builtin_classify_type, 25);
4573 }
4574
4575 /**
4576  * Parse a asm statement constraints specification.
4577  */
4578 static asm_constraint_t *parse_asm_constraints(void)
4579 {
4580         asm_constraint_t *result = NULL;
4581         asm_constraint_t *last   = NULL;
4582
4583         while(token.type == T_STRING_LITERAL || token.type == '[') {
4584                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4585                 memset(constraint, 0, sizeof(constraint[0]));
4586
4587                 if(token.type == '[') {
4588                         eat('[');
4589                         if(token.type != T_IDENTIFIER) {
4590                                 parse_error_expected("while parsing asm constraint",
4591                                                      T_IDENTIFIER, 0);
4592                                 return NULL;
4593                         }
4594                         constraint->symbol = token.v.symbol;
4595
4596                         expect(']');
4597                 }
4598
4599                 constraint->constraints = parse_string_literals();
4600                 expect('(');
4601                 constraint->expression = parse_expression();
4602                 expect(')');
4603
4604                 if(last != NULL) {
4605                         last->next = constraint;
4606                 } else {
4607                         result = constraint;
4608                 }
4609                 last = constraint;
4610
4611                 if(token.type != ',')
4612                         break;
4613                 eat(',');
4614         }
4615
4616         return result;
4617 }
4618
4619 /**
4620  * Parse a asm statement clobber specification.
4621  */
4622 static asm_clobber_t *parse_asm_clobbers(void)
4623 {
4624         asm_clobber_t *result = NULL;
4625         asm_clobber_t *last   = NULL;
4626
4627         while(token.type == T_STRING_LITERAL) {
4628                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4629                 clobber->clobber       = parse_string_literals();
4630
4631                 if(last != NULL) {
4632                         last->next = clobber;
4633                 } else {
4634                         result = clobber;
4635                 }
4636                 last = clobber;
4637
4638                 if(token.type != ',')
4639                         break;
4640                 eat(',');
4641         }
4642
4643         return result;
4644 }
4645
4646 /**
4647  * Parse an asm statement.
4648  */
4649 static statement_t *parse_asm_statement(void)
4650 {
4651         eat(T_asm);
4652
4653         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4654         statement->base.source_position = token.source_position;
4655
4656         asm_statement_t *asm_statement = &statement->asms;
4657
4658         if(token.type == T_volatile) {
4659                 next_token();
4660                 asm_statement->is_volatile = true;
4661         }
4662
4663         expect('(');
4664         asm_statement->asm_text = parse_string_literals();
4665
4666         if(token.type != ':')
4667                 goto end_of_asm;
4668         eat(':');
4669
4670         asm_statement->inputs = parse_asm_constraints();
4671         if(token.type != ':')
4672                 goto end_of_asm;
4673         eat(':');
4674
4675         asm_statement->outputs = parse_asm_constraints();
4676         if(token.type != ':')
4677                 goto end_of_asm;
4678         eat(':');
4679
4680         asm_statement->clobbers = parse_asm_clobbers();
4681
4682 end_of_asm:
4683         expect(')');
4684         expect(';');
4685         return statement;
4686 }
4687
4688 /**
4689  * Parse a case statement.
4690  */
4691 static statement_t *parse_case_statement(void)
4692 {
4693         eat(T_case);
4694
4695         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4696
4697         statement->base.source_position  = token.source_position;
4698         statement->case_label.expression = parse_expression();
4699
4700         expect(':');
4701         statement->case_label.label_statement = parse_statement();
4702
4703         return statement;
4704 }
4705
4706 /**
4707  * Parse a default statement.
4708  */
4709 static statement_t *parse_default_statement(void)
4710 {
4711         eat(T_default);
4712
4713         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4714
4715         statement->base.source_position = token.source_position;
4716
4717         expect(':');
4718         statement->label.label_statement = parse_statement();
4719
4720         return statement;
4721 }
4722
4723 /**
4724  * Return the declaration for a given label symbol or create a new one.
4725  */
4726 static declaration_t *get_label(symbol_t *symbol)
4727 {
4728         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4729         assert(current_function != NULL);
4730         /* if we found a label in the same function, then we already created the
4731          * declaration */
4732         if(candidate != NULL
4733                         && candidate->parent_context == &current_function->context) {
4734                 return candidate;
4735         }
4736
4737         /* otherwise we need to create a new one */
4738         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4739         declaration->namespc       = NAMESPACE_LABEL;
4740         declaration->symbol        = symbol;
4741
4742         label_push(declaration);
4743
4744         return declaration;
4745 }
4746
4747 /**
4748  * Parse a label statement.
4749  */
4750 static statement_t *parse_label_statement(void)
4751 {
4752         assert(token.type == T_IDENTIFIER);
4753         symbol_t *symbol = token.v.symbol;
4754         next_token();
4755
4756         declaration_t *label = get_label(symbol);
4757
4758         /* if source position is already set then the label is defined twice,
4759          * otherwise it was just mentioned in a goto so far */
4760         if(label->source_position.input_name != NULL) {
4761                 errorf(HERE, "duplicate label '%s'\n", symbol->string);
4762                 errorf(label->source_position, "previous definition of '%s' was here\n", symbol->string);
4763         } else {
4764                 label->source_position = token.source_position;
4765         }
4766
4767         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4768
4769         label_statement->statement.kind            = STATEMENT_LABEL;
4770         label_statement->statement.source_position = token.source_position;
4771         label_statement->label                     = label;
4772
4773         expect(':');
4774
4775         if(token.type == '}') {
4776                 /* TODO only warn? */
4777                 errorf(HERE, "label at end of compound statement");
4778                 return (statement_t*) label_statement;
4779         } else {
4780                 label_statement->label_statement = parse_statement();
4781         }
4782
4783         return (statement_t*) label_statement;
4784 }
4785
4786 /**
4787  * Parse an if statement.
4788  */
4789 static statement_t *parse_if(void)
4790 {
4791         eat(T_if);
4792
4793         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4794         statement->statement.kind            = STATEMENT_IF;
4795         statement->statement.source_position = token.source_position;
4796
4797         expect('(');
4798         statement->condition = parse_expression();
4799         expect(')');
4800
4801         statement->true_statement = parse_statement();
4802         if(token.type == T_else) {
4803                 next_token();
4804                 statement->false_statement = parse_statement();
4805         }
4806
4807         return (statement_t*) statement;
4808 }
4809
4810 /**
4811  * Parse a switch statement.
4812  */
4813 static statement_t *parse_switch(void)
4814 {
4815         eat(T_switch);
4816
4817         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4818         statement->statement.kind            = STATEMENT_SWITCH;
4819         statement->statement.source_position = token.source_position;
4820
4821         expect('(');
4822         statement->expression = parse_expression();
4823         expect(')');
4824         statement->body = parse_statement();
4825
4826         return (statement_t*) statement;
4827 }
4828
4829 /**
4830  * Parse a while statement.
4831  */
4832 static statement_t *parse_while(void)
4833 {
4834         eat(T_while);
4835
4836         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4837         statement->statement.kind            = STATEMENT_WHILE;
4838         statement->statement.source_position = token.source_position;
4839
4840         expect('(');
4841         statement->condition = parse_expression();
4842         expect(')');
4843         statement->body = parse_statement();
4844
4845         return (statement_t*) statement;
4846 }
4847
4848 /**
4849  * Parse a do statement.
4850  */
4851 static statement_t *parse_do(void)
4852 {
4853         eat(T_do);
4854
4855         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4856         statement->statement.kind            = STATEMENT_DO_WHILE;
4857         statement->statement.source_position = token.source_position;
4858
4859         statement->body = parse_statement();
4860         expect(T_while);
4861         expect('(');
4862         statement->condition = parse_expression();
4863         expect(')');
4864         expect(';');
4865
4866         return (statement_t*) statement;
4867 }
4868
4869 /**
4870  * Parse a for statement.
4871  */
4872 static statement_t *parse_for(void)
4873 {
4874         eat(T_for);
4875
4876         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4877         statement->statement.kind            = STATEMENT_FOR;
4878         statement->statement.source_position = token.source_position;
4879
4880         expect('(');
4881
4882         int         top          = environment_top();
4883         context_t  *last_context = context;
4884         set_context(&statement->context);
4885
4886         if(token.type != ';') {
4887                 if(is_declaration_specifier(&token, false)) {
4888                         parse_declaration(record_declaration);
4889                 } else {
4890                         statement->initialisation = parse_expression();
4891                         expect(';');
4892                 }
4893         } else {
4894                 expect(';');
4895         }
4896
4897         if(token.type != ';') {
4898                 statement->condition = parse_expression();
4899         }
4900         expect(';');
4901         if(token.type != ')') {
4902                 statement->step = parse_expression();
4903         }
4904         expect(')');
4905         statement->body = parse_statement();
4906
4907         assert(context == &statement->context);
4908         set_context(last_context);
4909         environment_pop_to(top);
4910
4911         return (statement_t*) statement;
4912 }
4913
4914 /**
4915  * Parse a goto statement.
4916  */
4917 static statement_t *parse_goto(void)
4918 {
4919         eat(T_goto);
4920
4921         if(token.type != T_IDENTIFIER) {
4922                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4923                 eat_statement();
4924                 return NULL;
4925         }
4926         symbol_t *symbol = token.v.symbol;
4927         next_token();
4928
4929         declaration_t *label = get_label(symbol);
4930
4931         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4932
4933         statement->statement.kind            = STATEMENT_GOTO;
4934         statement->statement.source_position = token.source_position;
4935
4936         statement->label = label;
4937
4938         expect(';');
4939
4940         return (statement_t*) statement;
4941 }
4942
4943 /**
4944  * Parse a continue statement.
4945  */
4946 static statement_t *parse_continue(void)
4947 {
4948         eat(T_continue);
4949         expect(';');
4950
4951         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4952         statement->kind                 = STATEMENT_CONTINUE;
4953         statement->base.source_position = token.source_position;
4954
4955         return statement;
4956 }
4957
4958 /**
4959  * Parse a break statement.
4960  */
4961 static statement_t *parse_break(void)
4962 {
4963         eat(T_break);
4964         expect(';');
4965
4966         statement_t *statement          = allocate_ast_zero(sizeof(statement[0]));
4967         statement->kind                 = STATEMENT_BREAK;
4968         statement->base.source_position = token.source_position;
4969
4970         return statement;
4971 }
4972
4973 /**
4974  * Parse a return statement.
4975  */
4976 static statement_t *parse_return(void)
4977 {
4978         eat(T_return);
4979
4980         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4981
4982         statement->statement.kind            = STATEMENT_RETURN;
4983         statement->statement.source_position = token.source_position;
4984
4985         assert(is_type_function(current_function->type));
4986         function_type_t *function_type = &current_function->type->function;
4987         type_t          *return_type   = function_type->return_type;
4988
4989         expression_t *return_value = NULL;
4990         if(token.type != ';') {
4991                 return_value = parse_expression();
4992         }
4993         expect(';');
4994
4995         if(return_type == NULL)
4996                 return (statement_t*) statement;
4997         if(return_value != NULL && return_value->base.datatype == NULL)
4998                 return (statement_t*) statement;
4999
5000         return_type = skip_typeref(return_type);
5001
5002         if(return_value != NULL) {
5003                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
5004
5005                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5006                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5007                         warningf(HERE, "'return' with a value, in function returning void");
5008                         return_value = NULL;
5009                 } else {
5010                         if(return_type != NULL) {
5011                                 semantic_assign(return_type, &return_value, "'return'");
5012                         }
5013                 }
5014         } else {
5015                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5016                         warningf(HERE, "'return' without value, in function returning non-void");
5017                 }
5018         }
5019         statement->return_value = return_value;
5020
5021         return (statement_t*) statement;
5022 }
5023
5024 /**
5025  * Parse a declaration statement.
5026  */
5027 static statement_t *parse_declaration_statement(void)
5028 {
5029         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5030
5031         statement->base.source_position = token.source_position;
5032
5033         declaration_t *before = last_declaration;
5034         parse_declaration(record_declaration);
5035
5036         if(before == NULL) {
5037                 statement->declaration.declarations_begin = context->declarations;
5038         } else {
5039                 statement->declaration.declarations_begin = before->next;
5040         }
5041         statement->declaration.declarations_end = last_declaration;
5042
5043         return statement;
5044 }
5045
5046 /**
5047  * Parse an expression statement, ie. expr ';'.
5048  */
5049 static statement_t *parse_expression_statement(void)
5050 {
5051         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5052
5053         statement->base.source_position  = token.source_position;
5054         statement->expression.expression = parse_expression();
5055
5056         expect(';');
5057
5058         return statement;
5059 }
5060
5061 /**
5062  * Parse a statement.
5063  */
5064 static statement_t *parse_statement(void)
5065 {
5066         statement_t   *statement = NULL;
5067
5068         /* declaration or statement */
5069         switch(token.type) {
5070         case T_asm:
5071                 statement = parse_asm_statement();
5072                 break;
5073
5074         case T_case:
5075                 statement = parse_case_statement();
5076                 break;
5077
5078         case T_default:
5079                 statement = parse_default_statement();
5080                 break;
5081
5082         case '{':
5083                 statement = parse_compound_statement();
5084                 break;
5085
5086         case T_if:
5087                 statement = parse_if();
5088                 break;
5089
5090         case T_switch:
5091                 statement = parse_switch();
5092                 break;
5093
5094         case T_while:
5095                 statement = parse_while();
5096                 break;
5097
5098         case T_do:
5099                 statement = parse_do();
5100                 break;
5101
5102         case T_for:
5103                 statement = parse_for();
5104                 break;
5105
5106         case T_goto:
5107                 statement = parse_goto();
5108                 break;
5109
5110         case T_continue:
5111                 statement = parse_continue();
5112                 break;
5113
5114         case T_break:
5115                 statement = parse_break();
5116                 break;
5117
5118         case T_return:
5119                 statement = parse_return();
5120                 break;
5121
5122         case ';':
5123                 next_token();
5124                 statement = NULL;
5125                 break;
5126
5127         case T_IDENTIFIER:
5128                 if(look_ahead(1)->type == ':') {
5129                         statement = parse_label_statement();
5130                         break;
5131                 }
5132
5133                 if(is_typedef_symbol(token.v.symbol)) {
5134                         statement = parse_declaration_statement();
5135                         break;
5136                 }
5137
5138                 statement = parse_expression_statement();
5139                 break;
5140
5141         case T___extension__:
5142                 /* this can be a prefix to a declaration or an expression statement */
5143                 /* we simply eat it now and parse the rest with tail recursion */
5144                 do {
5145                         next_token();
5146                 } while(token.type == T___extension__);
5147                 statement = parse_statement();
5148                 break;
5149
5150         DECLARATION_START
5151                 statement = parse_declaration_statement();
5152                 break;
5153
5154         default:
5155                 statement = parse_expression_statement();
5156                 break;
5157         }
5158
5159         assert(statement == NULL
5160                         || statement->base.source_position.input_name != NULL);
5161
5162         return statement;
5163 }
5164
5165 /**
5166  * Parse a compound statement.
5167  */
5168 static statement_t *parse_compound_statement(void)
5169 {
5170         compound_statement_t *compound_statement
5171                 = allocate_ast_zero(sizeof(compound_statement[0]));
5172         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5173         compound_statement->statement.source_position = token.source_position;
5174
5175         eat('{');
5176
5177         int        top          = environment_top();
5178         context_t *last_context = context;
5179         set_context(&compound_statement->context);
5180
5181         statement_t *last_statement = NULL;
5182
5183         while(token.type != '}' && token.type != T_EOF) {
5184                 statement_t *statement = parse_statement();
5185                 if(statement == NULL)
5186                         continue;
5187
5188                 if(last_statement != NULL) {
5189                         last_statement->base.next = statement;
5190                 } else {
5191                         compound_statement->statements = statement;
5192                 }
5193
5194                 while(statement->base.next != NULL)
5195                         statement = statement->base.next;
5196
5197                 last_statement = statement;
5198         }
5199
5200         if(token.type == '}') {
5201                 next_token();
5202         } else {
5203                 errorf(compound_statement->statement.source_position, "end of file while looking for closing '}'");
5204         }
5205
5206         assert(context == &compound_statement->context);
5207         set_context(last_context);
5208         environment_pop_to(top);
5209
5210         return (statement_t*) compound_statement;
5211 }
5212
5213 /**
5214  * Initialize builtin types.
5215  */
5216 static void initialize_builtin_types(void)
5217 {
5218         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5219         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5220         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5221         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5222         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5223         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5224         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5225         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5226
5227         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5228         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5229         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5230         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5231 }
5232
5233 /**
5234  * Parse a translation unit.
5235  */
5236 static translation_unit_t *parse_translation_unit(void)
5237 {
5238         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5239
5240         assert(global_context == NULL);
5241         global_context = &unit->context;
5242
5243         assert(context == NULL);
5244         set_context(&unit->context);
5245
5246         initialize_builtin_types();
5247
5248         while(token.type != T_EOF) {
5249                 parse_external_declaration();
5250         }
5251
5252         assert(context == &unit->context);
5253         context          = NULL;
5254         last_declaration = NULL;
5255
5256         assert(global_context == &unit->context);
5257         global_context = NULL;
5258
5259         return unit;
5260 }
5261
5262 /**
5263  * Parse the input.
5264  *
5265  * @return  the translation unit or NULL if errors occurred.
5266  */
5267 translation_unit_t *parse(void)
5268 {
5269         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5270         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5271         diagnostic_count  = 0;
5272         error_count       = 0;
5273         warning_count     = 0;
5274
5275         type_set_output(stderr);
5276         ast_set_output(stderr);
5277
5278         lookahead_bufpos = 0;
5279         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5280                 next_token();
5281         }
5282         translation_unit_t *unit = parse_translation_unit();
5283
5284         DEL_ARR_F(environment_stack);
5285         DEL_ARR_F(label_stack);
5286
5287         if(error_count > 0)
5288                 return NULL;
5289
5290         return unit;
5291 }
5292
5293 /**
5294  * Initialize the parser.
5295  */
5296 void init_parser(void)
5297 {
5298         init_expression_parsers();
5299         obstack_init(&temp_obst);
5300
5301         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5302         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5303 }
5304
5305 /**
5306  * Terminate the parser.
5307  */
5308 void exit_parser(void)
5309 {
5310         obstack_free(&temp_obst, NULL);
5311 }