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