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