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