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