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