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