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