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