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