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