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