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