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