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