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