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