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