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