handle automatic type conversion of array and function types like described in the...
[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
3192                                         if(type == NULL)
3193                                                 continue;
3194
3195                                         if(is_type_integer(type)) {
3196                                                 type = promote_integer(type);
3197                                         } else if(type == type_float) {
3198                                                 type = type_double;
3199                                         }
3200                                         argument->expression
3201                                                 = create_implicit_cast(argument->expression, type);
3202                                 }
3203                         }
3204                 }
3205         }
3206
3207         return (expression_t*) call;
3208 }
3209
3210 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3211
3212 static expression_t *parse_conditional_expression(unsigned precedence,
3213                                                   expression_t *expression)
3214 {
3215         eat('?');
3216
3217         conditional_expression_t *conditional
3218                 = allocate_ast_zero(sizeof(conditional[0]));
3219         conditional->expression.type = EXPR_CONDITIONAL;
3220         conditional->condition       = expression;
3221
3222         /* 6.5.15.2 */
3223         type_t *condition_type_orig = conditional->condition->datatype;
3224         if(condition_type_orig != NULL) {
3225                 type_t *condition_type      = skip_typeref(condition_type_orig);
3226                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3227                         type_error("expected a scalar type", expression->source_position,
3228                                            condition_type_orig);
3229                 }
3230         }
3231
3232         expression_t *const t_expr = parse_expression();
3233         conditional->true_expression = t_expr;
3234         expect(':');
3235         expression_t *const f_expr = parse_sub_expression(precedence);
3236         conditional->false_expression = f_expr;
3237
3238         type_t *const true_type  = t_expr->datatype;
3239         if(true_type == NULL)
3240                 return (expression_t*) conditional;
3241         type_t *const false_type = f_expr->datatype;
3242         if(false_type == NULL)
3243                 return (expression_t*) conditional;
3244
3245         type_t *const skipped_true_type  = skip_typeref(true_type);
3246         type_t *const skipped_false_type = skip_typeref(false_type);
3247
3248         /* 6.5.15.3 */
3249         if (skipped_true_type == skipped_false_type) {
3250                 conditional->expression.datatype = skipped_true_type;
3251         } else if (is_type_arithmetic(skipped_true_type) &&
3252                    is_type_arithmetic(skipped_false_type)) {
3253                 type_t *const result = semantic_arithmetic(skipped_true_type,
3254                                                            skipped_false_type);
3255                 conditional->true_expression  = create_implicit_cast(t_expr, result);
3256                 conditional->false_expression = create_implicit_cast(f_expr, result);
3257                 conditional->expression.datatype = result;
3258         } else if (skipped_true_type->type == TYPE_POINTER &&
3259                    skipped_false_type->type == TYPE_POINTER &&
3260                           true /* TODO compatible points_to types */) {
3261                 /* TODO */
3262         } else if(/* (is_null_ptr_const(skipped_true_type) &&
3263                       skipped_false_type->type == TYPE_POINTER)
3264                || (is_null_ptr_const(skipped_false_type) &&
3265                    skipped_true_type->type == TYPE_POINTER) TODO*/ false) {
3266                 /* TODO */
3267         } else if(/* 1 is pointer to object type, other is void* */ false) {
3268                 /* TODO */
3269         } else {
3270                 type_error_incompatible("while parsing conditional",
3271                                         expression->source_position, true_type,
3272                                         skipped_false_type);
3273         }
3274
3275         return (expression_t*) conditional;
3276 }
3277
3278 static expression_t *parse_extension(unsigned precedence)
3279 {
3280         eat(T___extension__);
3281
3282         /* TODO enable extensions */
3283
3284         return parse_sub_expression(precedence);
3285 }
3286
3287 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3288 {
3289         eat(T___builtin_classify_type);
3290
3291         classify_type_expression_t *const classify_type_expr =
3292                 allocate_ast_zero(sizeof(classify_type_expr[0]));
3293         classify_type_expr->expression.type     = EXPR_CLASSIFY_TYPE;
3294         classify_type_expr->expression.datatype = type_int;
3295
3296         expect('(');
3297         expression_t *const expression = parse_sub_expression(precedence);
3298         expect(')');
3299         classify_type_expr->type_expression = expression;
3300
3301         return (expression_t*)classify_type_expr;
3302 }
3303
3304 static void semantic_incdec(unary_expression_t *expression)
3305 {
3306         type_t *orig_type = expression->value->datatype;
3307         if(orig_type == NULL)
3308                 return;
3309
3310         type_t *type = skip_typeref(orig_type);
3311         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
3312                 /* TODO: improve error message */
3313                 parser_print_error_prefix();
3314                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3315                 return;
3316         }
3317
3318         expression->expression.datatype = orig_type;
3319 }
3320
3321 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3322 {
3323         type_t *orig_type = expression->value->datatype;
3324         if(orig_type == NULL)
3325                 return;
3326
3327         type_t *type = skip_typeref(orig_type);
3328         if(!is_type_arithmetic(type)) {
3329                 /* TODO: improve error message */
3330                 parser_print_error_prefix();
3331                 fprintf(stderr, "operation needs an arithmetic type\n");
3332                 return;
3333         }
3334
3335         expression->expression.datatype = orig_type;
3336 }
3337
3338 static void semantic_unexpr_scalar(unary_expression_t *expression)
3339 {
3340         type_t *orig_type = expression->value->datatype;
3341         if(orig_type == NULL)
3342                 return;
3343
3344         type_t *type = skip_typeref(orig_type);
3345         if (!is_type_scalar(type)) {
3346                 parse_error("operand of ! must be of scalar type\n");
3347                 return;
3348         }
3349
3350         expression->expression.datatype = orig_type;
3351 }
3352
3353 static void semantic_unexpr_integer(unary_expression_t *expression)
3354 {
3355         type_t *orig_type = expression->value->datatype;
3356         if(orig_type == NULL)
3357                 return;
3358
3359         type_t *type = skip_typeref(orig_type);
3360         if (!is_type_integer(type)) {
3361                 parse_error("operand of ~ must be of integer type\n");
3362                 return;
3363         }
3364
3365         expression->expression.datatype = orig_type;
3366 }
3367
3368 static void semantic_dereference(unary_expression_t *expression)
3369 {
3370         type_t *orig_type = expression->value->datatype;
3371         if(orig_type == NULL)
3372                 return;
3373
3374         type_t *type = skip_typeref(orig_type);
3375         if(!is_type_pointer(type)) {
3376                 parser_print_error_prefix();
3377                 fputs("'Unary *' needs pointer or arrray type, but type ", stderr);
3378                 print_type_quoted(orig_type);
3379                 fputs(" given.\n", stderr);
3380                 return;
3381         }
3382
3383         pointer_type_t *pointer_type = (pointer_type_t*)type;
3384         type_t         *result_type  = pointer_type->points_to;
3385
3386         result_type = automatic_type_conversion(result_type);
3387         expression->expression.datatype = result_type;
3388 }
3389
3390 static void semantic_take_addr(unary_expression_t *expression)
3391 {
3392         expression_t *value = expression->value;
3393         value->datatype     = revert_automatic_type_conversion(value);
3394
3395         type_t *orig_type = value->datatype;
3396         if(orig_type == NULL)
3397                 return;
3398
3399         if(value->type == EXPR_REFERENCE) {
3400                 reference_expression_t *reference   = (reference_expression_t*) value;
3401                 declaration_t          *declaration = reference->declaration;
3402                 if(declaration != NULL) {
3403                         declaration->address_taken = 1;
3404                 }
3405         }
3406
3407         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3408 }
3409
3410 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3411 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3412 {                                                                              \
3413         eat(token_type);                                                           \
3414                                                                                \
3415         unary_expression_t *unary_expression                                       \
3416                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
3417         unary_expression->expression.type     = EXPR_UNARY;                        \
3418         unary_expression->type                = unexpression_type;                 \
3419         unary_expression->value               = parse_sub_expression(precedence);  \
3420                                                                                    \
3421         sfunc(unary_expression);                                                   \
3422                                                                                \
3423         return (expression_t*) unary_expression;                                   \
3424 }
3425
3426 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
3427 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
3428 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
3429 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
3430 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
3431 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
3432                                semantic_unexpr_integer)
3433 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
3434                                semantic_incdec)
3435 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
3436                                semantic_incdec)
3437
3438 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3439                                                sfunc)                         \
3440 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3441                                                expression_t *left)            \
3442 {                                                                             \
3443         (void) precedence;                                                        \
3444         eat(token_type);                                                          \
3445                                                                               \
3446         unary_expression_t *unary_expression                                      \
3447                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
3448         unary_expression->expression.type     = EXPR_UNARY;                       \
3449         unary_expression->type                = unexpression_type;                \
3450         unary_expression->value               = left;                             \
3451                                                                                   \
3452         sfunc(unary_expression);                                                  \
3453                                                                               \
3454         return (expression_t*) unary_expression;                                  \
3455 }
3456
3457 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3458                                        semantic_incdec)
3459 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3460                                        semantic_incdec)
3461
3462 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3463 {
3464         /* TODO: handle complex + imaginary types */
3465
3466         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3467         if(type_left == type_long_double || type_right == type_long_double) {
3468                 return type_long_double;
3469         } else if(type_left == type_double || type_right == type_double) {
3470                 return type_double;
3471         } else if(type_left == type_float || type_right == type_float) {
3472                 return type_float;
3473         }
3474
3475         type_right = promote_integer(type_right);
3476         type_left  = promote_integer(type_left);
3477
3478         if(type_left == type_right)
3479                 return type_left;
3480
3481         bool signed_left  = is_type_signed(type_left);
3482         bool signed_right = is_type_signed(type_right);
3483         if(get_rank(type_left) < get_rank(type_right)) {
3484                 if(signed_left == signed_right || !signed_right) {
3485                         return type_right;
3486                 } else {
3487                         return type_left;
3488                 }
3489         } else {
3490                 if(signed_left == signed_right || !signed_left) {
3491                         return type_left;
3492                 } else {
3493                         return type_right;
3494                 }
3495         }
3496 }
3497
3498 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3499 {
3500         expression_t *left       = expression->left;
3501         expression_t *right      = expression->right;
3502         type_t       *orig_type_left  = left->datatype;
3503         type_t       *orig_type_right = right->datatype;
3504
3505         if(orig_type_left == NULL || orig_type_right == NULL)
3506                 return;
3507
3508         type_t *type_left  = skip_typeref(orig_type_left);
3509         type_t *type_right = skip_typeref(orig_type_right);
3510
3511         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3512                 /* TODO: improve error message */
3513                 parser_print_error_prefix();
3514                 fprintf(stderr, "operation needs arithmetic types\n");
3515                 return;
3516         }
3517
3518         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3519         expression->left  = create_implicit_cast(left, arithmetic_type);
3520         expression->right = create_implicit_cast(right, arithmetic_type);
3521         expression->expression.datatype = arithmetic_type;
3522 }
3523
3524 static void semantic_shift_op(binary_expression_t *expression)
3525 {
3526         expression_t *left       = expression->left;
3527         expression_t *right      = expression->right;
3528         type_t       *orig_type_left  = left->datatype;
3529         type_t       *orig_type_right = right->datatype;
3530
3531         if(orig_type_left == NULL || orig_type_right == NULL)
3532                 return;
3533
3534         type_t *type_left  = skip_typeref(orig_type_left);
3535         type_t *type_right = skip_typeref(orig_type_right);
3536
3537         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3538                 /* TODO: improve error message */
3539                 parser_print_error_prefix();
3540                 fprintf(stderr, "operation needs integer types\n");
3541                 return;
3542         }
3543
3544         type_left  = promote_integer(type_left);
3545         type_right = promote_integer(type_right);
3546
3547         expression->left  = create_implicit_cast(left, type_left);
3548         expression->right = create_implicit_cast(right, type_right);
3549         expression->expression.datatype = type_left;
3550 }
3551
3552 static void semantic_add(binary_expression_t *expression)
3553 {
3554         expression_t *left            = expression->left;
3555         expression_t *right           = expression->right;
3556         type_t       *orig_type_left  = left->datatype;
3557         type_t       *orig_type_right = right->datatype;
3558
3559         if(orig_type_left == NULL || orig_type_right == NULL)
3560                 return;
3561
3562         type_t *type_left  = skip_typeref(orig_type_left);
3563         type_t *type_right = skip_typeref(orig_type_right);
3564
3565         /* Â§ 5.6.5 */
3566         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3567                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3568                 expression->left  = create_implicit_cast(left, arithmetic_type);
3569                 expression->right = create_implicit_cast(right, arithmetic_type);
3570                 expression->expression.datatype = arithmetic_type;
3571                 return;
3572         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
3573                 expression->expression.datatype = type_left;
3574         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
3575                 expression->expression.datatype = type_right;
3576         } else {
3577                 parser_print_error_prefix();
3578                 fprintf(stderr, "invalid operands to binary + (");
3579                 print_type_quoted(orig_type_left);
3580                 fprintf(stderr, ", ");
3581                 print_type_quoted(orig_type_right);
3582                 fprintf(stderr, ")\n");
3583         }
3584 }
3585
3586 static void semantic_sub(binary_expression_t *expression)
3587 {
3588         expression_t *left            = expression->left;
3589         expression_t *right           = expression->right;
3590         type_t       *orig_type_left  = left->datatype;
3591         type_t       *orig_type_right = right->datatype;
3592
3593         if(orig_type_left == NULL || orig_type_right == NULL)
3594                 return;
3595
3596         type_t       *type_left       = skip_typeref(orig_type_left);
3597         type_t       *type_right      = skip_typeref(orig_type_right);
3598
3599         /* Â§ 5.6.5 */
3600         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3601                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3602                 expression->left  = create_implicit_cast(left, arithmetic_type);
3603                 expression->right = create_implicit_cast(right, arithmetic_type);
3604                 expression->expression.datatype = arithmetic_type;
3605                 return;
3606         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3607                 expression->expression.datatype = type_left;
3608         } else if(type_left->type == TYPE_POINTER &&
3609                         type_right->type == TYPE_POINTER) {
3610                 if(!pointers_compatible(type_left, type_right)) {
3611                         parser_print_error_prefix();
3612                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3613                         print_type_quoted(orig_type_left);
3614                         fprintf(stderr, ", ");
3615                         print_type_quoted(orig_type_right);
3616                         fprintf(stderr, ")\n");
3617                 } else {
3618                         expression->expression.datatype = type_ptrdiff_t;
3619                 }
3620         } else {
3621                 parser_print_error_prefix();
3622                 fprintf(stderr, "invalid operands to binary - (");
3623                 print_type_quoted(orig_type_left);
3624                 fprintf(stderr, ", ");
3625                 print_type_quoted(orig_type_right);
3626                 fprintf(stderr, ")\n");
3627         }
3628 }
3629
3630 static void semantic_comparison(binary_expression_t *expression)
3631 {
3632         expression_t *left            = expression->left;
3633         expression_t *right           = expression->right;
3634         type_t       *orig_type_left  = left->datatype;
3635         type_t       *orig_type_right = right->datatype;
3636
3637         if(orig_type_left == NULL || orig_type_right == NULL)
3638                 return;
3639
3640         type_t *type_left  = skip_typeref(orig_type_left);
3641         type_t *type_right = skip_typeref(orig_type_right);
3642
3643         /* TODO non-arithmetic types */
3644         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3645                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3646                 expression->left  = create_implicit_cast(left, arithmetic_type);
3647                 expression->right = create_implicit_cast(right, arithmetic_type);
3648                 expression->expression.datatype = arithmetic_type;
3649         } else if (type_left->type  == TYPE_POINTER &&
3650                    type_right->type == TYPE_POINTER) {
3651                 /* TODO check compatibility */
3652         } else if (type_left->type == TYPE_POINTER) {
3653                 expression->right = create_implicit_cast(right, type_left);
3654         } else if (type_right->type == TYPE_POINTER) {
3655                 expression->left = create_implicit_cast(left, type_right);
3656         } else {
3657                 type_error_incompatible("invalid operands in comparison",
3658                                         token.source_position, type_left, type_right);
3659         }
3660         expression->expression.datatype = type_int;
3661 }
3662
3663 static void semantic_arithmetic_assign(binary_expression_t *expression)
3664 {
3665         expression_t *left            = expression->left;
3666         expression_t *right           = expression->right;
3667         type_t       *orig_type_left  = left->datatype;
3668         type_t       *orig_type_right = right->datatype;
3669
3670         if(orig_type_left == NULL || orig_type_right == NULL)
3671                 return;
3672
3673         type_t *type_left  = skip_typeref(orig_type_left);
3674         type_t *type_right = skip_typeref(orig_type_right);
3675
3676         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3677                 /* TODO: improve error message */
3678                 parser_print_error_prefix();
3679                 fprintf(stderr, "operation needs arithmetic types\n");
3680                 return;
3681         }
3682
3683         /* combined instructions are tricky. We can't create an implicit cast on
3684          * the left side, because we need the uncasted form for the store.
3685          * The ast2firm pass has to know that left_type must be right_type
3686          * for the arithmeitc operation and create a cast by itself */
3687         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3688         expression->right       = create_implicit_cast(right, arithmetic_type);
3689         expression->expression.datatype = type_left;
3690 }
3691
3692 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
3693 {
3694         expression_t *left            = expression->left;
3695         expression_t *right           = expression->right;
3696         type_t       *orig_type_left  = left->datatype;
3697         type_t       *orig_type_right = right->datatype;
3698
3699         if(orig_type_left == NULL || orig_type_right == NULL)
3700                 return;
3701
3702         type_t *type_left  = skip_typeref(orig_type_left);
3703         type_t *type_right = skip_typeref(orig_type_right);
3704
3705         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3706                 /* combined instructions are tricky. We can't create an implicit cast on
3707                  * the left side, because we need the uncasted form for the store.
3708                  * The ast2firm pass has to know that left_type must be right_type
3709                  * for the arithmeitc operation and create a cast by itself */
3710                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
3711                 expression->right = create_implicit_cast(right, arithmetic_type);
3712                 expression->expression.datatype = type_left;
3713         } else if (type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3714                 expression->expression.datatype = type_left;
3715         } else {
3716                 parser_print_error_prefix();
3717                 fputs("Incompatible types ", stderr);
3718                 print_type_quoted(orig_type_left);
3719                 fputs(" and ", stderr);
3720                 print_type_quoted(orig_type_right);
3721                 fputs(" in assignment\n", stderr);
3722                 return;
3723         }
3724 }
3725
3726 static void semantic_logical_op(binary_expression_t *expression)
3727 {
3728         expression_t *left            = expression->left;
3729         expression_t *right           = expression->right;
3730         type_t       *orig_type_left  = left->datatype;
3731         type_t       *orig_type_right = right->datatype;
3732
3733         if(orig_type_left == NULL || orig_type_right == NULL)
3734                 return;
3735
3736         type_t *type_left  = skip_typeref(orig_type_left);
3737         type_t *type_right = skip_typeref(orig_type_right);
3738
3739         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
3740                 /* TODO: improve error message */
3741                 parser_print_error_prefix();
3742                 fprintf(stderr, "operation needs scalar types\n");
3743                 return;
3744         }
3745
3746         expression->expression.datatype = type_int;
3747 }
3748
3749 static bool has_const_fields(type_t *type)
3750 {
3751         (void) type;
3752         /* TODO */
3753         return false;
3754 }
3755
3756 static void semantic_binexpr_assign(binary_expression_t *expression)
3757 {
3758         expression_t *left           = expression->left;
3759         type_t       *orig_type_left = left->datatype;
3760
3761         if(orig_type_left == NULL)
3762                 return;
3763
3764         type_t *type_left = revert_automatic_type_conversion(left);
3765         type_left = skip_typeref(orig_type_left);
3766
3767         /* must be a modifiable lvalue */
3768         if (type_left->type == TYPE_ARRAY) {
3769                 parser_print_error_prefix();
3770                 fprintf(stderr, "Cannot assign to arrays ('");
3771                 print_expression(left);
3772                 fprintf(stderr, "')\n");
3773                 return;
3774         }
3775         if(type_left->qualifiers & TYPE_QUALIFIER_CONST) {
3776                 parser_print_error_prefix();
3777                 fprintf(stderr, "assignment to readonly location '");
3778                 print_expression(left);
3779                 fprintf(stderr, "' (type ");
3780                 print_type_quoted(orig_type_left);
3781                 fprintf(stderr, ")\n");
3782                 return;
3783         }
3784         if(is_type_incomplete(type_left)) {
3785                 parser_print_error_prefix();
3786                 fprintf(stderr, "left-hand side of assignment '");
3787                 print_expression(left);
3788                 fprintf(stderr, "' has incomplete type ");
3789                 print_type_quoted(orig_type_left);
3790                 fprintf(stderr, "\n");
3791                 return;
3792         }
3793         if(is_type_compound(type_left) && has_const_fields(type_left)) {
3794                 parser_print_error_prefix();
3795                 fprintf(stderr, "can't assign to '");
3796                 print_expression(left);
3797                 fprintf(stderr, "' because compound type ");
3798                 print_type_quoted(orig_type_left);
3799                 fprintf(stderr, " has readonly fields\n");
3800                 return;
3801         }
3802
3803         semantic_assign(orig_type_left, &expression->right, "assignment");
3804
3805         expression->expression.datatype = orig_type_left;
3806 }
3807
3808 static void semantic_comma(binary_expression_t *expression)
3809 {
3810         expression->expression.datatype = expression->right->datatype;
3811 }
3812
3813 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
3814 static expression_t *parse_##binexpression_type(unsigned precedence,     \
3815                                                 expression_t *left)      \
3816 {                                                                        \
3817         eat(token_type);                                                     \
3818                                                                          \
3819         expression_t *right = parse_sub_expression(precedence + lr);         \
3820                                                                          \
3821         binary_expression_t *binexpr                                         \
3822                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
3823         binexpr->expression.type     = EXPR_BINARY;                          \
3824         binexpr->type                = binexpression_type;                   \
3825         binexpr->left                = left;                                 \
3826         binexpr->right               = right;                                \
3827         sfunc(binexpr);                                                      \
3828                                                                          \
3829         return (expression_t*) binexpr;                                      \
3830 }
3831
3832 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
3833 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
3834 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
3835 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
3836 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
3837 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
3838 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
3839 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
3840 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
3841 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
3842 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
3843                       semantic_comparison, 1)
3844 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
3845 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
3846                       semantic_comparison, 1)
3847 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
3848 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
3849 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
3850 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
3851 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
3852 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
3853                       semantic_shift_op, 1)
3854 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
3855                       semantic_shift_op, 1)
3856 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
3857                       semantic_arithmetic_addsubb_assign, 0)
3858 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
3859                       semantic_arithmetic_addsubb_assign, 0)
3860 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
3861                       semantic_arithmetic_assign, 0)
3862 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
3863                       semantic_arithmetic_assign, 0)
3864 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
3865                       semantic_arithmetic_assign, 0)
3866 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
3867                       semantic_arithmetic_assign, 0)
3868 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
3869                       semantic_arithmetic_assign, 0)
3870 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
3871                       semantic_arithmetic_assign, 0)
3872 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
3873                       semantic_arithmetic_assign, 0)
3874 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
3875                       semantic_arithmetic_assign, 0)
3876
3877 static expression_t *parse_sub_expression(unsigned precedence)
3878 {
3879         if(token.type < 0) {
3880                 return expected_expression_error();
3881         }
3882
3883         expression_parser_function_t *parser
3884                 = &expression_parsers[token.type];
3885         source_position_t             source_position = token.source_position;
3886         expression_t                 *left;
3887
3888         if(parser->parser != NULL) {
3889                 left = parser->parser(parser->precedence);
3890         } else {
3891                 left = parse_primary_expression();
3892         }
3893         assert(left != NULL);
3894         left->source_position = source_position;
3895
3896         while(true) {
3897                 if(token.type < 0) {
3898                         return expected_expression_error();
3899                 }
3900
3901                 parser = &expression_parsers[token.type];
3902                 if(parser->infix_parser == NULL)
3903                         break;
3904                 if(parser->infix_precedence < precedence)
3905                         break;
3906
3907                 left = parser->infix_parser(parser->infix_precedence, left);
3908
3909                 assert(left != NULL);
3910                 assert(left->type != EXPR_UNKNOWN);
3911                 left->source_position = source_position;
3912         }
3913
3914         return left;
3915 }
3916
3917 static expression_t *parse_expression(void)
3918 {
3919         return parse_sub_expression(1);
3920 }
3921
3922
3923
3924 static void register_expression_parser(parse_expression_function parser,
3925                                        int token_type, unsigned precedence)
3926 {
3927         expression_parser_function_t *entry = &expression_parsers[token_type];
3928
3929         if(entry->parser != NULL) {
3930                 fprintf(stderr, "for token ");
3931                 print_token_type(stderr, token_type);
3932                 fprintf(stderr, "\n");
3933                 panic("trying to register multiple expression parsers for a token");
3934         }
3935         entry->parser     = parser;
3936         entry->precedence = precedence;
3937 }
3938
3939 static void register_expression_infix_parser(
3940                 parse_expression_infix_function parser, int token_type,
3941                 unsigned precedence)
3942 {
3943         expression_parser_function_t *entry = &expression_parsers[token_type];
3944
3945         if(entry->infix_parser != NULL) {
3946                 fprintf(stderr, "for token ");
3947                 print_token_type(stderr, token_type);
3948                 fprintf(stderr, "\n");
3949                 panic("trying to register multiple infix expression parsers for a "
3950                       "token");
3951         }
3952         entry->infix_parser     = parser;
3953         entry->infix_precedence = precedence;
3954 }
3955
3956 static void init_expression_parsers(void)
3957 {
3958         memset(&expression_parsers, 0, sizeof(expression_parsers));
3959
3960         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
3961         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
3962         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
3963         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
3964         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
3965                                                               T_GREATERGREATER, 16);
3966         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
3967         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
3968         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
3969         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
3970         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
3971         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
3972                                                                 T_GREATEREQUAL, 14);
3973         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
3974         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
3975                                                         T_EXCLAMATIONMARKEQUAL, 13);
3976         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
3977         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
3978         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
3979         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
3980         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
3981         register_expression_infix_parser(parse_conditional_expression, '?',      7);
3982         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
3983         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
3984         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
3985         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
3986                                                                 T_ASTERISKEQUAL, 2);
3987         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
3988         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
3989                                                                  T_PERCENTEQUAL, 2);
3990         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
3991                                                                 T_LESSLESSEQUAL, 2);
3992         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
3993                                                           T_GREATERGREATEREQUAL, 2);
3994         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
3995                                                                      T_ANDEQUAL, 2);
3996         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
3997                                                                     T_PIPEEQUAL, 2);
3998         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
3999                                                                    T_CARETEQUAL, 2);
4000
4001         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
4002
4003         register_expression_infix_parser(parse_array_expression,        '[',    30);
4004         register_expression_infix_parser(parse_call_expression,         '(',    30);
4005         register_expression_infix_parser(parse_select_expression,       '.',    30);
4006         register_expression_infix_parser(parse_select_expression,
4007                                                                 T_MINUSGREATER, 30);
4008         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
4009                                          T_PLUSPLUS, 30);
4010         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
4011                                          T_MINUSMINUS, 30);
4012
4013         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
4014         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
4015         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
4016         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
4017         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
4018         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
4019         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
4020         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
4021         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4022         register_expression_parser(parse_extension,            T___extension__, 25);
4023         register_expression_parser(parse_builtin_classify_type,
4024                                                      T___builtin_classify_type, 25);
4025 }
4026
4027
4028 static statement_t *parse_case_statement(void)
4029 {
4030         eat(T_case);
4031         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4032         label->statement.type            = STATEMENT_CASE_LABEL;
4033         label->statement.source_position = token.source_position;
4034
4035         label->expression = parse_expression();
4036
4037         expect(':');
4038         label->label_statement = parse_statement();
4039
4040         return (statement_t*) label;
4041 }
4042
4043 static statement_t *parse_default_statement(void)
4044 {
4045         eat(T_default);
4046
4047         case_label_statement_t *label = allocate_ast_zero(sizeof(label[0]));
4048         label->statement.type            = STATEMENT_CASE_LABEL;
4049         label->statement.source_position = token.source_position;
4050
4051         expect(':');
4052         label->label_statement = parse_statement();
4053
4054         return (statement_t*) label;
4055 }
4056
4057 static declaration_t *get_label(symbol_t *symbol)
4058 {
4059         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4060         assert(current_function != NULL);
4061         /* if we found a label in the same function, then we already created the
4062          * declaration */
4063         if(candidate != NULL
4064                         && candidate->parent_context == &current_function->context) {
4065                 return candidate;
4066         }
4067
4068         /* otherwise we need to create a new one */
4069         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
4070         declaration->namespc     = NAMESPACE_LABEL;
4071         declaration->symbol        = symbol;
4072
4073         label_push(declaration);
4074
4075         return declaration;
4076 }
4077
4078 static statement_t *parse_label_statement(void)
4079 {
4080         assert(token.type == T_IDENTIFIER);
4081         symbol_t *symbol = token.v.symbol;
4082         next_token();
4083
4084         declaration_t *label = get_label(symbol);
4085
4086         /* if source position is already set then the label is defined twice,
4087          * otherwise it was just mentioned in a goto so far */
4088         if(label->source_position.input_name != NULL) {
4089                 parser_print_error_prefix();
4090                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
4091                 parser_print_error_prefix_pos(label->source_position);
4092                 fprintf(stderr, "previous definition of '%s' was here\n",
4093                         symbol->string);
4094         } else {
4095                 label->source_position = token.source_position;
4096         }
4097
4098         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
4099
4100         label_statement->statement.type            = STATEMENT_LABEL;
4101         label_statement->statement.source_position = token.source_position;
4102         label_statement->label                     = label;
4103
4104         expect(':');
4105
4106         if(token.type == '}') {
4107                 parse_error("label at end of compound statement");
4108                 return (statement_t*) label_statement;
4109         } else {
4110                 label_statement->label_statement = parse_statement();
4111         }
4112
4113         return (statement_t*) label_statement;
4114 }
4115
4116 static statement_t *parse_if(void)
4117 {
4118         eat(T_if);
4119
4120         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4121         statement->statement.type            = STATEMENT_IF;
4122         statement->statement.source_position = token.source_position;
4123
4124         expect('(');
4125         statement->condition = parse_expression();
4126         expect(')');
4127
4128         statement->true_statement = parse_statement();
4129         if(token.type == T_else) {
4130                 next_token();
4131                 statement->false_statement = parse_statement();
4132         }
4133
4134         return (statement_t*) statement;
4135 }
4136
4137 static statement_t *parse_switch(void)
4138 {
4139         eat(T_switch);
4140
4141         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4142         statement->statement.type            = STATEMENT_SWITCH;
4143         statement->statement.source_position = token.source_position;
4144
4145         expect('(');
4146         statement->expression = parse_expression();
4147         expect(')');
4148         statement->body = parse_statement();
4149
4150         return (statement_t*) statement;
4151 }
4152
4153 static statement_t *parse_while(void)
4154 {
4155         eat(T_while);
4156
4157         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4158         statement->statement.type            = STATEMENT_WHILE;
4159         statement->statement.source_position = token.source_position;
4160
4161         expect('(');
4162         statement->condition = parse_expression();
4163         expect(')');
4164         statement->body = parse_statement();
4165
4166         return (statement_t*) statement;
4167 }
4168
4169 static statement_t *parse_do(void)
4170 {
4171         eat(T_do);
4172
4173         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4174         statement->statement.type            = STATEMENT_DO_WHILE;
4175         statement->statement.source_position = token.source_position;
4176
4177         statement->body = parse_statement();
4178         expect(T_while);
4179         expect('(');
4180         statement->condition = parse_expression();
4181         expect(')');
4182         expect(';');
4183
4184         return (statement_t*) statement;
4185 }
4186
4187 static statement_t *parse_for(void)
4188 {
4189         eat(T_for);
4190
4191         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4192         statement->statement.type            = STATEMENT_FOR;
4193         statement->statement.source_position = token.source_position;
4194
4195         expect('(');
4196
4197         int         top          = environment_top();
4198         context_t  *last_context = context;
4199         set_context(&statement->context);
4200
4201         if(token.type != ';') {
4202                 if(is_declaration_specifier(&token, false)) {
4203                         parse_declaration();
4204                 } else {
4205                         statement->initialisation = parse_expression();
4206                         expect(';');
4207                 }
4208         } else {
4209                 expect(';');
4210         }
4211
4212         if(token.type != ';') {
4213                 statement->condition = parse_expression();
4214         }
4215         expect(';');
4216         if(token.type != ')') {
4217                 statement->step = parse_expression();
4218         }
4219         expect(')');
4220         statement->body = parse_statement();
4221
4222         assert(context == &statement->context);
4223         set_context(last_context);
4224         environment_pop_to(top);
4225
4226         return (statement_t*) statement;
4227 }
4228
4229 static statement_t *parse_goto(void)
4230 {
4231         eat(T_goto);
4232
4233         if(token.type != T_IDENTIFIER) {
4234                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4235                 eat_statement();
4236                 return NULL;
4237         }
4238         symbol_t *symbol = token.v.symbol;
4239         next_token();
4240
4241         declaration_t *label = get_label(symbol);
4242
4243         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4244
4245         statement->statement.type            = STATEMENT_GOTO;
4246         statement->statement.source_position = token.source_position;
4247
4248         statement->label = label;
4249
4250         expect(';');
4251
4252         return (statement_t*) statement;
4253 }
4254
4255 static statement_t *parse_continue(void)
4256 {
4257         eat(T_continue);
4258         expect(';');
4259
4260         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
4261         statement->type            = STATEMENT_CONTINUE;
4262         statement->source_position = token.source_position;
4263
4264         return statement;
4265 }
4266
4267 static statement_t *parse_break(void)
4268 {
4269         eat(T_break);
4270         expect(';');
4271
4272         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
4273         statement->type            = STATEMENT_BREAK;
4274         statement->source_position = token.source_position;
4275
4276         return statement;
4277 }
4278
4279 static statement_t *parse_return(void)
4280 {
4281         eat(T_return);
4282
4283         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4284
4285         statement->statement.type            = STATEMENT_RETURN;
4286         statement->statement.source_position = token.source_position;
4287
4288         assert(current_function->type->type == TYPE_FUNCTION);
4289         function_type_t *function_type = (function_type_t*) current_function->type;
4290         type_t          *return_type   = function_type->result_type;
4291
4292         expression_t *return_value;
4293         if(token.type != ';') {
4294                 return_value = parse_expression();
4295
4296                 if(return_type == type_void && return_value->datatype != type_void) {
4297                         parse_warning("'return' with a value, in function returning void");
4298                         return_value = NULL;
4299                 } else {
4300                         if(return_type != NULL) {
4301                                 semantic_assign(return_type, &return_value, "'return'");
4302                         }
4303                 }
4304         } else {
4305                 return_value = NULL;
4306                 if(return_type != type_void) {
4307                         parse_warning("'return' without value, in function returning "
4308                                       "non-void");
4309                 }
4310         }
4311         statement->return_value = return_value;
4312
4313         expect(';');
4314
4315         return (statement_t*) statement;
4316 }
4317
4318 static statement_t *parse_declaration_statement(void)
4319 {
4320         declaration_t *before = last_declaration;
4321
4322         declaration_statement_t *statement
4323                 = allocate_ast_zero(sizeof(statement[0]));
4324         statement->statement.type            = STATEMENT_DECLARATION;
4325         statement->statement.source_position = token.source_position;
4326
4327         declaration_specifiers_t specifiers;
4328         memset(&specifiers, 0, sizeof(specifiers));
4329         parse_declaration_specifiers(&specifiers);
4330
4331         if(token.type == ';') {
4332                 eat(';');
4333         } else {
4334                 parse_init_declarators(&specifiers);
4335         }
4336
4337         if(before == NULL) {
4338                 statement->declarations_begin = context->declarations;
4339         } else {
4340                 statement->declarations_begin = before->next;
4341         }
4342         statement->declarations_end = last_declaration;
4343
4344         return (statement_t*) statement;
4345 }
4346
4347 static statement_t *parse_expression_statement(void)
4348 {
4349         expression_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4350         statement->statement.type            = STATEMENT_EXPRESSION;
4351         statement->statement.source_position = token.source_position;
4352
4353         statement->expression = parse_expression();
4354
4355         expect(';');
4356
4357         return (statement_t*) statement;
4358 }
4359
4360 static statement_t *parse_statement(void)
4361 {
4362         statement_t   *statement = NULL;
4363
4364         /* declaration or statement */
4365         switch(token.type) {
4366         case T_case:
4367                 statement = parse_case_statement();
4368                 break;
4369
4370         case T_default:
4371                 statement = parse_default_statement();
4372                 break;
4373
4374         case '{':
4375                 statement = parse_compound_statement();
4376                 break;
4377
4378         case T_if:
4379                 statement = parse_if();
4380                 break;
4381
4382         case T_switch:
4383                 statement = parse_switch();
4384                 break;
4385
4386         case T_while:
4387                 statement = parse_while();
4388                 break;
4389
4390         case T_do:
4391                 statement = parse_do();
4392                 break;
4393
4394         case T_for:
4395                 statement = parse_for();
4396                 break;
4397
4398         case T_goto:
4399                 statement = parse_goto();
4400                 break;
4401
4402         case T_continue:
4403                 statement = parse_continue();
4404                 break;
4405
4406         case T_break:
4407                 statement = parse_break();
4408                 break;
4409
4410         case T_return:
4411                 statement = parse_return();
4412                 break;
4413
4414         case ';':
4415                 next_token();
4416                 statement = NULL;
4417                 break;
4418
4419         case T_IDENTIFIER:
4420                 if(look_ahead(1)->type == ':') {
4421                         statement = parse_label_statement();
4422                         break;
4423                 }
4424
4425                 if(is_typedef_symbol(token.v.symbol)) {
4426                         statement = parse_declaration_statement();
4427                         break;
4428                 }
4429
4430                 statement = parse_expression_statement();
4431                 break;
4432
4433         case T___extension__:
4434                 /* this can be a prefix to a declaration or an expression statement */
4435                 /* we simply eat it now and parse the rest with tail recursion */
4436                 do {
4437                         next_token();
4438                 } while(token.type == T___extension__);
4439                 statement = parse_statement();
4440                 break;
4441
4442         DECLARATION_START
4443                 statement = parse_declaration_statement();
4444                 break;
4445
4446         default:
4447                 statement = parse_expression_statement();
4448                 break;
4449         }
4450
4451         assert(statement == NULL || statement->source_position.input_name != NULL);
4452
4453         return statement;
4454 }
4455
4456 static statement_t *parse_compound_statement(void)
4457 {
4458         compound_statement_t *compound_statement
4459                 = allocate_ast_zero(sizeof(compound_statement[0]));
4460         compound_statement->statement.type            = STATEMENT_COMPOUND;
4461         compound_statement->statement.source_position = token.source_position;
4462
4463         eat('{');
4464
4465         int        top          = environment_top();
4466         context_t *last_context = context;
4467         set_context(&compound_statement->context);
4468
4469         statement_t *last_statement = NULL;
4470
4471         while(token.type != '}' && token.type != T_EOF) {
4472                 statement_t *statement = parse_statement();
4473                 if(statement == NULL)
4474                         continue;
4475
4476                 if(last_statement != NULL) {
4477                         last_statement->next = statement;
4478                 } else {
4479                         compound_statement->statements = statement;
4480                 }
4481
4482                 while(statement->next != NULL)
4483                         statement = statement->next;
4484
4485                 last_statement = statement;
4486         }
4487
4488         if(token.type != '}') {
4489                 parser_print_error_prefix_pos(
4490                                 compound_statement->statement.source_position);
4491                 fprintf(stderr, "end of file while looking for closing '}'\n");
4492         }
4493         next_token();
4494
4495         assert(context == &compound_statement->context);
4496         set_context(last_context);
4497         environment_pop_to(top);
4498
4499         return (statement_t*) compound_statement;
4500 }
4501
4502 static translation_unit_t *parse_translation_unit(void)
4503 {
4504         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4505
4506         assert(global_context == NULL);
4507         global_context = &unit->context;
4508
4509         assert(context == NULL);
4510         set_context(&unit->context);
4511
4512         while(token.type != T_EOF) {
4513                 parse_declaration();
4514         }
4515
4516         assert(context == &unit->context);
4517         context          = NULL;
4518         last_declaration = NULL;
4519
4520         assert(global_context == &unit->context);
4521         global_context = NULL;
4522
4523         return unit;
4524 }
4525
4526 translation_unit_t *parse(void)
4527 {
4528         environment_stack = NEW_ARR_F(stack_entry_t, 0);
4529         label_stack       = NEW_ARR_F(stack_entry_t, 0);
4530         found_error       = false;
4531
4532         type_set_output(stderr);
4533         ast_set_output(stderr);
4534
4535         lookahead_bufpos = 0;
4536         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
4537                 next_token();
4538         }
4539         translation_unit_t *unit = parse_translation_unit();
4540
4541         DEL_ARR_F(environment_stack);
4542         DEL_ARR_F(label_stack);
4543
4544         if(found_error)
4545                 return NULL;
4546
4547         return unit;
4548 }
4549
4550 void init_parser(void)
4551 {
4552         init_expression_parsers();
4553         obstack_init(&temp_obst);
4554
4555         type_int         = make_atomic_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
4556         type_uint        = make_atomic_type(ATOMIC_TYPE_UINT, TYPE_QUALIFIER_NONE);
4557         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE, TYPE_QUALIFIER_NONE);
4558         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE, TYPE_QUALIFIER_NONE);
4559         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, TYPE_QUALIFIER_NONE);
4560         type_size_t      = make_atomic_type(ATOMIC_TYPE_ULONG, TYPE_QUALIFIER_NONE);
4561         type_ptrdiff_t   = make_atomic_type(ATOMIC_TYPE_LONG, TYPE_QUALIFIER_NONE);
4562         type_char        = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_NONE);
4563         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4564         type_void_ptr    = make_pointer_type(type_void, TYPE_QUALIFIER_NONE);
4565         type_string      = make_pointer_type(type_char, TYPE_QUALIFIER_NONE);
4566 }
4567
4568 void exit_parser(void)
4569 {
4570         obstack_free(&temp_obst, NULL);
4571 }