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