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