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