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