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