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