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