introduce type_qualifiers_t type and remove a lot of warnings
[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 type_qualifiers_t parse_type_qualifiers(void)
1735 {
1736         type_qualifiers_t 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_qualifiers_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_qualifiers_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_qualifiers_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
2589         /* find last statement and use it's type */
2590         const statement_t *last_statement = NULL;
2591         const statement_t *iter           = statement->v.compound_stmt.statements;
2592         for( ; iter != NULL; iter = iter->next) {
2593                 last_statement = iter;
2594         }
2595
2596         if(last_statement->type == STATEMENT_EXPRESSION) {
2597                 expression->expression.datatype
2598                         = last_statement->v.expression->datatype;
2599         } else {
2600                 expression->expression.datatype = type_void;
2601         }
2602
2603         expect(')');
2604
2605         return (expression_t*) expression;
2606 }
2607
2608 static expression_t *parse_brace_expression(void)
2609 {
2610         eat('(');
2611
2612         switch(token.type) {
2613         case '{':
2614                 /* gcc extension: a stement expression */
2615                 return parse_statement_expression();
2616
2617         TYPE_QUALIFIERS
2618         TYPE_SPECIFIERS
2619                 return parse_cast();
2620         case T_IDENTIFIER:
2621                 if(is_typedef_symbol(token.v.symbol)) {
2622                         return parse_cast();
2623                 }
2624         }
2625
2626         expression_t *result = parse_expression();
2627         expect(')');
2628
2629         return result;
2630 }
2631
2632 static expression_t *parse_function_keyword(void)
2633 {
2634         next_token();
2635         /* TODO */
2636
2637         if (current_function == NULL) {
2638                 parse_error("'__func__' used outside of a function");
2639         }
2640
2641         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
2642         expression->expression.type     = EXPR_FUNCTION;
2643         expression->expression.datatype = type_string;
2644         expression->value               = "TODO: FUNCTION";
2645
2646         return (expression_t*) expression;
2647 }
2648
2649 static expression_t *parse_pretty_function_keyword(void)
2650 {
2651         eat(T___PRETTY_FUNCTION__);
2652         /* TODO */
2653
2654         string_literal_t *expression = allocate_ast_zero(sizeof(expression[0]));
2655         expression->expression.type     = EXPR_PRETTY_FUNCTION;
2656         expression->expression.datatype = type_string;
2657         expression->value               = "TODO: PRETTY FUNCTION";
2658
2659         return (expression_t*) expression;
2660 }
2661
2662 static designator_t *parse_designator(void)
2663 {
2664         designator_t *result = allocate_ast_zero(sizeof(result[0]));
2665
2666         if(token.type != T_IDENTIFIER) {
2667                 parse_error_expected("while parsing member designator",
2668                                      T_IDENTIFIER, 0);
2669                 eat_brace();
2670                 return NULL;
2671         }
2672         result->symbol = token.v.symbol;
2673         next_token();
2674
2675         designator_t *last_designator = result;
2676         while(true) {
2677                 if(token.type == '.') {
2678                         next_token();
2679                         if(token.type != T_IDENTIFIER) {
2680                                 parse_error_expected("while parsing member designator",
2681                                                      T_IDENTIFIER, 0);
2682                                 eat_brace();
2683                                 return NULL;
2684                         }
2685                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2686                         designator->symbol       = token.v.symbol;
2687                         next_token();
2688
2689                         last_designator->next = designator;
2690                         last_designator       = designator;
2691                         continue;
2692                 }
2693                 if(token.type == '[') {
2694                         next_token();
2695                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
2696                         designator->array_access = parse_expression();
2697                         if(designator->array_access == NULL) {
2698                                 eat_brace();
2699                                 return NULL;
2700                         }
2701                         expect(']');
2702
2703                         last_designator->next = designator;
2704                         last_designator       = designator;
2705                         continue;
2706                 }
2707                 break;
2708         }
2709
2710         return result;
2711 }
2712
2713 static expression_t *parse_offsetof(void)
2714 {
2715         eat(T___builtin_offsetof);
2716
2717         offsetof_expression_t *expression
2718                 = allocate_ast_zero(sizeof(expression[0]));
2719         expression->expression.type     = EXPR_OFFSETOF;
2720         expression->expression.datatype = type_size_t;
2721
2722         expect('(');
2723         expression->type = parse_typename();
2724         expect(',');
2725         expression->designator = parse_designator();
2726         expect(')');
2727
2728         return (expression_t*) expression;
2729 }
2730
2731 static expression_t *parse_va_arg(void)
2732 {
2733         eat(T___builtin_va_arg);
2734
2735         va_arg_expression_t *expression = allocate_ast_zero(sizeof(expression[0]));
2736         expression->expression.type     = EXPR_VA_ARG;
2737
2738         expect('(');
2739         expression->arg = parse_assignment_expression();
2740         expect(',');
2741         expression->expression.datatype = parse_typename();
2742         expect(')');
2743
2744         return (expression_t*) expression;
2745 }
2746
2747 static type_t *make_function_1_type(type_t *result_type, type_t *argument_type)
2748 {
2749         function_parameter_t *parameter = allocate_type_zero(sizeof(parameter[0]));
2750         parameter->type = argument_type;
2751
2752         function_type_t *type = allocate_type_zero(sizeof(type[0]));
2753         type->type.type   = TYPE_FUNCTION;
2754         type->result_type = result_type;
2755         type->parameters  = parameter;
2756
2757         type_t *result = typehash_insert((type_t*) type);
2758         if(result != (type_t*) type) {
2759                 free_type(type);
2760         }
2761
2762         return result;
2763 }
2764
2765 static expression_t *parse_builtin_symbol(void)
2766 {
2767         builtin_symbol_expression_t *expression
2768                 = allocate_ast_zero(sizeof(expression[0]));
2769         expression->expression.type = EXPR_BUILTIN_SYMBOL;
2770
2771         expression->symbol = token.v.symbol;
2772
2773         type_t *type;
2774         switch(token.type) {
2775         case T___builtin_alloca:
2776                 type = make_function_1_type(type_void_ptr, type_size_t);
2777                 break;
2778         }
2779
2780         next_token();
2781
2782         expression->expression.datatype = type;
2783         return (expression_t*) expression;
2784 }
2785
2786 static expression_t *parse_primary_expression(void)
2787 {
2788         switch(token.type) {
2789         case T_INTEGER:
2790                 return parse_int_const();
2791         case T_FLOATINGPOINT:
2792                 return parse_float_const();
2793         case T_STRING_LITERAL:
2794                 return parse_string_const();
2795         case T_IDENTIFIER:
2796                 return parse_reference();
2797         case T___FUNCTION__:
2798         case T___func__:
2799                 return parse_function_keyword();
2800         case T___PRETTY_FUNCTION__:
2801                 return parse_pretty_function_keyword();
2802         case T___builtin_offsetof:
2803                 return parse_offsetof();
2804         case T___builtin_va_arg:
2805                 return parse_va_arg();
2806         case T___builtin_alloca:
2807         case T___builtin_expect:
2808         case T___builtin_va_start:
2809         case T___builtin_va_end:
2810                 return parse_builtin_symbol();
2811
2812         case '(':
2813                 return parse_brace_expression();
2814         }
2815
2816         parser_print_error_prefix();
2817         fprintf(stderr, "unexpected token ");
2818         print_token(stderr, &token);
2819         fprintf(stderr, "\n");
2820         eat_statement();
2821
2822         return make_invalid_expression();
2823 }
2824
2825 static expression_t *parse_array_expression(unsigned precedence,
2826                                             expression_t *array_ref)
2827 {
2828         (void) precedence;
2829
2830         eat('[');
2831
2832         expression_t *index = parse_expression();
2833
2834         array_access_expression_t *array_access
2835                 = allocate_ast_zero(sizeof(array_access[0]));
2836
2837         array_access->expression.type = EXPR_ARRAY_ACCESS;
2838         array_access->array_ref       = array_ref;
2839         array_access->index           = index;
2840
2841         type_t *type_left  = skip_typeref(array_ref->datatype);
2842         type_t *type_right = skip_typeref(index->datatype);
2843
2844         if(type_left != NULL && type_right != NULL) {
2845                 if(type_left->type == TYPE_POINTER) {
2846                         pointer_type_t *pointer           = (pointer_type_t*) type_left;
2847                         array_access->expression.datatype = pointer->points_to;
2848                 } else if(type_left->type == TYPE_ARRAY) {
2849                         array_type_t *array_type          = (array_type_t*) type_left;
2850                         array_access->expression.datatype = array_type->element_type;
2851                 } else if(type_right->type == TYPE_POINTER) {
2852                         pointer_type_t *pointer           = (pointer_type_t*) type_right;
2853                         array_access->expression.datatype = pointer->points_to;
2854                 } else if(type_right->type == TYPE_ARRAY) {
2855                         array_type_t *array_type          = (array_type_t*) type_right;
2856                         array_access->expression.datatype = array_type->element_type;
2857                 } else {
2858                         parser_print_error_prefix();
2859                         fprintf(stderr, "array access on object with non-pointer types ");
2860                         print_type_quoted(type_left);
2861                         fprintf(stderr, ", ");
2862                         print_type_quoted(type_right);
2863                         fprintf(stderr, "\n");
2864                 }
2865         }
2866
2867         if(token.type != ']') {
2868                 parse_error_expected("Problem while parsing array access", ']', 0);
2869                 return (expression_t*) array_access;
2870         }
2871         next_token();
2872
2873         return (expression_t*) array_access;
2874 }
2875
2876 static bool is_declaration_specifier(const token_t *token,
2877                                      bool only_type_specifiers)
2878 {
2879         switch(token->type) {
2880                 TYPE_SPECIFIERS
2881                         return 1;
2882                 case T_IDENTIFIER:
2883                         return is_typedef_symbol(token->v.symbol);
2884                 STORAGE_CLASSES
2885                 TYPE_QUALIFIERS
2886                         if(only_type_specifiers)
2887                                 return 0;
2888                         return 1;
2889
2890                 default:
2891                         return 0;
2892         }
2893 }
2894
2895 static expression_t *parse_sizeof(unsigned precedence)
2896 {
2897         eat(T_sizeof);
2898
2899         sizeof_expression_t *sizeof_expression
2900                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
2901         sizeof_expression->expression.type     = EXPR_SIZEOF;
2902         sizeof_expression->expression.datatype = type_size_t;
2903
2904         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
2905                 next_token();
2906                 sizeof_expression->type = parse_typename();
2907                 expect(')');
2908         } else {
2909                 expression_t *expression           = parse_sub_expression(precedence);
2910                 sizeof_expression->type            = expression->datatype;
2911                 sizeof_expression->size_expression = expression;
2912         }
2913
2914         return (expression_t*) sizeof_expression;
2915 }
2916
2917 static expression_t *parse_select_expression(unsigned precedence,
2918                                              expression_t *compound)
2919 {
2920         (void) precedence;
2921         assert(token.type == '.' || token.type == T_MINUSGREATER);
2922
2923         bool is_pointer = (token.type == T_MINUSGREATER);
2924         next_token();
2925
2926         select_expression_t *select = allocate_ast_zero(sizeof(select[0]));
2927
2928         select->expression.type = EXPR_SELECT;
2929         select->compound        = compound;
2930
2931         if(token.type != T_IDENTIFIER) {
2932                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
2933                 return (expression_t*) select;
2934         }
2935         symbol_t *symbol = token.v.symbol;
2936         select->symbol   = symbol;
2937         next_token();
2938
2939         type_t *orig_type = compound->datatype;
2940         if(orig_type == NULL)
2941                 return make_invalid_expression();
2942
2943         type_t *type = skip_typeref(orig_type);
2944
2945         type_t *type_left = type;
2946         if(is_pointer) {
2947                 if(type->type != TYPE_POINTER) {
2948                         parser_print_error_prefix();
2949                         fprintf(stderr, "left hand side of '->' is not a pointer, but ");
2950                         print_type_quoted(orig_type);
2951                         fputc('\n', stderr);
2952                         return make_invalid_expression();
2953                 }
2954                 pointer_type_t *pointer_type = (pointer_type_t*) type;
2955                 type_left                    = pointer_type->points_to;
2956         }
2957         type_left = skip_typeref(type_left);
2958
2959         if(type_left->type != TYPE_COMPOUND_STRUCT
2960                         && type_left->type != TYPE_COMPOUND_UNION) {
2961                 parser_print_error_prefix();
2962                 fprintf(stderr, "request for member '%s' in something not a struct or "
2963                         "union, but ", symbol->string);
2964                 print_type_quoted(type_left);
2965                 fputc('\n', stderr);
2966                 return make_invalid_expression();
2967         }
2968
2969         compound_type_t *compound_type = (compound_type_t*) type_left;
2970         declaration_t   *declaration   = compound_type->declaration;
2971
2972         if(!declaration->init.is_defined) {
2973                 parser_print_error_prefix();
2974                 fprintf(stderr, "request for member '%s' of incomplete type ",
2975                         symbol->string);
2976                 print_type_quoted(type_left);
2977                 fputc('\n', stderr);
2978                 return make_invalid_expression();
2979         }
2980
2981         declaration_t *iter = declaration->context.declarations;
2982         for( ; iter != NULL; iter = iter->next) {
2983                 if(iter->symbol == symbol) {
2984                         break;
2985                 }
2986         }
2987         if(iter == NULL) {
2988                 parser_print_error_prefix();
2989                 print_type_quoted(type_left);
2990                 fprintf(stderr, " has no member named '%s'\n", symbol->string);
2991                 return make_invalid_expression();
2992         }
2993
2994         select->compound_entry      = iter;
2995         select->expression.datatype = iter->type;
2996         return (expression_t*) select;
2997 }
2998
2999 static expression_t *parse_call_expression(unsigned precedence,
3000                                            expression_t *expression)
3001 {
3002         (void) precedence;
3003         call_expression_t *call = allocate_ast_zero(sizeof(call[0]));
3004         call->expression.type   = EXPR_CALL;
3005         call->function          = expression;
3006
3007         function_type_t *function_type;
3008         type_t          *orig_type     = expression->datatype;
3009         type_t          *type          = skip_typeref(orig_type);
3010
3011         if(type->type == TYPE_POINTER) {
3012                 pointer_type_t *pointer_type = (pointer_type_t*) type;
3013
3014                 type = skip_typeref(pointer_type->points_to);
3015         }
3016         if (type->type == TYPE_FUNCTION) {
3017                 function_type             = (function_type_t*) type;
3018                 call->expression.datatype = function_type->result_type;
3019         } else {
3020                 parser_print_error_prefix();
3021                 fputs("called object '", stderr);
3022                 print_expression(expression);
3023                 fputs("' (type ", stderr);
3024                 print_type_quoted(orig_type);
3025                 fputs(") is not a function\n", stderr);
3026
3027                 function_type             = NULL;
3028                 call->expression.datatype = NULL;
3029         }
3030
3031         /* parse arguments */
3032         eat('(');
3033
3034         if(token.type != ')') {
3035                 call_argument_t *last_argument = NULL;
3036
3037                 while(true) {
3038                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3039
3040                         argument->expression = parse_assignment_expression();
3041                         if(last_argument == NULL) {
3042                                 call->arguments = argument;
3043                         } else {
3044                                 last_argument->next = argument;
3045                         }
3046                         last_argument = argument;
3047
3048                         if(token.type != ',')
3049                                 break;
3050                         next_token();
3051                 }
3052         }
3053         expect(')');
3054
3055         if(function_type != NULL) {
3056                 function_parameter_t *parameter = function_type->parameters;
3057                 call_argument_t      *argument  = call->arguments;
3058                 for( ; parameter != NULL && argument != NULL;
3059                                 parameter = parameter->next, argument = argument->next) {
3060                         type_t *expected_type = parameter->type;
3061                         /* TODO report context in error messages */
3062                         argument->expression = create_implicit_cast(argument->expression,
3063                                                                     expected_type);
3064                 }
3065                 /* too few parameters */
3066                 if(parameter != NULL) {
3067                         parser_print_error_prefix();
3068                         fprintf(stderr, "too few arguments to function '");
3069                         print_expression(expression);
3070                         fprintf(stderr, "'\n");
3071                 } else if(argument != NULL) {
3072                         /* too many parameters */
3073                         if(!function_type->variadic
3074                                         && !function_type->unspecified_parameters) {
3075                                 parser_print_error_prefix();
3076                                 fprintf(stderr, "too many arguments to function '");
3077                                 print_expression(expression);
3078                                 fprintf(stderr, "'\n");
3079                         } else {
3080                                 /* do default promotion */
3081                                 for( ; argument != NULL; argument = argument->next) {
3082                                         type_t *type = argument->expression->datatype;
3083
3084                                         if(type == NULL)
3085                                                 continue;
3086
3087                                         if(is_type_integer(type)) {
3088                                                 type = promote_integer(type);
3089                                         } else if(type == type_float) {
3090                                                 type = type_double;
3091                                         }
3092                                         argument->expression
3093                                                 = create_implicit_cast(argument->expression, type);
3094                                 }
3095                         }
3096                 }
3097         }
3098
3099         return (expression_t*) call;
3100 }
3101
3102 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3103
3104 static expression_t *parse_conditional_expression(unsigned precedence,
3105                                                   expression_t *expression)
3106 {
3107         eat('?');
3108
3109         conditional_expression_t *conditional
3110                 = allocate_ast_zero(sizeof(conditional[0]));
3111         conditional->expression.type = EXPR_CONDITIONAL;
3112         conditional->condition       = expression;
3113
3114         /* 6.5.15.2 */
3115         type_t *condition_type_orig = conditional->condition->datatype;
3116         if(condition_type_orig != NULL) {
3117                 type_t *condition_type      = skip_typeref(condition_type_orig);
3118                 if(condition_type != NULL && !is_type_scalar(condition_type)) {
3119                         type_error("expected a scalar type", expression->source_position,
3120                                            condition_type_orig);
3121                 }
3122         }
3123
3124         expression_t *const t_expr = parse_expression();
3125         conditional->true_expression = t_expr;
3126         expect(':');
3127         expression_t *const f_expr = parse_sub_expression(precedence);
3128         conditional->false_expression = f_expr;
3129
3130         type_t *const true_type  = t_expr->datatype;
3131         if(true_type == NULL)
3132                 return (expression_t*) conditional;
3133         type_t *const false_type = f_expr->datatype;
3134         if(false_type == NULL)
3135                 return (expression_t*) conditional;
3136
3137         type_t *const skipped_true_type  = skip_typeref(true_type);
3138         type_t *const skipped_false_type = skip_typeref(false_type);
3139
3140         /* 6.5.15.3 */
3141         if (skipped_true_type == skipped_false_type) {
3142                 conditional->expression.datatype = skipped_true_type;
3143         } else if (is_type_arithmetic(skipped_true_type) &&
3144                    is_type_arithmetic(skipped_false_type)) {
3145                 type_t *const result = semantic_arithmetic(skipped_true_type,
3146                                                            skipped_false_type);
3147                 conditional->true_expression  = create_implicit_cast(t_expr, result);
3148                 conditional->false_expression = create_implicit_cast(f_expr, result);
3149                 conditional->expression.datatype = result;
3150         } else if (skipped_true_type->type == TYPE_POINTER &&
3151                    skipped_false_type->type == TYPE_POINTER &&
3152                           true /* TODO compatible points_to types */) {
3153                 /* TODO */
3154         } else if(/* (is_null_ptr_const(skipped_true_type) &&
3155                       skipped_false_type->type == TYPE_POINTER)
3156                || (is_null_ptr_const(skipped_false_type) &&
3157                    skipped_true_type->type == TYPE_POINTER) TODO*/ false) {
3158                 /* TODO */
3159         } else if(/* 1 is pointer to object type, other is void* */ false) {
3160                 /* TODO */
3161         } else {
3162                 type_error_incompatible("while parsing conditional",
3163                                         expression->source_position, true_type,
3164                                         skipped_false_type);
3165         }
3166
3167         return (expression_t*) conditional;
3168 }
3169
3170 static expression_t *parse_extension(unsigned precedence)
3171 {
3172         eat(T___extension__);
3173
3174         /* TODO enable extensions */
3175
3176         return parse_sub_expression(precedence);
3177 }
3178
3179 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3180 {
3181         eat(T___builtin_classify_type);
3182
3183         classify_type_expression_t *const classify_type_expr =
3184                 allocate_ast_zero(sizeof(classify_type_expr[0]));
3185         classify_type_expr->expression.type     = EXPR_CLASSIFY_TYPE;
3186         classify_type_expr->expression.datatype = type_int;
3187
3188         expect('(');
3189         expression_t *const expression = parse_sub_expression(precedence);
3190         expect(')');
3191         classify_type_expr->type_expression = expression;
3192
3193         return (expression_t*)classify_type_expr;
3194 }
3195
3196 static void semantic_incdec(unary_expression_t *expression)
3197 {
3198         type_t *orig_type = expression->value->datatype;
3199         if(orig_type == NULL)
3200                 return;
3201
3202         type_t *type = skip_typeref(orig_type);
3203         if(!is_type_arithmetic(type) && type->type != TYPE_POINTER) {
3204                 /* TODO: improve error message */
3205                 parser_print_error_prefix();
3206                 fprintf(stderr, "operation needs an arithmetic or pointer type\n");
3207                 return;
3208         }
3209
3210         expression->expression.datatype = orig_type;
3211 }
3212
3213 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3214 {
3215         type_t *orig_type = expression->value->datatype;
3216         if(orig_type == NULL)
3217                 return;
3218
3219         type_t *type = skip_typeref(orig_type);
3220         if(!is_type_arithmetic(type)) {
3221                 /* TODO: improve error message */
3222                 parser_print_error_prefix();
3223                 fprintf(stderr, "operation needs an arithmetic type\n");
3224                 return;
3225         }
3226
3227         expression->expression.datatype = orig_type;
3228 }
3229
3230 static void semantic_unexpr_scalar(unary_expression_t *expression)
3231 {
3232         type_t *orig_type = expression->value->datatype;
3233         if(orig_type == NULL)
3234                 return;
3235
3236         type_t *type = skip_typeref(orig_type);
3237         if (!is_type_scalar(type)) {
3238                 parse_error("operand of ! must be of scalar type\n");
3239                 return;
3240         }
3241
3242         expression->expression.datatype = orig_type;
3243 }
3244
3245 static void semantic_unexpr_integer(unary_expression_t *expression)
3246 {
3247         type_t *orig_type = expression->value->datatype;
3248         if(orig_type == NULL)
3249                 return;
3250
3251         type_t *type = skip_typeref(orig_type);
3252         if (!is_type_integer(type)) {
3253                 parse_error("operand of ~ must be of integer type\n");
3254                 return;
3255         }
3256
3257         expression->expression.datatype = orig_type;
3258 }
3259
3260 static void semantic_dereference(unary_expression_t *expression)
3261 {
3262         type_t *orig_type = expression->value->datatype;
3263         if(orig_type == NULL)
3264                 return;
3265
3266         type_t *type = skip_typeref(orig_type);
3267         switch (type->type) {
3268                 case TYPE_ARRAY: {
3269                         array_type_t *const array_type  = (array_type_t*)type;
3270                         expression->expression.datatype = array_type->element_type;
3271                         break;
3272                 }
3273
3274                 case TYPE_POINTER: {
3275                         pointer_type_t *pointer_type    = (pointer_type_t*)type;
3276                         expression->expression.datatype = pointer_type->points_to;
3277                         break;
3278                 }
3279
3280                 default:
3281                         parser_print_error_prefix();
3282                         fputs("'Unary *' needs pointer or arrray type, but type ", stderr);
3283                         print_type_quoted(orig_type);
3284                         fputs(" given.\n", stderr);
3285                         return;
3286         }
3287 }
3288
3289 static void semantic_take_addr(unary_expression_t *expression)
3290 {
3291         type_t *orig_type = expression->value->datatype;
3292         if(orig_type == NULL)
3293                 return;
3294
3295         expression_t *value = expression->value;
3296         if(value->type == EXPR_REFERENCE) {
3297                 reference_expression_t *reference   = (reference_expression_t*) value;
3298                 declaration_t          *declaration = reference->declaration;
3299                 if(declaration != NULL) {
3300                         declaration->address_taken = 1;
3301                 }
3302         }
3303
3304         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3305 }
3306
3307 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
3308 static expression_t *parse_##unexpression_type(unsigned precedence)            \
3309 {                                                                              \
3310         eat(token_type);                                                           \
3311                                                                                \
3312         unary_expression_t *unary_expression                                       \
3313                 = allocate_ast_zero(sizeof(unary_expression[0]));                      \
3314         unary_expression->expression.type     = EXPR_UNARY;                        \
3315         unary_expression->type                = unexpression_type;                 \
3316         unary_expression->value               = parse_sub_expression(precedence);  \
3317                                                                                    \
3318         sfunc(unary_expression);                                                   \
3319                                                                                \
3320         return (expression_t*) unary_expression;                                   \
3321 }
3322
3323 CREATE_UNARY_EXPRESSION_PARSER('-', UNEXPR_NEGATE, semantic_unexpr_arithmetic)
3324 CREATE_UNARY_EXPRESSION_PARSER('+', UNEXPR_PLUS,   semantic_unexpr_arithmetic)
3325 CREATE_UNARY_EXPRESSION_PARSER('!', UNEXPR_NOT,    semantic_unexpr_scalar)
3326 CREATE_UNARY_EXPRESSION_PARSER('*', UNEXPR_DEREFERENCE, semantic_dereference)
3327 CREATE_UNARY_EXPRESSION_PARSER('&', UNEXPR_TAKE_ADDRESS, semantic_take_addr)
3328 CREATE_UNARY_EXPRESSION_PARSER('~', UNEXPR_BITWISE_NEGATE,
3329                                semantic_unexpr_integer)
3330 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_PREFIX_INCREMENT,
3331                                semantic_incdec)
3332 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_PREFIX_DECREMENT,
3333                                semantic_incdec)
3334
3335 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
3336                                                sfunc)                         \
3337 static expression_t *parse_##unexpression_type(unsigned precedence,           \
3338                                                expression_t *left)            \
3339 {                                                                             \
3340         (void) precedence;                                                        \
3341         eat(token_type);                                                          \
3342                                                                               \
3343         unary_expression_t *unary_expression                                      \
3344                 = allocate_ast_zero(sizeof(unary_expression[0]));                     \
3345         unary_expression->expression.type     = EXPR_UNARY;                       \
3346         unary_expression->type                = unexpression_type;                \
3347         unary_expression->value               = left;                             \
3348                                                                                   \
3349         sfunc(unary_expression);                                                  \
3350                                                                               \
3351         return (expression_t*) unary_expression;                                  \
3352 }
3353
3354 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,   UNEXPR_POSTFIX_INCREMENT,
3355                                        semantic_incdec)
3356 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS, UNEXPR_POSTFIX_DECREMENT,
3357                                        semantic_incdec)
3358
3359 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
3360 {
3361         /* TODO: handle complex + imaginary types */
3362
3363         /* Â§ 6.3.1.8 Usual arithmetic conversions */
3364         if(type_left == type_long_double || type_right == type_long_double) {
3365                 return type_long_double;
3366         } else if(type_left == type_double || type_right == type_double) {
3367                 return type_double;
3368         } else if(type_left == type_float || type_right == type_float) {
3369                 return type_float;
3370         }
3371
3372         type_right = promote_integer(type_right);
3373         type_left  = promote_integer(type_left);
3374
3375         if(type_left == type_right)
3376                 return type_left;
3377
3378         bool signed_left  = is_type_signed(type_left);
3379         bool signed_right = is_type_signed(type_right);
3380         if(get_rank(type_left) < get_rank(type_right)) {
3381                 if(signed_left == signed_right || !signed_right) {
3382                         return type_right;
3383                 } else {
3384                         return type_left;
3385                 }
3386         } else {
3387                 if(signed_left == signed_right || !signed_left) {
3388                         return type_left;
3389                 } else {
3390                         return type_right;
3391                 }
3392         }
3393 }
3394
3395 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
3396 {
3397         expression_t *left       = expression->left;
3398         expression_t *right      = expression->right;
3399         type_t       *orig_type_left  = left->datatype;
3400         type_t       *orig_type_right = right->datatype;
3401
3402         if(orig_type_left == NULL || orig_type_right == NULL)
3403                 return;
3404
3405         type_t *type_left  = skip_typeref(orig_type_left);
3406         type_t *type_right = skip_typeref(orig_type_right);
3407
3408         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3409                 /* TODO: improve error message */
3410                 parser_print_error_prefix();
3411                 fprintf(stderr, "operation needs arithmetic types\n");
3412                 return;
3413         }
3414
3415         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3416         expression->left  = create_implicit_cast(left, arithmetic_type);
3417         expression->right = create_implicit_cast(right, arithmetic_type);
3418         expression->expression.datatype = arithmetic_type;
3419 }
3420
3421 static void semantic_shift_op(binary_expression_t *expression)
3422 {
3423         expression_t *left       = expression->left;
3424         expression_t *right      = expression->right;
3425         type_t       *orig_type_left  = left->datatype;
3426         type_t       *orig_type_right = right->datatype;
3427
3428         if(orig_type_left == NULL || orig_type_right == NULL)
3429                 return;
3430
3431         type_t *type_left  = skip_typeref(orig_type_left);
3432         type_t *type_right = skip_typeref(orig_type_right);
3433
3434         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
3435                 /* TODO: improve error message */
3436                 parser_print_error_prefix();
3437                 fprintf(stderr, "operation needs integer types\n");
3438                 return;
3439         }
3440
3441         type_left  = promote_integer(type_left);
3442         type_right = promote_integer(type_right);
3443
3444         expression->left  = create_implicit_cast(left, type_left);
3445         expression->right = create_implicit_cast(right, type_right);
3446         expression->expression.datatype = type_left;
3447 }
3448
3449 static void semantic_add(binary_expression_t *expression)
3450 {
3451         expression_t *left            = expression->left;
3452         expression_t *right           = expression->right;
3453         type_t       *orig_type_left  = left->datatype;
3454         type_t       *orig_type_right = right->datatype;
3455
3456         if(orig_type_left == NULL || orig_type_right == NULL)
3457                 return;
3458
3459         type_t *type_left  = skip_typeref(orig_type_left);
3460         type_t *type_right = skip_typeref(orig_type_right);
3461
3462         /* Â§ 5.6.5 */
3463         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3464                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3465                 expression->left  = create_implicit_cast(left, arithmetic_type);
3466                 expression->right = create_implicit_cast(right, arithmetic_type);
3467                 expression->expression.datatype = arithmetic_type;
3468                 return;
3469         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3470                 expression->expression.datatype = type_left;
3471         } else if(type_right->type == TYPE_POINTER && is_type_integer(type_left)) {
3472                 expression->expression.datatype = type_right;
3473         } else if (type_left->type == TYPE_ARRAY && is_type_integer(type_right)) {
3474                 const array_type_t *const arr_type = (const array_type_t*)type_left;
3475                 expression->expression.datatype =
3476                   make_pointer_type(arr_type->element_type, TYPE_QUALIFIER_NONE);
3477         } else if (type_right->type == TYPE_ARRAY && is_type_integer(type_left)) {
3478                 const array_type_t *const arr_type = (const array_type_t*)type_right;
3479                 expression->expression.datatype =
3480                         make_pointer_type(arr_type->element_type, TYPE_QUALIFIER_NONE);
3481         } else {
3482                 parser_print_error_prefix();
3483                 fprintf(stderr, "invalid operands to binary + (");
3484                 print_type_quoted(orig_type_left);
3485                 fprintf(stderr, ", ");
3486                 print_type_quoted(orig_type_right);
3487                 fprintf(stderr, ")\n");
3488         }
3489 }
3490
3491 static void semantic_sub(binary_expression_t *expression)
3492 {
3493         expression_t *left            = expression->left;
3494         expression_t *right           = expression->right;
3495         type_t       *orig_type_left  = left->datatype;
3496         type_t       *orig_type_right = right->datatype;
3497
3498         if(orig_type_left == NULL || orig_type_right == NULL)
3499                 return;
3500
3501         type_t       *type_left       = skip_typeref(orig_type_left);
3502         type_t       *type_right      = skip_typeref(orig_type_right);
3503
3504         /* Â§ 5.6.5 */
3505         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3506                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3507                 expression->left  = create_implicit_cast(left, arithmetic_type);
3508                 expression->right = create_implicit_cast(right, arithmetic_type);
3509                 expression->expression.datatype = arithmetic_type;
3510                 return;
3511         } else if(type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3512                 expression->expression.datatype = type_left;
3513         } else if(type_left->type == TYPE_POINTER &&
3514                         type_right->type == TYPE_POINTER) {
3515                 if(!pointers_compatible(type_left, type_right)) {
3516                         parser_print_error_prefix();
3517                         fprintf(stderr, "pointers to incompatible objects to binary - (");
3518                         print_type_quoted(orig_type_left);
3519                         fprintf(stderr, ", ");
3520                         print_type_quoted(orig_type_right);
3521                         fprintf(stderr, ")\n");
3522                 } else {
3523                         expression->expression.datatype = type_ptrdiff_t;
3524                 }
3525         } else {
3526                 parser_print_error_prefix();
3527                 fprintf(stderr, "invalid operands to binary - (");
3528                 print_type_quoted(orig_type_left);
3529                 fprintf(stderr, ", ");
3530                 print_type_quoted(orig_type_right);
3531                 fprintf(stderr, ")\n");
3532         }
3533 }
3534
3535 static void semantic_comparison(binary_expression_t *expression)
3536 {
3537         expression_t *left            = expression->left;
3538         expression_t *right           = expression->right;
3539         type_t       *orig_type_left  = left->datatype;
3540         type_t       *orig_type_right = right->datatype;
3541
3542         if(orig_type_left == NULL || orig_type_right == NULL)
3543                 return;
3544
3545         type_t *type_left  = skip_typeref(orig_type_left);
3546         type_t *type_right = skip_typeref(orig_type_right);
3547
3548         /* TODO non-arithmetic types */
3549         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3550                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3551                 expression->left  = create_implicit_cast(left, arithmetic_type);
3552                 expression->right = create_implicit_cast(right, arithmetic_type);
3553                 expression->expression.datatype = arithmetic_type;
3554         } else if (type_left->type  == TYPE_POINTER &&
3555                    type_right->type == TYPE_POINTER) {
3556                 /* TODO check compatibility */
3557         } else if (type_left->type == TYPE_POINTER) {
3558                 expression->right = create_implicit_cast(right, type_left);
3559         } else if (type_right->type == TYPE_POINTER) {
3560                 expression->left = create_implicit_cast(left, type_right);
3561         } else {
3562                 type_error_incompatible("invalid operands in comparison",
3563                                         token.source_position, type_left, type_right);
3564         }
3565         expression->expression.datatype = type_int;
3566 }
3567
3568 static void semantic_arithmetic_assign(binary_expression_t *expression)
3569 {
3570         expression_t *left            = expression->left;
3571         expression_t *right           = expression->right;
3572         type_t       *orig_type_left  = left->datatype;
3573         type_t       *orig_type_right = right->datatype;
3574
3575         if(orig_type_left == NULL || orig_type_right == NULL)
3576                 return;
3577
3578         type_t *type_left  = skip_typeref(orig_type_left);
3579         type_t *type_right = skip_typeref(orig_type_right);
3580
3581         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
3582                 /* TODO: improve error message */
3583                 parser_print_error_prefix();
3584                 fprintf(stderr, "operation needs arithmetic types\n");
3585                 return;
3586         }
3587
3588         /* combined instructions are tricky. We can't create an implicit cast on
3589          * the left side, because we need the uncasted form for the store.
3590          * The ast2firm pass has to know that left_type must be right_type
3591          * for the arithmeitc operation and create a cast by itself */
3592         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
3593         expression->right       = create_implicit_cast(right, arithmetic_type);
3594         expression->expression.datatype = type_left;
3595 }
3596
3597 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
3598 {
3599         expression_t *left            = expression->left;
3600         expression_t *right           = expression->right;
3601         type_t       *orig_type_left  = left->datatype;
3602         type_t       *orig_type_right = right->datatype;
3603
3604         if(orig_type_left == NULL || orig_type_right == NULL)
3605                 return;
3606
3607         type_t *type_left  = skip_typeref(orig_type_left);
3608         type_t *type_right = skip_typeref(orig_type_right);
3609
3610         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
3611                 /* combined instructions are tricky. We can't create an implicit cast on
3612                  * the left side, because we need the uncasted form for the store.
3613                  * The ast2firm pass has to know that left_type must be right_type
3614                  * for the arithmeitc operation and create a cast by itself */
3615                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
3616                 expression->right = create_implicit_cast(right, arithmetic_type);
3617                 expression->expression.datatype = type_left;
3618         } else if (type_left->type == TYPE_POINTER && is_type_integer(type_right)) {
3619                 expression->expression.datatype = type_left;
3620         } else {
3621                 parser_print_error_prefix();
3622                 fputs("Incompatible types ", stderr);
3623                 print_type_quoted(orig_type_left);
3624                 fputs(" and ", stderr);
3625                 print_type_quoted(orig_type_right);
3626                 fputs(" in assignment\n", stderr);
3627                 return;
3628         }
3629 }
3630
3631 static void semantic_logical_op(binary_expression_t *expression)
3632 {
3633         expression_t *left            = expression->left;
3634         expression_t *right           = expression->right;
3635         type_t       *orig_type_left  = left->datatype;
3636         type_t       *orig_type_right = right->datatype;
3637
3638         if(orig_type_left == NULL || orig_type_right == NULL)
3639                 return;
3640
3641         type_t *type_left  = skip_typeref(orig_type_left);
3642         type_t *type_right = skip_typeref(orig_type_right);
3643
3644         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
3645                 /* TODO: improve error message */
3646                 parser_print_error_prefix();
3647                 fprintf(stderr, "operation needs scalar types\n");
3648                 return;
3649         }
3650
3651         expression->expression.datatype = type_int;
3652 }
3653
3654 static void semantic_binexpr_assign(binary_expression_t *expression)
3655 {
3656         expression_t *left           = expression->left;
3657         type_t       *orig_type_left = left->datatype;
3658
3659         if(orig_type_left == NULL)
3660                 return;
3661
3662         type_t *type_left = skip_typeref(orig_type_left);
3663
3664         if (type_left->type == TYPE_ARRAY) {
3665                 parse_error("Cannot assign to arrays.");
3666                 return;
3667         }
3668
3669         if(type_left->qualifiers & TYPE_QUALIFIER_CONST) {
3670                 parser_print_error_prefix();
3671                 fprintf(stderr, "assignment to readonly location '");
3672                 print_expression(left);
3673                 fprintf(stderr, "' (type ");
3674                 print_type_quoted(orig_type_left);
3675                 fprintf(stderr, ")\n");
3676         }
3677
3678         semantic_assign(orig_type_left, &expression->right, "assignment");
3679
3680         expression->expression.datatype = orig_type_left;
3681 }
3682
3683 static void semantic_comma(binary_expression_t *expression)
3684 {
3685         expression->expression.datatype = expression->right->datatype;
3686 }
3687
3688 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr) \
3689 static expression_t *parse_##binexpression_type(unsigned precedence,     \
3690                                                 expression_t *left)      \
3691 {                                                                        \
3692         eat(token_type);                                                     \
3693                                                                          \
3694         expression_t *right = parse_sub_expression(precedence + lr);         \
3695                                                                          \
3696         binary_expression_t *binexpr                                         \
3697                 = allocate_ast_zero(sizeof(binexpr[0]));                         \
3698         binexpr->expression.type     = EXPR_BINARY;                          \
3699         binexpr->type                = binexpression_type;                   \
3700         binexpr->left                = left;                                 \
3701         binexpr->right               = right;                                \
3702         sfunc(binexpr);                                                      \
3703                                                                          \
3704         return (expression_t*) binexpr;                                      \
3705 }
3706
3707 CREATE_BINEXPR_PARSER(',', BINEXPR_COMMA,          semantic_comma, 1)
3708 CREATE_BINEXPR_PARSER('*', BINEXPR_MUL,            semantic_binexpr_arithmetic, 1)
3709 CREATE_BINEXPR_PARSER('/', BINEXPR_DIV,            semantic_binexpr_arithmetic, 1)
3710 CREATE_BINEXPR_PARSER('%', BINEXPR_MOD,            semantic_binexpr_arithmetic, 1)
3711 CREATE_BINEXPR_PARSER('+', BINEXPR_ADD,            semantic_add, 1)
3712 CREATE_BINEXPR_PARSER('-', BINEXPR_SUB,            semantic_sub, 1)
3713 CREATE_BINEXPR_PARSER('<', BINEXPR_LESS,           semantic_comparison, 1)
3714 CREATE_BINEXPR_PARSER('>', BINEXPR_GREATER,        semantic_comparison, 1)
3715 CREATE_BINEXPR_PARSER('=', BINEXPR_ASSIGN,         semantic_binexpr_assign, 0)
3716 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, BINEXPR_EQUAL, semantic_comparison, 1)
3717 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, BINEXPR_NOTEQUAL,
3718                       semantic_comparison, 1)
3719 CREATE_BINEXPR_PARSER(T_LESSEQUAL, BINEXPR_LESSEQUAL, semantic_comparison, 1)
3720 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, BINEXPR_GREATEREQUAL,
3721                       semantic_comparison, 1)
3722 CREATE_BINEXPR_PARSER('&', BINEXPR_BITWISE_AND,    semantic_binexpr_arithmetic, 1)
3723 CREATE_BINEXPR_PARSER('|', BINEXPR_BITWISE_OR,     semantic_binexpr_arithmetic, 1)
3724 CREATE_BINEXPR_PARSER('^', BINEXPR_BITWISE_XOR,    semantic_binexpr_arithmetic, 1)
3725 CREATE_BINEXPR_PARSER(T_ANDAND, BINEXPR_LOGICAL_AND,  semantic_logical_op, 1)
3726 CREATE_BINEXPR_PARSER(T_PIPEPIPE, BINEXPR_LOGICAL_OR, semantic_logical_op, 1)
3727 CREATE_BINEXPR_PARSER(T_LESSLESS, BINEXPR_SHIFTLEFT,
3728                       semantic_shift_op, 1)
3729 CREATE_BINEXPR_PARSER(T_GREATERGREATER, BINEXPR_SHIFTRIGHT,
3730                       semantic_shift_op, 1)
3731 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, BINEXPR_ADD_ASSIGN,
3732                       semantic_arithmetic_addsubb_assign, 0)
3733 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, BINEXPR_SUB_ASSIGN,
3734                       semantic_arithmetic_addsubb_assign, 0)
3735 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, BINEXPR_MUL_ASSIGN,
3736                       semantic_arithmetic_assign, 0)
3737 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, BINEXPR_DIV_ASSIGN,
3738                       semantic_arithmetic_assign, 0)
3739 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, BINEXPR_MOD_ASSIGN,
3740                       semantic_arithmetic_assign, 0)
3741 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, BINEXPR_SHIFTLEFT_ASSIGN,
3742                       semantic_arithmetic_assign, 0)
3743 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, BINEXPR_SHIFTRIGHT_ASSIGN,
3744                       semantic_arithmetic_assign, 0)
3745 CREATE_BINEXPR_PARSER(T_ANDEQUAL, BINEXPR_BITWISE_AND_ASSIGN,
3746                       semantic_arithmetic_assign, 0)
3747 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, BINEXPR_BITWISE_OR_ASSIGN,
3748                       semantic_arithmetic_assign, 0)
3749 CREATE_BINEXPR_PARSER(T_CARETEQUAL, BINEXPR_BITWISE_XOR_ASSIGN,
3750                       semantic_arithmetic_assign, 0)
3751
3752 static expression_t *parse_sub_expression(unsigned precedence)
3753 {
3754         if(token.type < 0) {
3755                 return expected_expression_error();
3756         }
3757
3758         expression_parser_function_t *parser
3759                 = &expression_parsers[token.type];
3760         source_position_t             source_position = token.source_position;
3761         expression_t                 *left;
3762
3763         if(parser->parser != NULL) {
3764                 left = parser->parser(parser->precedence);
3765         } else {
3766                 left = parse_primary_expression();
3767         }
3768         assert(left != NULL);
3769         left->source_position = source_position;
3770
3771         while(true) {
3772                 if(token.type < 0) {
3773                         return expected_expression_error();
3774                 }
3775
3776                 parser = &expression_parsers[token.type];
3777                 if(parser->infix_parser == NULL)
3778                         break;
3779                 if(parser->infix_precedence < precedence)
3780                         break;
3781
3782                 left = parser->infix_parser(parser->infix_precedence, left);
3783
3784                 assert(left != NULL);
3785                 assert(left->type != EXPR_UNKNOWN);
3786                 left->source_position = source_position;
3787         }
3788
3789         return left;
3790 }
3791
3792 static expression_t *parse_expression(void)
3793 {
3794         return parse_sub_expression(1);
3795 }
3796
3797
3798
3799 static void register_expression_parser(parse_expression_function parser,
3800                                        int token_type, unsigned precedence)
3801 {
3802         expression_parser_function_t *entry = &expression_parsers[token_type];
3803
3804         if(entry->parser != NULL) {
3805                 fprintf(stderr, "for token ");
3806                 print_token_type(stderr, token_type);
3807                 fprintf(stderr, "\n");
3808                 panic("trying to register multiple expression parsers for a token");
3809         }
3810         entry->parser     = parser;
3811         entry->precedence = precedence;
3812 }
3813
3814 static void register_expression_infix_parser(
3815                 parse_expression_infix_function parser, int token_type,
3816                 unsigned precedence)
3817 {
3818         expression_parser_function_t *entry = &expression_parsers[token_type];
3819
3820         if(entry->infix_parser != NULL) {
3821                 fprintf(stderr, "for token ");
3822                 print_token_type(stderr, token_type);
3823                 fprintf(stderr, "\n");
3824                 panic("trying to register multiple infix expression parsers for a "
3825                       "token");
3826         }
3827         entry->infix_parser     = parser;
3828         entry->infix_precedence = precedence;
3829 }
3830
3831 static void init_expression_parsers(void)
3832 {
3833         memset(&expression_parsers, 0, sizeof(expression_parsers));
3834
3835         register_expression_infix_parser(parse_BINEXPR_MUL,         '*',        16);
3836         register_expression_infix_parser(parse_BINEXPR_DIV,         '/',        16);
3837         register_expression_infix_parser(parse_BINEXPR_MOD,         '%',        16);
3838         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT,   T_LESSLESS, 16);
3839         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT,
3840                                                               T_GREATERGREATER, 16);
3841         register_expression_infix_parser(parse_BINEXPR_ADD,         '+',        15);
3842         register_expression_infix_parser(parse_BINEXPR_SUB,         '-',        15);
3843         register_expression_infix_parser(parse_BINEXPR_LESS,        '<',        14);
3844         register_expression_infix_parser(parse_BINEXPR_GREATER,     '>',        14);
3845         register_expression_infix_parser(parse_BINEXPR_LESSEQUAL, T_LESSEQUAL,  14);
3846         register_expression_infix_parser(parse_BINEXPR_GREATEREQUAL,
3847                                                                 T_GREATEREQUAL, 14);
3848         register_expression_infix_parser(parse_BINEXPR_EQUAL,     T_EQUALEQUAL, 13);
3849         register_expression_infix_parser(parse_BINEXPR_NOTEQUAL,
3850                                                         T_EXCLAMATIONMARKEQUAL, 13);
3851         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND, '&',        12);
3852         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR, '^',        11);
3853         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR,  '|',        10);
3854         register_expression_infix_parser(parse_BINEXPR_LOGICAL_AND, T_ANDAND,    9);
3855         register_expression_infix_parser(parse_BINEXPR_LOGICAL_OR,  T_PIPEPIPE,  8);
3856         register_expression_infix_parser(parse_conditional_expression, '?',      7);
3857         register_expression_infix_parser(parse_BINEXPR_ASSIGN,      '=',         2);
3858         register_expression_infix_parser(parse_BINEXPR_ADD_ASSIGN, T_PLUSEQUAL,  2);
3859         register_expression_infix_parser(parse_BINEXPR_SUB_ASSIGN, T_MINUSEQUAL, 2);
3860         register_expression_infix_parser(parse_BINEXPR_MUL_ASSIGN,
3861                                                                 T_ASTERISKEQUAL, 2);
3862         register_expression_infix_parser(parse_BINEXPR_DIV_ASSIGN, T_SLASHEQUAL, 2);
3863         register_expression_infix_parser(parse_BINEXPR_MOD_ASSIGN,
3864                                                                  T_PERCENTEQUAL, 2);
3865         register_expression_infix_parser(parse_BINEXPR_SHIFTLEFT_ASSIGN,
3866                                                                 T_LESSLESSEQUAL, 2);
3867         register_expression_infix_parser(parse_BINEXPR_SHIFTRIGHT_ASSIGN,
3868                                                           T_GREATERGREATEREQUAL, 2);
3869         register_expression_infix_parser(parse_BINEXPR_BITWISE_AND_ASSIGN,
3870                                                                      T_ANDEQUAL, 2);
3871         register_expression_infix_parser(parse_BINEXPR_BITWISE_OR_ASSIGN,
3872                                                                     T_PIPEEQUAL, 2);
3873         register_expression_infix_parser(parse_BINEXPR_BITWISE_XOR_ASSIGN,
3874                                                                    T_CARETEQUAL, 2);
3875
3876         register_expression_infix_parser(parse_BINEXPR_COMMA,       ',',         1);
3877
3878         register_expression_infix_parser(parse_array_expression,        '[',    30);
3879         register_expression_infix_parser(parse_call_expression,         '(',    30);
3880         register_expression_infix_parser(parse_select_expression,       '.',    30);
3881         register_expression_infix_parser(parse_select_expression,
3882                                                                 T_MINUSGREATER, 30);
3883         register_expression_infix_parser(parse_UNEXPR_POSTFIX_INCREMENT,
3884                                          T_PLUSPLUS, 30);
3885         register_expression_infix_parser(parse_UNEXPR_POSTFIX_DECREMENT,
3886                                          T_MINUSMINUS, 30);
3887
3888         register_expression_parser(parse_UNEXPR_NEGATE,           '-',          25);
3889         register_expression_parser(parse_UNEXPR_PLUS,             '+',          25);
3890         register_expression_parser(parse_UNEXPR_NOT,              '!',          25);
3891         register_expression_parser(parse_UNEXPR_BITWISE_NEGATE,   '~',          25);
3892         register_expression_parser(parse_UNEXPR_DEREFERENCE,      '*',          25);
3893         register_expression_parser(parse_UNEXPR_TAKE_ADDRESS,     '&',          25);
3894         register_expression_parser(parse_UNEXPR_PREFIX_INCREMENT, T_PLUSPLUS,   25);
3895         register_expression_parser(parse_UNEXPR_PREFIX_DECREMENT, T_MINUSMINUS, 25);
3896         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
3897         register_expression_parser(parse_extension,            T___extension__, 25);
3898         register_expression_parser(parse_builtin_classify_type,
3899                                                      T___builtin_classify_type, 25);
3900 }
3901
3902
3903 static statement_t *parse_case_statement(void)
3904 {
3905         eat(T_case);
3906         statement_t *label = allocate_ast_zero(sizeof(label[0]));
3907         label->type            = STATEMENT_CASE_LABEL;
3908         label->source_position = token.source_position;
3909
3910         label->v.case_label_stmt.expression = parse_expression();
3911
3912         expect(':');
3913         label->v.case_label_stmt.label_statement = parse_statement();
3914
3915         return label;
3916 }
3917
3918 static statement_t *parse_default_statement(void)
3919 {
3920         eat(T_default);
3921
3922         statement_t *label = allocate_ast_zero(sizeof(label[0]));
3923         label->type            = STATEMENT_CASE_LABEL;
3924         label->source_position = token.source_position;
3925
3926         expect(':');
3927         label->v.case_label_stmt.label_statement = parse_statement();
3928
3929         return (statement_t*) label;
3930 }
3931
3932 static declaration_t *get_label(symbol_t *symbol)
3933 {
3934         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
3935         assert(current_function != NULL);
3936         /* if we found a label in the same function, then we already created the
3937          * declaration */
3938         if(candidate != NULL
3939                         && candidate->parent_context == &current_function->context) {
3940                 return candidate;
3941         }
3942
3943         /* otherwise we need to create a new one */
3944         declaration_t *declaration = allocate_ast_zero(sizeof(declaration[0]));
3945         declaration->namespc     = NAMESPACE_LABEL;
3946         declaration->symbol        = symbol;
3947
3948         label_push(declaration);
3949
3950         return declaration;
3951 }
3952
3953 static statement_t *parse_label_statement(void)
3954 {
3955         assert(token.type == T_IDENTIFIER);
3956         symbol_t *symbol = token.v.symbol;
3957         next_token();
3958
3959         declaration_t *label = get_label(symbol);
3960
3961         /* if source position is already set then the label is defined twice,
3962          * otherwise it was just mentioned in a goto so far */
3963         if(label->source_position.input_name != NULL) {
3964                 parser_print_error_prefix();
3965                 fprintf(stderr, "duplicate label '%s'\n", symbol->string);
3966                 parser_print_error_prefix_pos(label->source_position);
3967                 fprintf(stderr, "previous definition of '%s' was here\n",
3968                         symbol->string);
3969         } else {
3970                 label->source_position = token.source_position;
3971         }
3972
3973         statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
3974
3975         label_statement->type               = STATEMENT_LABEL;
3976         label_statement->source_position    = token.source_position;
3977         label_statement->v.label_stmt.label = label;
3978
3979         expect(':');
3980
3981         if(token.type == '}') {
3982                 parse_error("label at end of compound statement");
3983                 return (statement_t*) label_statement;
3984         } else {
3985                 label_statement->v.label_stmt.label_statement = parse_statement();
3986         }
3987
3988         return label_statement;
3989 }
3990
3991 static statement_t *parse_if(void)
3992 {
3993         eat(T_if);
3994
3995         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
3996         statement->type            = STATEMENT_IF;
3997         statement->source_position = token.source_position;
3998
3999         expect('(');
4000         statement->v.if_stmt.condition = parse_expression();
4001         expect(')');
4002
4003         statement->v.if_stmt.true_statement = parse_statement();
4004         if(token.type == T_else) {
4005                 next_token();
4006                 statement->v.if_stmt.false_statement = parse_statement();
4007         }
4008
4009         return statement;
4010 }
4011
4012 static statement_t *parse_switch(void)
4013 {
4014         eat(T_switch);
4015
4016         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4017         statement->type            = STATEMENT_SWITCH;
4018         statement->source_position = token.source_position;
4019
4020         expect('(');
4021         statement->v.switch_stmt.expression = parse_expression();
4022         expect(')');
4023         statement->v.switch_stmt.body = parse_statement();
4024
4025         return statement;
4026 }
4027
4028 static statement_t *parse_while(void)
4029 {
4030         eat(T_while);
4031
4032         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4033         statement->type            = STATEMENT_WHILE;
4034         statement->source_position = token.source_position;
4035
4036         expect('(');
4037         statement->v.while_stmt.condition = parse_expression();
4038         expect(')');
4039         statement->v.while_stmt.body = parse_statement();
4040
4041         return statement;
4042 }
4043
4044 static statement_t *parse_do(void)
4045 {
4046         eat(T_do);
4047
4048         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4049         statement->type            = STATEMENT_DO_WHILE;
4050         statement->source_position = token.source_position;
4051
4052         statement->v.while_stmt.body = parse_statement();
4053         expect(T_while);
4054         expect('(');
4055         statement->v.while_stmt.condition = parse_expression();
4056         expect(')');
4057         expect(';');
4058
4059         return statement;
4060 }
4061
4062 static statement_t *parse_for(void)
4063 {
4064         eat(T_for);
4065
4066         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4067         statement->type            = STATEMENT_FOR;
4068         statement->source_position = token.source_position;
4069
4070         expect('(');
4071
4072         int         top          = environment_top();
4073         context_t  *last_context = context;
4074         set_context(&statement->v.for_stmt.context);
4075
4076         if(token.type != ';') {
4077                 if(is_declaration_specifier(&token, false)) {
4078                         parse_declaration();
4079                 } else {
4080                         statement->v.for_stmt.initialisation = parse_expression();
4081                         expect(';');
4082                 }
4083         } else {
4084                 expect(';');
4085         }
4086
4087         if(token.type != ';') {
4088                 statement->v.for_stmt.condition = parse_expression();
4089         }
4090         expect(';');
4091         if(token.type != ')') {
4092                 statement->v.for_stmt.step = parse_expression();
4093         }
4094         expect(')');
4095         statement->v.for_stmt.body = parse_statement();
4096
4097         assert(context == &statement->v.for_stmt.context);
4098         set_context(last_context);
4099         environment_pop_to(top);
4100
4101         return statement;
4102 }
4103
4104 static statement_t *parse_goto(void)
4105 {
4106         eat(T_goto);
4107
4108         if(token.type != T_IDENTIFIER) {
4109                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
4110                 eat_statement();
4111                 return NULL;
4112         }
4113         symbol_t *symbol = token.v.symbol;
4114         next_token();
4115
4116         declaration_t *label = get_label(symbol);
4117
4118         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4119
4120         statement->type            = STATEMENT_GOTO;
4121         statement->source_position = token.source_position;
4122
4123         statement->v.goto_label = label;
4124
4125         expect(';');
4126
4127         return statement;
4128 }
4129
4130 static statement_t *parse_continue(void)
4131 {
4132         eat(T_continue);
4133         expect(';');
4134
4135         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
4136         statement->type            = STATEMENT_CONTINUE;
4137         statement->source_position = token.source_position;
4138
4139         return statement;
4140 }
4141
4142 static statement_t *parse_break(void)
4143 {
4144         eat(T_break);
4145         expect(';');
4146
4147         statement_t *statement     = allocate_ast_zero(sizeof(statement[0]));
4148         statement->type            = STATEMENT_BREAK;
4149         statement->source_position = token.source_position;
4150
4151         return statement;
4152 }
4153
4154 static statement_t *parse_return(void)
4155 {
4156         eat(T_return);
4157
4158         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4159
4160         statement->type            = STATEMENT_RETURN;
4161         statement->source_position = token.source_position;
4162
4163         assert(current_function->type->type == TYPE_FUNCTION);
4164         function_type_t *function_type = (function_type_t*) current_function->type;
4165         type_t          *return_type   = function_type->result_type;
4166
4167         expression_t *return_value;
4168         if(token.type != ';') {
4169                 return_value = parse_expression();
4170
4171                 if(return_type == type_void && return_value->datatype != type_void) {
4172                         parse_warning("'return' with a value, in function returning void");
4173                         return_value = NULL;
4174                 } else {
4175                         if(return_type != NULL) {
4176                                 semantic_assign(return_type, &return_value, "'return'");
4177                         }
4178                 }
4179         } else {
4180                 return_value = NULL;
4181                 if(return_type != type_void) {
4182                         parse_warning("'return' without value, in function returning "
4183                                       "non-void");
4184                 }
4185         }
4186         statement->v.return_value = return_value;
4187
4188         expect(';');
4189
4190         return statement;
4191 }
4192
4193 static statement_t *parse_declaration_statement(void)
4194 {
4195         declaration_t *before = last_declaration;
4196
4197         statement_t *statement
4198                 = allocate_ast_zero(sizeof(statement[0]));
4199         statement->type            = STATEMENT_DECLARATION;
4200         statement->source_position = token.source_position;
4201
4202         declaration_specifiers_t specifiers;
4203         memset(&specifiers, 0, sizeof(specifiers));
4204         parse_declaration_specifiers(&specifiers);
4205
4206         if(token.type == ';') {
4207                 eat(';');
4208         } else {
4209                 parse_init_declarators(&specifiers);
4210         }
4211
4212         if(before == NULL) {
4213                 statement->v.declaration_stmt.begin = context->declarations;
4214         } else {
4215                 statement->v.declaration_stmt.begin = before->next;
4216         }
4217         statement->v.declaration_stmt.end = last_declaration;
4218
4219         return statement;
4220 }
4221
4222 static statement_t *parse_expression_statement(void)
4223 {
4224         statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
4225         statement->type            = STATEMENT_EXPRESSION;
4226         statement->source_position = token.source_position;
4227
4228         statement->v.expression = parse_expression();
4229
4230         expect(';');
4231
4232         return statement;
4233 }
4234
4235 static statement_t *parse_statement(void)
4236 {
4237         statement_t   *statement = NULL;
4238
4239         /* declaration or statement */
4240         switch(token.type) {
4241         case T_case:
4242                 statement = parse_case_statement();
4243                 break;
4244
4245         case T_default:
4246                 statement = parse_default_statement();
4247                 break;
4248
4249         case '{':
4250                 statement = parse_compound_statement();
4251                 break;
4252
4253         case T_if:
4254                 statement = parse_if();
4255                 break;
4256
4257         case T_switch:
4258                 statement = parse_switch();
4259                 break;
4260
4261         case T_while:
4262                 statement = parse_while();
4263                 break;
4264
4265         case T_do:
4266                 statement = parse_do();
4267                 break;
4268
4269         case T_for:
4270                 statement = parse_for();
4271                 break;
4272
4273         case T_goto:
4274                 statement = parse_goto();
4275                 break;
4276
4277         case T_continue:
4278                 statement = parse_continue();
4279                 break;
4280
4281         case T_break:
4282                 statement = parse_break();
4283                 break;
4284
4285         case T_return:
4286                 statement = parse_return();
4287                 break;
4288
4289         case ';':
4290                 next_token();
4291                 statement = NULL;
4292                 break;
4293
4294         case T_IDENTIFIER:
4295                 if(look_ahead(1)->type == ':') {
4296                         statement = parse_label_statement();
4297                         break;
4298                 }
4299
4300                 if(is_typedef_symbol(token.v.symbol)) {
4301                         statement = parse_declaration_statement();
4302                         break;
4303                 }
4304
4305                 statement = parse_expression_statement();
4306                 break;
4307
4308         case T___extension__:
4309                 /* this can be a prefix to a declaration or an expression statement */
4310                 /* we simply eat it now and parse the rest with tail recursion */
4311                 do {
4312                         next_token();
4313                 } while(token.type == T___extension__);
4314                 statement = parse_statement();
4315                 break;
4316
4317         DECLARATION_START
4318                 statement = parse_declaration_statement();
4319                 break;
4320
4321         default:
4322                 statement = parse_expression_statement();
4323                 break;
4324         }
4325
4326         assert(statement == NULL || statement->source_position.input_name != NULL);
4327
4328         return statement;
4329 }
4330
4331 static statement_t *parse_compound_statement(void)
4332 {
4333         statement_t *compound_statement
4334                 = allocate_ast_zero(sizeof(compound_statement[0]));
4335         compound_statement->type            = STATEMENT_COMPOUND;
4336         compound_statement->source_position = token.source_position;
4337
4338         eat('{');
4339
4340         int        top          = environment_top();
4341         context_t *last_context = context;
4342         set_context(&compound_statement->v.compound_stmt.context);
4343
4344         statement_t *last_statement = NULL;
4345
4346         while(token.type != '}' && token.type != T_EOF) {
4347                 statement_t *statement = parse_statement();
4348                 if(statement == NULL)
4349                         continue;
4350
4351                 if(last_statement != NULL) {
4352                         last_statement->next = statement;
4353                 } else {
4354                         compound_statement->v.compound_stmt.statements = statement;
4355                 }
4356
4357                 while(statement->next != NULL)
4358                         statement = statement->next;
4359
4360                 last_statement = statement;
4361         }
4362
4363         if(token.type != '}') {
4364                 parser_print_error_prefix_pos(
4365                                 compound_statement->source_position);
4366                 fprintf(stderr, "end of file while looking for closing '}'\n");
4367         }
4368         next_token();
4369
4370         assert(context == &compound_statement->v.compound_stmt.context);
4371         set_context(last_context);
4372         environment_pop_to(top);
4373
4374         return compound_statement;
4375 }
4376
4377 static translation_unit_t *parse_translation_unit(void)
4378 {
4379         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
4380
4381         assert(global_context == NULL);
4382         global_context = &unit->context;
4383
4384         assert(context == NULL);
4385         set_context(&unit->context);
4386
4387         while(token.type != T_EOF) {
4388                 parse_declaration();
4389         }
4390
4391         assert(context == &unit->context);
4392         context          = NULL;
4393         last_declaration = NULL;
4394
4395         assert(global_context == &unit->context);
4396         global_context = NULL;
4397
4398         return unit;
4399 }
4400
4401 translation_unit_t *parse(void)
4402 {
4403         environment_stack = NEW_ARR_F(stack_entry_t, 0);
4404         label_stack       = NEW_ARR_F(stack_entry_t, 0);
4405         found_error       = false;
4406
4407         type_set_output(stderr);
4408         ast_set_output(stderr);
4409
4410         lookahead_bufpos = 0;
4411         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
4412                 next_token();
4413         }
4414         translation_unit_t *unit = parse_translation_unit();
4415
4416         DEL_ARR_F(environment_stack);
4417         DEL_ARR_F(label_stack);
4418
4419         if(found_error)
4420                 return NULL;
4421
4422         return unit;
4423 }
4424
4425 void init_parser(void)
4426 {
4427         init_expression_parsers();
4428         obstack_init(&temp_obst);
4429
4430         type_int         = make_atomic_type(ATOMIC_TYPE_INT, TYPE_QUALIFIER_NONE);
4431         type_uint        = make_atomic_type(ATOMIC_TYPE_UINT, TYPE_QUALIFIER_NONE);
4432         type_long_double = make_atomic_type(ATOMIC_TYPE_LONG_DOUBLE, TYPE_QUALIFIER_NONE);
4433         type_double      = make_atomic_type(ATOMIC_TYPE_DOUBLE, TYPE_QUALIFIER_NONE);
4434         type_float       = make_atomic_type(ATOMIC_TYPE_FLOAT, TYPE_QUALIFIER_NONE);
4435         type_size_t      = make_atomic_type(ATOMIC_TYPE_ULONG, TYPE_QUALIFIER_NONE);
4436         type_ptrdiff_t   = make_atomic_type(ATOMIC_TYPE_LONG, TYPE_QUALIFIER_NONE);
4437         type_const_char  = make_atomic_type(ATOMIC_TYPE_CHAR, TYPE_QUALIFIER_CONST);
4438         type_void        = make_atomic_type(ATOMIC_TYPE_VOID, TYPE_QUALIFIER_NONE);
4439         type_void_ptr    = make_pointer_type(type_void, TYPE_QUALIFIER_NONE);
4440         type_string      = make_pointer_type(type_const_char, TYPE_QUALIFIER_NONE);
4441 }
4442
4443 void exit_parser(void)
4444 {
4445         obstack_free(&temp_obst, NULL);
4446 }