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