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