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