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