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