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