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