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