Consider type qualifiers to avoid incorrect format warnings.
[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 "warning.h"
18 #include "adt/bitfiddle.h"
19 #include "adt/error.h"
20 #include "adt/array.h"
21
22 //#define PRINT_TOKENS
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                                         if (warning.implicit_int) {
1750                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
1751                                         }
1752                                         atomic_type = ATOMIC_TYPE_INT;
1753                                         break;
1754                                 } else {
1755                                         errorf(HERE, "no type specifiers given in declaration");
1756                                 }
1757                         } else if((type_specifiers & SPECIFIER_SIGNED) &&
1758                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
1759                                 errorf(HERE, "signed and unsigned specifiers gives");
1760                         } else if(type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
1761                                 errorf(HERE, "only integer types can be signed or unsigned");
1762                         } else {
1763                                 errorf(HERE, "multiple datatypes in declaration");
1764                         }
1765                         atomic_type = ATOMIC_TYPE_INVALID;
1766                 }
1767
1768                 type               = allocate_type_zero(TYPE_ATOMIC);
1769                 type->atomic.akind = atomic_type;
1770                 newtype            = 1;
1771         } else {
1772                 if(type_specifiers != 0) {
1773                         errorf(HERE, "multiple datatypes in declaration");
1774                 }
1775         }
1776
1777         type->base.qualifiers = type_qualifiers;
1778
1779         type_t *result = typehash_insert(type);
1780         if(newtype && result != type) {
1781                 free_type(type);
1782         }
1783
1784         specifiers->type = result;
1785 }
1786
1787 static type_qualifiers_t parse_type_qualifiers(void)
1788 {
1789         type_qualifiers_t type_qualifiers = TYPE_QUALIFIER_NONE;
1790
1791         while(true) {
1792                 switch(token.type) {
1793                 /* type qualifiers */
1794                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
1795                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
1796                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
1797
1798                 default:
1799                         return type_qualifiers;
1800                 }
1801         }
1802 }
1803
1804 static declaration_t *parse_identifier_list(void)
1805 {
1806         declaration_t *declarations     = NULL;
1807         declaration_t *last_declaration = NULL;
1808         do {
1809                 declaration_t *const declaration = allocate_declaration_zero();
1810                 declaration->source_position = token.source_position;
1811                 declaration->symbol          = token.v.symbol;
1812                 next_token();
1813
1814                 if(last_declaration != NULL) {
1815                         last_declaration->next = declaration;
1816                 } else {
1817                         declarations = declaration;
1818                 }
1819                 last_declaration = declaration;
1820
1821                 if(token.type != ',')
1822                         break;
1823                 next_token();
1824         } while(token.type == T_IDENTIFIER);
1825
1826         return declarations;
1827 }
1828
1829 static void semantic_parameter(declaration_t *declaration)
1830 {
1831         /* TODO: improve error messages */
1832
1833         if(declaration->storage_class == STORAGE_CLASS_TYPEDEF) {
1834                 errorf(HERE, "typedef not allowed in parameter list");
1835         } else if(declaration->storage_class != STORAGE_CLASS_NONE
1836                         && declaration->storage_class != STORAGE_CLASS_REGISTER) {
1837                 errorf(HERE, "parameter may only have none or register storage class");
1838         }
1839
1840         type_t *const orig_type = declaration->type;
1841         type_t *      type      = skip_typeref(orig_type);
1842
1843         /* Array as last part of a parameter type is just syntactic sugar.  Turn it
1844          * into a pointer. Â§ 6.7.5.3 (7) */
1845         if (is_type_array(type)) {
1846                 type_t *const element_type = type->array.element_type;
1847
1848                 type = make_pointer_type(element_type, type->base.qualifiers);
1849
1850                 declaration->type = type;
1851         }
1852
1853         if(is_type_incomplete(type)) {
1854                 errorf(HERE, "incomplete type ('%T') not allowed for parameter '%Y'",
1855                        orig_type, declaration->symbol);
1856         }
1857 }
1858
1859 static declaration_t *parse_parameter(void)
1860 {
1861         declaration_specifiers_t specifiers;
1862         memset(&specifiers, 0, sizeof(specifiers));
1863
1864         parse_declaration_specifiers(&specifiers);
1865
1866         declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/true);
1867
1868         semantic_parameter(declaration);
1869
1870         return declaration;
1871 }
1872
1873 static declaration_t *parse_parameters(function_type_t *type)
1874 {
1875         if(token.type == T_IDENTIFIER) {
1876                 symbol_t *symbol = token.v.symbol;
1877                 if(!is_typedef_symbol(symbol)) {
1878                         type->kr_style_parameters = true;
1879                         return parse_identifier_list();
1880                 }
1881         }
1882
1883         if(token.type == ')') {
1884                 type->unspecified_parameters = 1;
1885                 return NULL;
1886         }
1887         if(token.type == T_void && look_ahead(1)->type == ')') {
1888                 next_token();
1889                 return NULL;
1890         }
1891
1892         declaration_t        *declarations = NULL;
1893         declaration_t        *declaration;
1894         declaration_t        *last_declaration = NULL;
1895         function_parameter_t *parameter;
1896         function_parameter_t *last_parameter = NULL;
1897
1898         while(true) {
1899                 switch(token.type) {
1900                 case T_DOTDOTDOT:
1901                         next_token();
1902                         type->variadic = 1;
1903                         return declarations;
1904
1905                 case T_IDENTIFIER:
1906                 case T___extension__:
1907                 DECLARATION_START
1908                         declaration = parse_parameter();
1909
1910                         parameter       = obstack_alloc(type_obst, sizeof(parameter[0]));
1911                         memset(parameter, 0, sizeof(parameter[0]));
1912                         parameter->type = declaration->type;
1913
1914                         if(last_parameter != NULL) {
1915                                 last_declaration->next = declaration;
1916                                 last_parameter->next   = parameter;
1917                         } else {
1918                                 type->parameters = parameter;
1919                                 declarations     = declaration;
1920                         }
1921                         last_parameter   = parameter;
1922                         last_declaration = declaration;
1923                         break;
1924
1925                 default:
1926                         return declarations;
1927                 }
1928                 if(token.type != ',')
1929                         return declarations;
1930                 next_token();
1931         }
1932 }
1933
1934 typedef enum {
1935         CONSTRUCT_INVALID,
1936         CONSTRUCT_POINTER,
1937         CONSTRUCT_FUNCTION,
1938         CONSTRUCT_ARRAY
1939 } construct_type_type_t;
1940
1941 typedef struct construct_type_t construct_type_t;
1942 struct construct_type_t {
1943         construct_type_type_t  type;
1944         construct_type_t      *next;
1945 };
1946
1947 typedef struct parsed_pointer_t parsed_pointer_t;
1948 struct parsed_pointer_t {
1949         construct_type_t  construct_type;
1950         type_qualifiers_t type_qualifiers;
1951 };
1952
1953 typedef struct construct_function_type_t construct_function_type_t;
1954 struct construct_function_type_t {
1955         construct_type_t  construct_type;
1956         type_t           *function_type;
1957 };
1958
1959 typedef struct parsed_array_t parsed_array_t;
1960 struct parsed_array_t {
1961         construct_type_t  construct_type;
1962         type_qualifiers_t type_qualifiers;
1963         bool              is_static;
1964         bool              is_variable;
1965         expression_t     *size;
1966 };
1967
1968 typedef struct construct_base_type_t construct_base_type_t;
1969 struct construct_base_type_t {
1970         construct_type_t  construct_type;
1971         type_t           *type;
1972 };
1973
1974 static construct_type_t *parse_pointer_declarator(void)
1975 {
1976         eat('*');
1977
1978         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
1979         memset(pointer, 0, sizeof(pointer[0]));
1980         pointer->construct_type.type = CONSTRUCT_POINTER;
1981         pointer->type_qualifiers     = parse_type_qualifiers();
1982
1983         return (construct_type_t*) pointer;
1984 }
1985
1986 static construct_type_t *parse_array_declarator(void)
1987 {
1988         eat('[');
1989
1990         parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
1991         memset(array, 0, sizeof(array[0]));
1992         array->construct_type.type = CONSTRUCT_ARRAY;
1993
1994         if(token.type == T_static) {
1995                 array->is_static = true;
1996                 next_token();
1997         }
1998
1999         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
2000         if(type_qualifiers != 0) {
2001                 if(token.type == T_static) {
2002                         array->is_static = true;
2003                         next_token();
2004                 }
2005         }
2006         array->type_qualifiers = type_qualifiers;
2007
2008         if(token.type == '*' && look_ahead(1)->type == ']') {
2009                 array->is_variable = true;
2010                 next_token();
2011         } else if(token.type != ']') {
2012                 array->size = parse_assignment_expression();
2013         }
2014
2015         expect(']');
2016
2017         return (construct_type_t*) array;
2018 }
2019
2020 static construct_type_t *parse_function_declarator(declaration_t *declaration)
2021 {
2022         eat('(');
2023
2024         type_t *type = allocate_type_zero(TYPE_FUNCTION);
2025
2026         declaration_t *parameters = parse_parameters(&type->function);
2027         if(declaration != NULL) {
2028                 declaration->context.declarations = parameters;
2029         }
2030
2031         construct_function_type_t *construct_function_type =
2032                 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
2033         memset(construct_function_type, 0, sizeof(construct_function_type[0]));
2034         construct_function_type->construct_type.type = CONSTRUCT_FUNCTION;
2035         construct_function_type->function_type       = type;
2036
2037         expect(')');
2038
2039         return (construct_type_t*) construct_function_type;
2040 }
2041
2042 static construct_type_t *parse_inner_declarator(declaration_t *declaration,
2043                 bool may_be_abstract)
2044 {
2045         /* construct a single linked list of construct_type_t's which describe
2046          * how to construct the final declarator type */
2047         construct_type_t *first = NULL;
2048         construct_type_t *last  = NULL;
2049
2050         /* pointers */
2051         while(token.type == '*') {
2052                 construct_type_t *type = parse_pointer_declarator();
2053
2054                 if(last == NULL) {
2055                         first = type;
2056                         last  = type;
2057                 } else {
2058                         last->next = type;
2059                         last       = type;
2060                 }
2061         }
2062
2063         /* TODO: find out if this is correct */
2064         parse_attributes();
2065
2066         construct_type_t *inner_types = NULL;
2067
2068         switch(token.type) {
2069         case T_IDENTIFIER:
2070                 if(declaration == NULL) {
2071                         errorf(HERE, "no identifier expected in typename");
2072                 } else {
2073                         declaration->symbol          = token.v.symbol;
2074                         declaration->source_position = token.source_position;
2075                 }
2076                 next_token();
2077                 break;
2078         case '(':
2079                 next_token();
2080                 inner_types = parse_inner_declarator(declaration, may_be_abstract);
2081                 expect(')');
2082                 break;
2083         default:
2084                 if(may_be_abstract)
2085                         break;
2086                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', 0);
2087                 /* avoid a loop in the outermost scope, because eat_statement doesn't
2088                  * eat '}' */
2089                 if(token.type == '}' && current_function == NULL) {
2090                         next_token();
2091                 } else {
2092                         eat_statement();
2093                 }
2094                 return NULL;
2095         }
2096
2097         construct_type_t *p = last;
2098
2099         while(true) {
2100                 construct_type_t *type;
2101                 switch(token.type) {
2102                 case '(':
2103                         type = parse_function_declarator(declaration);
2104                         break;
2105                 case '[':
2106                         type = parse_array_declarator();
2107                         break;
2108                 default:
2109                         goto declarator_finished;
2110                 }
2111
2112                 /* insert in the middle of the list (behind p) */
2113                 if(p != NULL) {
2114                         type->next = p->next;
2115                         p->next    = type;
2116                 } else {
2117                         type->next = first;
2118                         first      = type;
2119                 }
2120                 if(last == p) {
2121                         last = type;
2122                 }
2123         }
2124
2125 declarator_finished:
2126         parse_attributes();
2127
2128         /* append inner_types at the end of the list, we don't to set last anymore
2129          * as it's not needed anymore */
2130         if(last == NULL) {
2131                 assert(first == NULL);
2132                 first = inner_types;
2133         } else {
2134                 last->next = inner_types;
2135         }
2136
2137         return first;
2138 }
2139
2140 static type_t *construct_declarator_type(construct_type_t *construct_list,
2141                                          type_t *type)
2142 {
2143         construct_type_t *iter = construct_list;
2144         for( ; iter != NULL; iter = iter->next) {
2145                 switch(iter->type) {
2146                 case CONSTRUCT_INVALID:
2147                         panic("invalid type construction found");
2148                 case CONSTRUCT_FUNCTION: {
2149                         construct_function_type_t *construct_function_type
2150                                 = (construct_function_type_t*) iter;
2151
2152                         type_t *function_type = construct_function_type->function_type;
2153
2154                         function_type->function.return_type = type;
2155
2156                         type_t *skipped_return_type = skip_typeref(type);
2157                         if (is_type_function(skipped_return_type)) {
2158                                 errorf(HERE, "function returning function is not allowed");
2159                                 type = type_error_type;
2160                         } else if (is_type_array(skipped_return_type)) {
2161                                 errorf(HERE, "function returning array is not allowed");
2162                                 type = type_error_type;
2163                         } else {
2164                                 type = function_type;
2165                         }
2166                         break;
2167                 }
2168
2169                 case CONSTRUCT_POINTER: {
2170                         parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
2171                         type_t           *pointer_type   = allocate_type_zero(TYPE_POINTER);
2172                         pointer_type->pointer.points_to  = type;
2173                         pointer_type->base.qualifiers    = parsed_pointer->type_qualifiers;
2174
2175                         type = pointer_type;
2176                         break;
2177                 }
2178
2179                 case CONSTRUCT_ARRAY: {
2180                         parsed_array_t *parsed_array  = (parsed_array_t*) iter;
2181                         type_t         *array_type    = allocate_type_zero(TYPE_ARRAY);
2182
2183                         array_type->base.qualifiers    = parsed_array->type_qualifiers;
2184                         array_type->array.element_type = type;
2185                         array_type->array.is_static    = parsed_array->is_static;
2186                         array_type->array.is_variable  = parsed_array->is_variable;
2187                         array_type->array.size         = parsed_array->size;
2188
2189                         type_t *skipped_type = skip_typeref(type);
2190                         if (is_type_atomic(skipped_type, ATOMIC_TYPE_VOID)) {
2191                                 errorf(HERE, "array of void is not allowed");
2192                                 type = type_error_type;
2193                         } else {
2194                                 type = array_type;
2195                         }
2196                         break;
2197                 }
2198                 }
2199
2200                 type_t *hashed_type = typehash_insert(type);
2201                 if(hashed_type != type) {
2202                         /* the function type was constructed earlier freeing it here will
2203                          * destroy other types... */
2204                         if(iter->type != CONSTRUCT_FUNCTION) {
2205                                 free_type(type);
2206                         }
2207                         type = hashed_type;
2208                 }
2209         }
2210
2211         return type;
2212 }
2213
2214 static declaration_t *parse_declarator(
2215                 const declaration_specifiers_t *specifiers, bool may_be_abstract)
2216 {
2217         declaration_t *const declaration = allocate_declaration_zero();
2218         declaration->storage_class  = specifiers->storage_class;
2219         declaration->modifiers      = specifiers->decl_modifiers;
2220         declaration->is_inline      = specifiers->is_inline;
2221
2222         construct_type_t *construct_type
2223                 = parse_inner_declarator(declaration, may_be_abstract);
2224         type_t *const type = specifiers->type;
2225         declaration->type = construct_declarator_type(construct_type, type);
2226
2227         if(construct_type != NULL) {
2228                 obstack_free(&temp_obst, construct_type);
2229         }
2230
2231         return declaration;
2232 }
2233
2234 static type_t *parse_abstract_declarator(type_t *base_type)
2235 {
2236         construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
2237
2238         type_t *result = construct_declarator_type(construct_type, base_type);
2239         if(construct_type != NULL) {
2240                 obstack_free(&temp_obst, construct_type);
2241         }
2242
2243         return result;
2244 }
2245
2246 static declaration_t *append_declaration(declaration_t* const declaration)
2247 {
2248         if (last_declaration != NULL) {
2249                 last_declaration->next = declaration;
2250         } else {
2251                 context->declarations = declaration;
2252         }
2253         last_declaration = declaration;
2254         return declaration;
2255 }
2256
2257 static declaration_t *internal_record_declaration(
2258         declaration_t *const declaration,
2259         const bool is_function_definition)
2260 {
2261         const symbol_t *const symbol  = declaration->symbol;
2262         const namespace_t     namespc = (namespace_t)declaration->namespc;
2263
2264         const type_t *const type = skip_typeref(declaration->type);
2265         if (is_type_function(type) &&
2266                         type->function.unspecified_parameters &&
2267                         warning.strict_prototypes) {
2268                 warningf(declaration->source_position,
2269                          "function declaration '%#T' is not a prototype",
2270                          type, declaration->symbol);
2271         }
2272
2273         declaration_t *const previous_declaration = get_declaration(symbol, namespc);
2274         assert(declaration != previous_declaration);
2275         if (previous_declaration != NULL) {
2276                 if (previous_declaration->parent_context == context) {
2277                         /* can happen for K&R style declarations */
2278                         if(previous_declaration->type == NULL) {
2279                                 previous_declaration->type = declaration->type;
2280                         }
2281
2282                         const type_t *const prev_type = skip_typeref(previous_declaration->type);
2283                         if (!types_compatible(type, prev_type)) {
2284                                 errorf(declaration->source_position,
2285                                         "declaration '%#T' is incompatible with previous declaration '%#T'",
2286                                         type, symbol, previous_declaration->type, symbol);
2287                                 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2288                         } else {
2289                                 unsigned old_storage_class = previous_declaration->storage_class;
2290                                 unsigned new_storage_class = declaration->storage_class;
2291
2292                                 /* pretend no storage class means extern for function declarations
2293                                  * (except if the previous declaration is neither none nor extern) */
2294                                 if (is_type_function(type)) {
2295                                         switch (old_storage_class) {
2296                                                 case STORAGE_CLASS_NONE:
2297                                                         old_storage_class = STORAGE_CLASS_EXTERN;
2298
2299                                                 case STORAGE_CLASS_EXTERN:
2300                                                         if (is_function_definition) {
2301                                                                 if (warning.missing_prototypes &&
2302                                                                     prev_type->function.unspecified_parameters) {
2303                                                                         warningf(declaration->source_position, "no previous prototype for '%#T'", type, symbol);
2304                                                                 }
2305                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
2306                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
2307                                                         }
2308                                                         break;
2309
2310                                                 default: break;
2311                                         }
2312                                 }
2313
2314                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
2315                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
2316 warn_redundant_declaration:
2317                                         if (warning.redundant_decls) {
2318                                                 warningf(declaration->source_position, "redundant declaration for '%Y'", symbol);
2319                                                 warningf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2320                                         }
2321                                 } else if (current_function == NULL) {
2322                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
2323                                                         new_storage_class == STORAGE_CLASS_STATIC) {
2324                                                 errorf(declaration->source_position, "static declaration of '%Y' follows non-static declaration", symbol);
2325                                                 errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2326                                         } else {
2327                                                 if (old_storage_class != STORAGE_CLASS_EXTERN && !is_function_definition) {
2328                                                         goto warn_redundant_declaration;
2329                                                 }
2330                                                 if (new_storage_class == STORAGE_CLASS_NONE) {
2331                                                         previous_declaration->storage_class = STORAGE_CLASS_NONE;
2332                                                 }
2333                                         }
2334                                 } else {
2335                                         if (old_storage_class == new_storage_class) {
2336                                                 errorf(declaration->source_position, "redeclaration of '%Y'", symbol);
2337                                         } else {
2338                                                 errorf(declaration->source_position, "redeclaration of '%Y' with different linkage", symbol);
2339                                         }
2340                                         errorf(previous_declaration->source_position, "previous declaration of '%Y' was here", symbol);
2341                                 }
2342                         }
2343                         return previous_declaration;
2344                 }
2345         } else if (is_function_definition &&
2346                         declaration->storage_class != STORAGE_CLASS_STATIC) {
2347                 if (warning.missing_prototypes) {
2348                         warningf(declaration->source_position, "no previous prototype for '%#T'", type, symbol);
2349                 } else if (warning.missing_declarations) {
2350                         warningf(declaration->source_position, "no previous declaration for '%#T'", type, symbol);
2351                 }
2352         }
2353
2354         assert(declaration->parent_context == NULL);
2355         assert(declaration->symbol != NULL);
2356         assert(context != NULL);
2357
2358         declaration->parent_context = context;
2359
2360         environment_push(declaration);
2361         return append_declaration(declaration);
2362 }
2363
2364 static declaration_t *record_declaration(declaration_t *declaration)
2365 {
2366         return internal_record_declaration(declaration, false);
2367 }
2368
2369 static declaration_t *record_function_definition(declaration_t *declaration)
2370 {
2371         return internal_record_declaration(declaration, true);
2372 }
2373
2374 static void parser_error_multiple_definition(declaration_t *declaration,
2375                 const source_position_t source_position)
2376 {
2377         errorf(source_position, "multiple definition of symbol '%Y'",
2378                declaration->symbol);
2379         errorf(declaration->source_position,
2380                "this is the location of the previous definition.");
2381 }
2382
2383 static bool is_declaration_specifier(const token_t *token,
2384                                      bool only_type_specifiers)
2385 {
2386         switch(token->type) {
2387                 TYPE_SPECIFIERS
2388                         return true;
2389                 case T_IDENTIFIER:
2390                         return is_typedef_symbol(token->v.symbol);
2391
2392                 case T___extension__:
2393                 STORAGE_CLASSES
2394                 TYPE_QUALIFIERS
2395                         return !only_type_specifiers;
2396
2397                 default:
2398                         return false;
2399         }
2400 }
2401
2402 static void parse_init_declarator_rest(declaration_t *declaration)
2403 {
2404         eat('=');
2405
2406         type_t *orig_type = declaration->type;
2407         type_t *type      = type = skip_typeref(orig_type);
2408
2409         if(declaration->init.initializer != NULL) {
2410                 parser_error_multiple_definition(declaration, token.source_position);
2411         }
2412
2413         initializer_t *initializer = parse_initializer(type);
2414
2415         /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size determine
2416          * the array type size */
2417         if(is_type_array(type) && initializer != NULL) {
2418                 array_type_t *array_type = &type->array;
2419
2420                 if(array_type->size == NULL) {
2421                         expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2422
2423                         cnst->base.datatype = type_size_t;
2424
2425                         switch (initializer->kind) {
2426                                 case INITIALIZER_LIST: {
2427                                         cnst->conste.v.int_value = initializer->list.len;
2428                                         break;
2429                                 }
2430
2431                                 case INITIALIZER_STRING: {
2432                                         cnst->conste.v.int_value = initializer->string.string.size;
2433                                         break;
2434                                 }
2435
2436                                 case INITIALIZER_WIDE_STRING: {
2437                                         cnst->conste.v.int_value = initializer->wide_string.string.size;
2438                                         break;
2439                                 }
2440
2441                                 default:
2442                                         panic("invalid initializer type");
2443                         }
2444
2445                         array_type->size = cnst;
2446                 }
2447         }
2448
2449         if(is_type_function(type)) {
2450                 errorf(declaration->source_position,
2451                        "initializers not allowed for function types at declator '%Y' (type '%T')",
2452                        declaration->symbol, orig_type);
2453         } else {
2454                 declaration->init.initializer = initializer;
2455         }
2456 }
2457
2458 /* parse rest of a declaration without any declarator */
2459 static void parse_anonymous_declaration_rest(
2460                 const declaration_specifiers_t *specifiers,
2461                 parsed_declaration_func finished_declaration)
2462 {
2463         eat(';');
2464
2465         declaration_t *const declaration = allocate_declaration_zero();
2466         declaration->type            = specifiers->type;
2467         declaration->storage_class   = specifiers->storage_class;
2468         declaration->source_position = specifiers->source_position;
2469
2470         if (declaration->storage_class != STORAGE_CLASS_NONE) {
2471                 warningf(declaration->source_position, "useless storage class in empty declaration");
2472         }
2473
2474         type_t *type = declaration->type;
2475         switch (type->kind) {
2476                 case TYPE_COMPOUND_STRUCT:
2477                 case TYPE_COMPOUND_UNION: {
2478                         if (type->compound.declaration->symbol == NULL) {
2479                                 warningf(declaration->source_position, "unnamed struct/union that defines no instances");
2480                         }
2481                         break;
2482                 }
2483
2484                 case TYPE_ENUM:
2485                         break;
2486
2487                 default:
2488                         warningf(declaration->source_position, "empty declaration");
2489                         break;
2490         }
2491
2492         finished_declaration(declaration);
2493 }
2494
2495 static void parse_declaration_rest(declaration_t *ndeclaration,
2496                 const declaration_specifiers_t *specifiers,
2497                 parsed_declaration_func finished_declaration)
2498 {
2499         while(true) {
2500                 declaration_t *declaration = finished_declaration(ndeclaration);
2501
2502                 type_t *orig_type = declaration->type;
2503                 type_t *type      = skip_typeref(orig_type);
2504
2505                 if (type->kind != TYPE_FUNCTION &&
2506                     declaration->is_inline &&
2507                     is_type_valid(type)) {
2508                         warningf(declaration->source_position,
2509                                  "variable '%Y' declared 'inline'\n", declaration->symbol);
2510                 }
2511
2512                 if(token.type == '=') {
2513                         parse_init_declarator_rest(declaration);
2514                 }
2515
2516                 if(token.type != ',')
2517                         break;
2518                 eat(',');
2519
2520                 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false);
2521         }
2522         expect_void(';');
2523 }
2524
2525 static declaration_t *finished_kr_declaration(declaration_t *declaration)
2526 {
2527         symbol_t *symbol  = declaration->symbol;
2528         if(symbol == NULL) {
2529                 errorf(HERE, "anonymous declaration not valid as function parameter");
2530                 return declaration;
2531         }
2532         namespace_t namespc = (namespace_t) declaration->namespc;
2533         if(namespc != NAMESPACE_NORMAL) {
2534                 return record_declaration(declaration);
2535         }
2536
2537         declaration_t *previous_declaration = get_declaration(symbol, namespc);
2538         if(previous_declaration == NULL ||
2539                         previous_declaration->parent_context != context) {
2540                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
2541                        symbol);
2542                 return declaration;
2543         }
2544
2545         if(previous_declaration->type == NULL) {
2546                 previous_declaration->type           = declaration->type;
2547                 previous_declaration->storage_class  = declaration->storage_class;
2548                 previous_declaration->parent_context = context;
2549                 return previous_declaration;
2550         } else {
2551                 return record_declaration(declaration);
2552         }
2553 }
2554
2555 static void parse_declaration(parsed_declaration_func finished_declaration)
2556 {
2557         declaration_specifiers_t specifiers;
2558         memset(&specifiers, 0, sizeof(specifiers));
2559         parse_declaration_specifiers(&specifiers);
2560
2561         if(token.type == ';') {
2562                 parse_anonymous_declaration_rest(&specifiers, finished_declaration);
2563         } else {
2564                 declaration_t *declaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2565                 parse_declaration_rest(declaration, &specifiers, finished_declaration);
2566         }
2567 }
2568
2569 static void parse_kr_declaration_list(declaration_t *declaration)
2570 {
2571         type_t *type = skip_typeref(declaration->type);
2572         if(!is_type_function(type))
2573                 return;
2574
2575         if(!type->function.kr_style_parameters)
2576                 return;
2577
2578         /* push function parameters */
2579         int         top          = environment_top();
2580         context_t  *last_context = context;
2581         set_context(&declaration->context);
2582
2583         declaration_t *parameter = declaration->context.declarations;
2584         for( ; parameter != NULL; parameter = parameter->next) {
2585                 assert(parameter->parent_context == NULL);
2586                 parameter->parent_context = context;
2587                 environment_push(parameter);
2588         }
2589
2590         /* parse declaration list */
2591         while(is_declaration_specifier(&token, false)) {
2592                 parse_declaration(finished_kr_declaration);
2593         }
2594
2595         /* pop function parameters */
2596         assert(context == &declaration->context);
2597         set_context(last_context);
2598         environment_pop_to(top);
2599
2600         /* update function type */
2601         type_t *new_type = duplicate_type(type);
2602         new_type->function.kr_style_parameters = false;
2603
2604         function_parameter_t *parameters     = NULL;
2605         function_parameter_t *last_parameter = NULL;
2606
2607         declaration_t *parameter_declaration = declaration->context.declarations;
2608         for( ; parameter_declaration != NULL;
2609                         parameter_declaration = parameter_declaration->next) {
2610                 type_t *parameter_type = parameter_declaration->type;
2611                 if(parameter_type == NULL) {
2612                         if (strict_mode) {
2613                                 errorf(HERE, "no type specified for function parameter '%Y'",
2614                                        parameter_declaration->symbol);
2615                         } else {
2616                                 if (warning.implicit_int) {
2617                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
2618                                                 parameter_declaration->symbol);
2619                                 }
2620                                 parameter_type              = type_int;
2621                                 parameter_declaration->type = parameter_type;
2622                         }
2623                 }
2624
2625                 semantic_parameter(parameter_declaration);
2626                 parameter_type = parameter_declaration->type;
2627
2628                 function_parameter_t *function_parameter
2629                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
2630                 memset(function_parameter, 0, sizeof(function_parameter[0]));
2631
2632                 function_parameter->type = parameter_type;
2633                 if(last_parameter != NULL) {
2634                         last_parameter->next = function_parameter;
2635                 } else {
2636                         parameters = function_parameter;
2637                 }
2638                 last_parameter = function_parameter;
2639         }
2640         new_type->function.parameters = parameters;
2641
2642         type = typehash_insert(new_type);
2643         if(type != new_type) {
2644                 obstack_free(type_obst, new_type);
2645         }
2646
2647         declaration->type = type;
2648 }
2649
2650 /**
2651  * Check if all labels are defined in the current function.
2652  */
2653 static void check_for_missing_labels(void)
2654 {
2655         bool first_err = true;
2656         for (const goto_statement_t *goto_statement = goto_first;
2657              goto_statement != NULL;
2658              goto_statement = goto_statement->next) {
2659                  const declaration_t *label = goto_statement->label;
2660
2661                  if (label->source_position.input_name == NULL) {
2662                          if (first_err) {
2663                                  first_err = false;
2664                                  diagnosticf("%s: In function '%Y':\n",
2665                                          current_function->source_position.input_name,
2666                                          current_function->symbol);
2667                          }
2668                          errorf(goto_statement->statement.source_position,
2669                                  "label '%Y' used but not defined", label->symbol);
2670                  }
2671         }
2672         goto_first = goto_last = NULL;
2673 }
2674
2675 static void parse_external_declaration(void)
2676 {
2677         /* function-definitions and declarations both start with declaration
2678          * specifiers */
2679         declaration_specifiers_t specifiers;
2680         memset(&specifiers, 0, sizeof(specifiers));
2681         parse_declaration_specifiers(&specifiers);
2682
2683         /* must be a declaration */
2684         if(token.type == ';') {
2685                 parse_anonymous_declaration_rest(&specifiers, append_declaration);
2686                 return;
2687         }
2688
2689         /* declarator is common to both function-definitions and declarations */
2690         declaration_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false);
2691
2692         /* must be a declaration */
2693         if(token.type == ',' || token.type == '=' || token.type == ';') {
2694                 parse_declaration_rest(ndeclaration, &specifiers, record_declaration);
2695                 return;
2696         }
2697
2698         /* must be a function definition */
2699         parse_kr_declaration_list(ndeclaration);
2700
2701         if(token.type != '{') {
2702                 parse_error_expected("while parsing function definition", '{', 0);
2703                 eat_statement();
2704                 return;
2705         }
2706
2707         type_t *type = ndeclaration->type;
2708
2709         /* note that we don't skip typerefs: the standard doesn't allow them here
2710          * (so we can't use is_type_function here) */
2711         if(type->kind != TYPE_FUNCTION) {
2712                 if (is_type_valid(type)) {
2713                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
2714                                type, ndeclaration->symbol);
2715                 }
2716                 eat_block();
2717                 return;
2718         }
2719
2720         /* Â§ 6.7.5.3 (14) a function definition with () means no
2721          * parameters (and not unspecified parameters) */
2722         if(type->function.unspecified_parameters) {
2723                 type_t *duplicate = duplicate_type(type);
2724                 duplicate->function.unspecified_parameters = false;
2725
2726                 type = typehash_insert(duplicate);
2727                 if(type != duplicate) {
2728                         obstack_free(type_obst, duplicate);
2729                 }
2730                 ndeclaration->type = type;
2731         }
2732
2733         declaration_t *const declaration = record_function_definition(ndeclaration);
2734         if(ndeclaration != declaration) {
2735                 declaration->context = ndeclaration->context;
2736         }
2737         type = skip_typeref(declaration->type);
2738
2739         /* push function parameters and switch context */
2740         int         top          = environment_top();
2741         context_t  *last_context = context;
2742         set_context(&declaration->context);
2743
2744         declaration_t *parameter = declaration->context.declarations;
2745         for( ; parameter != NULL; parameter = parameter->next) {
2746                 if(parameter->parent_context == &ndeclaration->context) {
2747                         parameter->parent_context = context;
2748                 }
2749                 assert(parameter->parent_context == NULL
2750                                 || parameter->parent_context == context);
2751                 parameter->parent_context = context;
2752                 environment_push(parameter);
2753         }
2754
2755         if(declaration->init.statement != NULL) {
2756                 parser_error_multiple_definition(declaration, token.source_position);
2757                 eat_block();
2758                 goto end_of_parse_external_declaration;
2759         } else {
2760                 /* parse function body */
2761                 int            label_stack_top      = label_top();
2762                 declaration_t *old_current_function = current_function;
2763                 current_function                    = declaration;
2764
2765                 declaration->init.statement = parse_compound_statement();
2766                 check_for_missing_labels();
2767
2768                 assert(current_function == declaration);
2769                 current_function = old_current_function;
2770                 label_pop_to(label_stack_top);
2771         }
2772
2773 end_of_parse_external_declaration:
2774         assert(context == &declaration->context);
2775         set_context(last_context);
2776         environment_pop_to(top);
2777 }
2778
2779 static type_t *make_bitfield_type(type_t *base, expression_t *size)
2780 {
2781         type_t *type        = allocate_type_zero(TYPE_BITFIELD);
2782         type->bitfield.base = base;
2783         type->bitfield.size = size;
2784
2785         return type;
2786 }
2787
2788 static void parse_struct_declarators(const declaration_specifiers_t *specifiers)
2789 {
2790         /* TODO: check constraints for struct declarations (in specifiers) */
2791         while(1) {
2792                 declaration_t *declaration;
2793
2794                 if(token.type == ':') {
2795                         next_token();
2796
2797                         type_t *base_type = specifiers->type;
2798                         expression_t *size = parse_constant_expression();
2799
2800                         type_t *type = make_bitfield_type(base_type, size);
2801
2802                         declaration = allocate_declaration_zero();
2803                         declaration->namespc         = NAMESPACE_NORMAL;
2804                         declaration->storage_class   = STORAGE_CLASS_NONE;
2805                         declaration->source_position = token.source_position;
2806                         declaration->modifiers       = specifiers->decl_modifiers;
2807                         declaration->type            = type;
2808                 } else {
2809                         declaration = parse_declarator(specifiers,/*may_be_abstract=*/true);
2810
2811                         if(token.type == ':') {
2812                                 next_token();
2813                                 expression_t *size = parse_constant_expression();
2814
2815                                 type_t *type = make_bitfield_type(declaration->type, size);
2816                                 declaration->type = type;
2817                         }
2818                 }
2819                 record_declaration(declaration);
2820
2821                 if(token.type != ',')
2822                         break;
2823                 next_token();
2824         }
2825         expect_void(';');
2826 }
2827
2828 static void parse_compound_type_entries(void)
2829 {
2830         eat('{');
2831
2832         while(token.type != '}' && token.type != T_EOF) {
2833                 declaration_specifiers_t specifiers;
2834                 memset(&specifiers, 0, sizeof(specifiers));
2835                 parse_declaration_specifiers(&specifiers);
2836
2837                 parse_struct_declarators(&specifiers);
2838         }
2839         if(token.type == T_EOF) {
2840                 errorf(HERE, "EOF while parsing struct");
2841         }
2842         next_token();
2843 }
2844
2845 static type_t *parse_typename(void)
2846 {
2847         declaration_specifiers_t specifiers;
2848         memset(&specifiers, 0, sizeof(specifiers));
2849         parse_declaration_specifiers(&specifiers);
2850         if(specifiers.storage_class != STORAGE_CLASS_NONE) {
2851                 /* TODO: improve error message, user does probably not know what a
2852                  * storage class is...
2853                  */
2854                 errorf(HERE, "typename may not have a storage class");
2855         }
2856
2857         type_t *result = parse_abstract_declarator(specifiers.type);
2858
2859         return result;
2860 }
2861
2862
2863
2864
2865 typedef expression_t* (*parse_expression_function) (unsigned precedence);
2866 typedef expression_t* (*parse_expression_infix_function) (unsigned precedence,
2867                                                           expression_t *left);
2868
2869 typedef struct expression_parser_function_t expression_parser_function_t;
2870 struct expression_parser_function_t {
2871         unsigned                         precedence;
2872         parse_expression_function        parser;
2873         unsigned                         infix_precedence;
2874         parse_expression_infix_function  infix_parser;
2875 };
2876
2877 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
2878
2879 /**
2880  * Creates a new invalid expression.
2881  */
2882 static expression_t *create_invalid_expression(void)
2883 {
2884         expression_t *expression         = allocate_expression_zero(EXPR_INVALID);
2885         expression->base.source_position = token.source_position;
2886         return expression;
2887 }
2888
2889 /**
2890  * Prints an error message if an expression was expected but not read
2891  */
2892 static expression_t *expected_expression_error(void)
2893 {
2894         /* skip the error message if the error token was read */
2895         if (token.type != T_ERROR) {
2896                 errorf(HERE, "expected expression, got token '%K'", &token);
2897         }
2898         next_token();
2899
2900         return create_invalid_expression();
2901 }
2902
2903 /**
2904  * Parse a string constant.
2905  */
2906 static expression_t *parse_string_const(void)
2907 {
2908         expression_t *cnst  = allocate_expression_zero(EXPR_STRING_LITERAL);
2909         cnst->base.datatype = type_string;
2910         cnst->string.value  = parse_string_literals();
2911
2912         return cnst;
2913 }
2914
2915 /**
2916  * Parse a wide string constant.
2917  */
2918 static expression_t *parse_wide_string_const(void)
2919 {
2920         expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
2921         cnst->base.datatype      = type_wchar_t_ptr;
2922         cnst->wide_string.value  = token.v.wide_string; /* TODO concatenate */
2923         next_token();
2924         return cnst;
2925 }
2926
2927 /**
2928  * Parse an integer constant.
2929  */
2930 static expression_t *parse_int_const(void)
2931 {
2932         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2933         cnst->base.datatype      = token.datatype;
2934         cnst->conste.v.int_value = token.v.intvalue;
2935
2936         next_token();
2937
2938         return cnst;
2939 }
2940
2941 /**
2942  * Parse a float constant.
2943  */
2944 static expression_t *parse_float_const(void)
2945 {
2946         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
2947         cnst->base.datatype        = token.datatype;
2948         cnst->conste.v.float_value = token.v.floatvalue;
2949
2950         next_token();
2951
2952         return cnst;
2953 }
2954
2955 static declaration_t *create_implicit_function(symbol_t *symbol,
2956                 const source_position_t source_position)
2957 {
2958         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
2959         ntype->function.return_type            = type_int;
2960         ntype->function.unspecified_parameters = true;
2961
2962         type_t *type = typehash_insert(ntype);
2963         if(type != ntype) {
2964                 free_type(ntype);
2965         }
2966
2967         declaration_t *const declaration = allocate_declaration_zero();
2968         declaration->storage_class   = STORAGE_CLASS_EXTERN;
2969         declaration->type            = type;
2970         declaration->symbol          = symbol;
2971         declaration->source_position = source_position;
2972         declaration->parent_context  = global_context;
2973
2974         context_t *old_context = context;
2975         set_context(global_context);
2976
2977         environment_push(declaration);
2978         /* prepend the declaration to the global declarations list */
2979         declaration->next     = context->declarations;
2980         context->declarations = declaration;
2981
2982         assert(context == global_context);
2983         set_context(old_context);
2984
2985         return declaration;
2986 }
2987
2988 /**
2989  * Creates a return_type (func)(argument_type) function type if not
2990  * already exists.
2991  *
2992  * @param return_type    the return type
2993  * @param argument_type  the argument type
2994  */
2995 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
2996 {
2997         function_parameter_t *parameter
2998                 = obstack_alloc(type_obst, sizeof(parameter[0]));
2999         memset(parameter, 0, sizeof(parameter[0]));
3000         parameter->type = argument_type;
3001
3002         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
3003         type->function.return_type = return_type;
3004         type->function.parameters  = parameter;
3005
3006         type_t *result = typehash_insert(type);
3007         if(result != type) {
3008                 free_type(type);
3009         }
3010
3011         return result;
3012 }
3013
3014 /**
3015  * Creates a function type for some function like builtins.
3016  *
3017  * @param symbol   the symbol describing the builtin
3018  */
3019 static type_t *get_builtin_symbol_type(symbol_t *symbol)
3020 {
3021         switch(symbol->ID) {
3022         case T___builtin_alloca:
3023                 return make_function_1_type(type_void_ptr, type_size_t);
3024         case T___builtin_nan:
3025                 return make_function_1_type(type_double, type_string);
3026         case T___builtin_nanf:
3027                 return make_function_1_type(type_float, type_string);
3028         case T___builtin_nand:
3029                 return make_function_1_type(type_long_double, type_string);
3030         case T___builtin_va_end:
3031                 return make_function_1_type(type_void, type_valist);
3032         default:
3033                 panic("not implemented builtin symbol found");
3034         }
3035 }
3036
3037 /**
3038  * Performs automatic type cast as described in Â§ 6.3.2.1.
3039  *
3040  * @param orig_type  the original type
3041  */
3042 static type_t *automatic_type_conversion(type_t *orig_type)
3043 {
3044         type_t *type = skip_typeref(orig_type);
3045         if(is_type_array(type)) {
3046                 array_type_t *array_type   = &type->array;
3047                 type_t       *element_type = array_type->element_type;
3048                 unsigned      qualifiers   = array_type->type.qualifiers;
3049
3050                 return make_pointer_type(element_type, qualifiers);
3051         }
3052
3053         if(is_type_function(type)) {
3054                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
3055         }
3056
3057         return orig_type;
3058 }
3059
3060 /**
3061  * reverts the automatic casts of array to pointer types and function
3062  * to function-pointer types as defined Â§ 6.3.2.1
3063  */
3064 type_t *revert_automatic_type_conversion(const expression_t *expression)
3065 {
3066         switch (expression->kind) {
3067                 case EXPR_REFERENCE: return expression->reference.declaration->type;
3068                 case EXPR_SELECT:    return expression->select.compound_entry->type;
3069
3070                 case EXPR_UNARY_DEREFERENCE: {
3071                         const expression_t *const value = expression->unary.value;
3072                         type_t             *const type  = skip_typeref(value->base.datatype);
3073                         assert(is_type_pointer(type));
3074                         return type->pointer.points_to;
3075                 }
3076
3077                 case EXPR_BUILTIN_SYMBOL:
3078                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
3079
3080                 case EXPR_ARRAY_ACCESS: {
3081                         const expression_t *const array_ref = expression->array_access.array_ref;
3082                         type_t             *const type_left = skip_typeref(array_ref->base.datatype);
3083                         if (!is_type_valid(type_left))
3084                                 return type_left;
3085                         assert(is_type_pointer(type_left));
3086                         return type_left->pointer.points_to;
3087                 }
3088
3089                 default: break;
3090         }
3091
3092         return expression->base.datatype;
3093 }
3094
3095 static expression_t *parse_reference(void)
3096 {
3097         expression_t *expression = allocate_expression_zero(EXPR_REFERENCE);
3098
3099         reference_expression_t *ref = &expression->reference;
3100         ref->symbol = token.v.symbol;
3101
3102         declaration_t *declaration = get_declaration(ref->symbol, NAMESPACE_NORMAL);
3103
3104         source_position_t source_position = token.source_position;
3105         next_token();
3106
3107         if(declaration == NULL) {
3108                 if (! strict_mode && token.type == '(') {
3109                         /* an implicitly defined function */
3110                         if (warning.implicit_function_declaration) {
3111                                 warningf(HERE, "implicit declaration of function '%Y'",
3112                                         ref->symbol);
3113                         }
3114
3115                         declaration = create_implicit_function(ref->symbol,
3116                                                                source_position);
3117                 } else {
3118                         errorf(HERE, "unknown symbol '%Y' found.", ref->symbol);
3119                         return expression;
3120                 }
3121         }
3122
3123         type_t *type         = declaration->type;
3124
3125         /* we always do the auto-type conversions; the & and sizeof parser contains
3126          * code to revert this! */
3127         type = automatic_type_conversion(type);
3128
3129         ref->declaration         = declaration;
3130         ref->expression.datatype = type;
3131
3132         return expression;
3133 }
3134
3135 static void check_cast_allowed(expression_t *expression, type_t *dest_type)
3136 {
3137         (void) expression;
3138         (void) dest_type;
3139         /* TODO check if explicit cast is allowed and issue warnings/errors */
3140 }
3141
3142 static expression_t *parse_cast(void)
3143 {
3144         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
3145
3146         cast->base.source_position = token.source_position;
3147
3148         type_t *type  = parse_typename();
3149
3150         expect(')');
3151         expression_t *value = parse_sub_expression(20);
3152
3153         check_cast_allowed(value, type);
3154
3155         cast->base.datatype = type;
3156         cast->unary.value   = value;
3157
3158         return cast;
3159 }
3160
3161 static expression_t *parse_statement_expression(void)
3162 {
3163         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
3164
3165         statement_t *statement           = parse_compound_statement();
3166         expression->statement.statement  = statement;
3167         expression->base.source_position = statement->base.source_position;
3168
3169         /* find last statement and use its type */
3170         type_t *type = type_void;
3171         const statement_t *stmt = statement->compound.statements;
3172         if (stmt != NULL) {
3173                 while (stmt->base.next != NULL)
3174                         stmt = stmt->base.next;
3175
3176                 if (stmt->kind == STATEMENT_EXPRESSION) {
3177                         type = stmt->expression.expression->base.datatype;
3178                 }
3179         } else {
3180                 warningf(expression->base.source_position, "empty statement expression ({})");
3181         }
3182         expression->base.datatype = type;
3183
3184         expect(')');
3185
3186         return expression;
3187 }
3188
3189 static expression_t *parse_brace_expression(void)
3190 {
3191         eat('(');
3192
3193         switch(token.type) {
3194         case '{':
3195                 /* gcc extension: a statement expression */
3196                 return parse_statement_expression();
3197
3198         TYPE_QUALIFIERS
3199         TYPE_SPECIFIERS
3200                 return parse_cast();
3201         case T_IDENTIFIER:
3202                 if(is_typedef_symbol(token.v.symbol)) {
3203                         return parse_cast();
3204                 }
3205         }
3206
3207         expression_t *result = parse_expression();
3208         expect(')');
3209
3210         return result;
3211 }
3212
3213 static expression_t *parse_function_keyword(void)
3214 {
3215         next_token();
3216         /* TODO */
3217
3218         if (current_function == NULL) {
3219                 errorf(HERE, "'__func__' used outside of a function");
3220         }
3221
3222         string_literal_expression_t *expression
3223                 = allocate_ast_zero(sizeof(expression[0]));
3224
3225         expression->expression.kind     = EXPR_FUNCTION;
3226         expression->expression.datatype = type_string;
3227
3228         return (expression_t*) expression;
3229 }
3230
3231 static expression_t *parse_pretty_function_keyword(void)
3232 {
3233         eat(T___PRETTY_FUNCTION__);
3234         /* TODO */
3235
3236         if (current_function == NULL) {
3237                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
3238         }
3239
3240         string_literal_expression_t *expression
3241                 = allocate_ast_zero(sizeof(expression[0]));
3242
3243         expression->expression.kind     = EXPR_PRETTY_FUNCTION;
3244         expression->expression.datatype = type_string;
3245
3246         return (expression_t*) expression;
3247 }
3248
3249 static designator_t *parse_designator(void)
3250 {
3251         designator_t *result = allocate_ast_zero(sizeof(result[0]));
3252
3253         if(token.type != T_IDENTIFIER) {
3254                 parse_error_expected("while parsing member designator",
3255                                      T_IDENTIFIER, 0);
3256                 eat_paren();
3257                 return NULL;
3258         }
3259         result->symbol = token.v.symbol;
3260         next_token();
3261
3262         designator_t *last_designator = result;
3263         while(true) {
3264                 if(token.type == '.') {
3265                         next_token();
3266                         if(token.type != T_IDENTIFIER) {
3267                                 parse_error_expected("while parsing member designator",
3268                                                      T_IDENTIFIER, 0);
3269                                 eat_paren();
3270                                 return NULL;
3271                         }
3272                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3273                         designator->symbol       = token.v.symbol;
3274                         next_token();
3275
3276                         last_designator->next = designator;
3277                         last_designator       = designator;
3278                         continue;
3279                 }
3280                 if(token.type == '[') {
3281                         next_token();
3282                         designator_t *designator = allocate_ast_zero(sizeof(result[0]));
3283                         designator->array_access = parse_expression();
3284                         if(designator->array_access == NULL) {
3285                                 eat_paren();
3286                                 return NULL;
3287                         }
3288                         expect(']');
3289
3290                         last_designator->next = designator;
3291                         last_designator       = designator;
3292                         continue;
3293                 }
3294                 break;
3295         }
3296
3297         return result;
3298 }
3299
3300 static expression_t *parse_offsetof(void)
3301 {
3302         eat(T___builtin_offsetof);
3303
3304         expression_t *expression  = allocate_expression_zero(EXPR_OFFSETOF);
3305         expression->base.datatype = type_size_t;
3306
3307         expect('(');
3308         expression->offsetofe.type = parse_typename();
3309         expect(',');
3310         expression->offsetofe.designator = parse_designator();
3311         expect(')');
3312
3313         return expression;
3314 }
3315
3316 static expression_t *parse_va_start(void)
3317 {
3318         eat(T___builtin_va_start);
3319
3320         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
3321
3322         expect('(');
3323         expression->va_starte.ap = parse_assignment_expression();
3324         expect(',');
3325         expression_t *const expr = parse_assignment_expression();
3326         if (expr->kind == EXPR_REFERENCE) {
3327                 declaration_t *const decl = expr->reference.declaration;
3328                 if (decl->parent_context == &current_function->context &&
3329                     decl->next == NULL) {
3330                         expression->va_starte.parameter = decl;
3331                         expect(')');
3332                         return expression;
3333                 }
3334         }
3335         errorf(expr->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
3336
3337         return create_invalid_expression();
3338 }
3339
3340 static expression_t *parse_va_arg(void)
3341 {
3342         eat(T___builtin_va_arg);
3343
3344         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
3345
3346         expect('(');
3347         expression->va_arge.ap = parse_assignment_expression();
3348         expect(',');
3349         expression->base.datatype = parse_typename();
3350         expect(')');
3351
3352         return expression;
3353 }
3354
3355 static expression_t *parse_builtin_symbol(void)
3356 {
3357         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
3358
3359         symbol_t *symbol = token.v.symbol;
3360
3361         expression->builtin_symbol.symbol = symbol;
3362         next_token();
3363
3364         type_t *type = get_builtin_symbol_type(symbol);
3365         type = automatic_type_conversion(type);
3366
3367         expression->base.datatype = type;
3368         return expression;
3369 }
3370
3371 static expression_t *parse_builtin_constant(void)
3372 {
3373         eat(T___builtin_constant_p);
3374
3375         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
3376
3377         expect('(');
3378         expression->builtin_constant.value = parse_assignment_expression();
3379         expect(')');
3380         expression->base.datatype = type_int;
3381
3382         return expression;
3383 }
3384
3385 static expression_t *parse_builtin_prefetch(void)
3386 {
3387         eat(T___builtin_prefetch);
3388
3389         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
3390
3391         expect('(');
3392         expression->builtin_prefetch.adr = parse_assignment_expression();
3393         if (token.type == ',') {
3394                 next_token();
3395                 expression->builtin_prefetch.rw = parse_assignment_expression();
3396         }
3397         if (token.type == ',') {
3398                 next_token();
3399                 expression->builtin_prefetch.locality = parse_assignment_expression();
3400         }
3401         expect(')');
3402         expression->base.datatype = type_void;
3403
3404         return expression;
3405 }
3406
3407 static expression_t *parse_compare_builtin(void)
3408 {
3409         expression_t *expression;
3410
3411         switch(token.type) {
3412         case T___builtin_isgreater:
3413                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
3414                 break;
3415         case T___builtin_isgreaterequal:
3416                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
3417                 break;
3418         case T___builtin_isless:
3419                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
3420                 break;
3421         case T___builtin_islessequal:
3422                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
3423                 break;
3424         case T___builtin_islessgreater:
3425                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
3426                 break;
3427         case T___builtin_isunordered:
3428                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
3429                 break;
3430         default:
3431                 panic("invalid compare builtin found");
3432                 break;
3433         }
3434         next_token();
3435
3436         expect('(');
3437         expression->binary.left = parse_assignment_expression();
3438         expect(',');
3439         expression->binary.right = parse_assignment_expression();
3440         expect(')');
3441
3442         type_t *const orig_type_left  = expression->binary.left->base.datatype;
3443         type_t *const orig_type_right = expression->binary.right->base.datatype;
3444
3445         type_t *const type_left  = skip_typeref(orig_type_left);
3446         type_t *const type_right = skip_typeref(orig_type_right);
3447         if(!is_type_floating(type_left) && !is_type_floating(type_right)) {
3448                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
3449                         type_error_incompatible("invalid operands in comparison",
3450                                 token.source_position, orig_type_left, orig_type_right);
3451                 }
3452         } else {
3453                 semantic_comparison(&expression->binary);
3454         }
3455
3456         return expression;
3457 }
3458
3459 static expression_t *parse_builtin_expect(void)
3460 {
3461         eat(T___builtin_expect);
3462
3463         expression_t *expression
3464                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
3465
3466         expect('(');
3467         expression->binary.left = parse_assignment_expression();
3468         expect(',');
3469         expression->binary.right = parse_constant_expression();
3470         expect(')');
3471
3472         expression->base.datatype = expression->binary.left->base.datatype;
3473
3474         return expression;
3475 }
3476
3477 static expression_t *parse_assume(void) {
3478         eat(T_assume);
3479
3480         expression_t *expression
3481                 = allocate_expression_zero(EXPR_UNARY_ASSUME);
3482
3483         expect('(');
3484         expression->unary.value = parse_assignment_expression();
3485         expect(')');
3486
3487         expression->base.datatype = type_void;
3488         return expression;
3489 }
3490
3491 static expression_t *parse_alignof(void) {
3492         eat(T___alignof__);
3493
3494         expression_t *expression
3495                 = allocate_expression_zero(EXPR_ALIGNOF);
3496
3497         expect('(');
3498         expression->alignofe.type = parse_typename();
3499         expect(')');
3500
3501         expression->base.datatype = type_size_t;
3502         return expression;
3503 }
3504
3505 static expression_t *parse_primary_expression(void)
3506 {
3507         switch(token.type) {
3508         case T_INTEGER:
3509                 return parse_int_const();
3510         case T_FLOATINGPOINT:
3511                 return parse_float_const();
3512         case T_STRING_LITERAL:
3513                 return parse_string_const();
3514         case T_WIDE_STRING_LITERAL:
3515                 return parse_wide_string_const();
3516         case T_IDENTIFIER:
3517                 return parse_reference();
3518         case T___FUNCTION__:
3519         case T___func__:
3520                 return parse_function_keyword();
3521         case T___PRETTY_FUNCTION__:
3522                 return parse_pretty_function_keyword();
3523         case T___builtin_offsetof:
3524                 return parse_offsetof();
3525         case T___builtin_va_start:
3526                 return parse_va_start();
3527         case T___builtin_va_arg:
3528                 return parse_va_arg();
3529         case T___builtin_expect:
3530                 return parse_builtin_expect();
3531         case T___builtin_nanf:
3532         case T___builtin_alloca:
3533         case T___builtin_va_end:
3534                 return parse_builtin_symbol();
3535         case T___builtin_isgreater:
3536         case T___builtin_isgreaterequal:
3537         case T___builtin_isless:
3538         case T___builtin_islessequal:
3539         case T___builtin_islessgreater:
3540         case T___builtin_isunordered:
3541                 return parse_compare_builtin();
3542         case T___builtin_constant_p:
3543                 return parse_builtin_constant();
3544         case T___builtin_prefetch:
3545                 return parse_builtin_prefetch();
3546         case T___alignof__:
3547                 return parse_alignof();
3548         case T_assume:
3549                 return parse_assume();
3550
3551         case '(':
3552                 return parse_brace_expression();
3553         }
3554
3555         errorf(HERE, "unexpected token '%K'", &token);
3556         eat_statement();
3557
3558         return create_invalid_expression();
3559 }
3560
3561 /**
3562  * Check if the expression has the character type and issue a warning then.
3563  */
3564 static void check_for_char_index_type(const expression_t *expression) {
3565         type_t       *const type      = expression->base.datatype;
3566         const type_t *const base_type = skip_typeref(type);
3567
3568         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
3569                         warning.char_subscripts) {
3570                 warningf(expression->base.source_position,
3571                         "array subscript has type '%T'", type);
3572         }
3573 }
3574
3575 static expression_t *parse_array_expression(unsigned precedence,
3576                                             expression_t *left)
3577 {
3578         (void) precedence;
3579
3580         eat('[');
3581
3582         expression_t *inside = parse_expression();
3583
3584         array_access_expression_t *array_access
3585                 = allocate_ast_zero(sizeof(array_access[0]));
3586
3587         array_access->expression.kind = EXPR_ARRAY_ACCESS;
3588
3589         type_t *const orig_type_left   = left->base.datatype;
3590         type_t *const orig_type_inside = inside->base.datatype;
3591
3592         type_t *const type_left   = skip_typeref(orig_type_left);
3593         type_t *const type_inside = skip_typeref(orig_type_inside);
3594
3595         type_t *return_type;
3596         if (is_type_pointer(type_left)) {
3597                 return_type             = type_left->pointer.points_to;
3598                 array_access->array_ref = left;
3599                 array_access->index     = inside;
3600                 check_for_char_index_type(inside);
3601         } else if (is_type_pointer(type_inside)) {
3602                 return_type             = type_inside->pointer.points_to;
3603                 array_access->array_ref = inside;
3604                 array_access->index     = left;
3605                 array_access->flipped   = true;
3606                 check_for_char_index_type(left);
3607         } else {
3608                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
3609                         errorf(HERE,
3610                                 "array access on object with non-pointer types '%T', '%T'",
3611                                 orig_type_left, orig_type_inside);
3612                 }
3613                 return_type             = type_error_type;
3614                 array_access->array_ref = create_invalid_expression();
3615         }
3616
3617         if(token.type != ']') {
3618                 parse_error_expected("Problem while parsing array access", ']', 0);
3619                 return (expression_t*) array_access;
3620         }
3621         next_token();
3622
3623         return_type = automatic_type_conversion(return_type);
3624         array_access->expression.datatype = return_type;
3625
3626         return (expression_t*) array_access;
3627 }
3628
3629 static expression_t *parse_sizeof(unsigned precedence)
3630 {
3631         eat(T_sizeof);
3632
3633         sizeof_expression_t *sizeof_expression
3634                 = allocate_ast_zero(sizeof(sizeof_expression[0]));
3635         sizeof_expression->expression.kind     = EXPR_SIZEOF;
3636         sizeof_expression->expression.datatype = type_size_t;
3637
3638         if(token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
3639                 next_token();
3640                 sizeof_expression->type = parse_typename();
3641                 expect(')');
3642         } else {
3643                 expression_t *expression  = parse_sub_expression(precedence);
3644                 expression->base.datatype = revert_automatic_type_conversion(expression);
3645
3646                 sizeof_expression->type            = expression->base.datatype;
3647                 sizeof_expression->size_expression = expression;
3648         }
3649
3650         return (expression_t*) sizeof_expression;
3651 }
3652
3653 static expression_t *parse_select_expression(unsigned precedence,
3654                                              expression_t *compound)
3655 {
3656         (void) precedence;
3657         assert(token.type == '.' || token.type == T_MINUSGREATER);
3658
3659         bool is_pointer = (token.type == T_MINUSGREATER);
3660         next_token();
3661
3662         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
3663         select->select.compound = compound;
3664
3665         if(token.type != T_IDENTIFIER) {
3666                 parse_error_expected("while parsing select", T_IDENTIFIER, 0);
3667                 return select;
3668         }
3669         symbol_t *symbol      = token.v.symbol;
3670         select->select.symbol = symbol;
3671         next_token();
3672
3673         type_t *const orig_type = compound->base.datatype;
3674         type_t *const type      = skip_typeref(orig_type);
3675
3676         type_t *type_left = type;
3677         if(is_pointer) {
3678                 if (!is_type_pointer(type)) {
3679                         if (is_type_valid(type)) {
3680                                 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
3681                         }
3682                         return create_invalid_expression();
3683                 }
3684                 type_left = type->pointer.points_to;
3685         }
3686         type_left = skip_typeref(type_left);
3687
3688         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
3689             type_left->kind != TYPE_COMPOUND_UNION) {
3690                 if (is_type_valid(type_left)) {
3691                         errorf(HERE, "request for member '%Y' in something not a struct or "
3692                                "union, but '%T'", symbol, type_left);
3693                 }
3694                 return create_invalid_expression();
3695         }
3696
3697         declaration_t *const declaration = type_left->compound.declaration;
3698
3699         if(!declaration->init.is_defined) {
3700                 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
3701                        symbol, type_left);
3702                 return create_invalid_expression();
3703         }
3704
3705         declaration_t *iter = declaration->context.declarations;
3706         for( ; iter != NULL; iter = iter->next) {
3707                 if(iter->symbol == symbol) {
3708                         break;
3709                 }
3710         }
3711         if(iter == NULL) {
3712                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
3713                 return create_invalid_expression();
3714         }
3715
3716         /* we always do the auto-type conversions; the & and sizeof parser contains
3717          * code to revert this! */
3718         type_t *expression_type = automatic_type_conversion(iter->type);
3719
3720         select->select.compound_entry = iter;
3721         select->base.datatype         = expression_type;
3722
3723         if(expression_type->kind == TYPE_BITFIELD) {
3724                 expression_t *extract
3725                         = allocate_expression_zero(EXPR_UNARY_BITFIELD_EXTRACT);
3726                 extract->unary.value   = select;
3727                 extract->base.datatype = expression_type->bitfield.base;
3728
3729                 return extract;
3730         }
3731
3732         return select;
3733 }
3734
3735 /**
3736  * Parse a call expression, ie. expression '( ... )'.
3737  *
3738  * @param expression  the function address
3739  */
3740 static expression_t *parse_call_expression(unsigned precedence,
3741                                            expression_t *expression)
3742 {
3743         (void) precedence;
3744         expression_t *result = allocate_expression_zero(EXPR_CALL);
3745
3746         call_expression_t *call = &result->call;
3747         call->function          = expression;
3748
3749         type_t *const orig_type = expression->base.datatype;
3750         type_t *const type      = skip_typeref(orig_type);
3751
3752         function_type_t *function_type = NULL;
3753         if (is_type_pointer(type)) {
3754                 type_t *const to_type = skip_typeref(type->pointer.points_to);
3755
3756                 if (is_type_function(to_type)) {
3757                         function_type             = &to_type->function;
3758                         call->expression.datatype = function_type->return_type;
3759                 }
3760         }
3761
3762         if (function_type == NULL && is_type_valid(type)) {
3763                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
3764         }
3765
3766         /* parse arguments */
3767         eat('(');
3768
3769         if(token.type != ')') {
3770                 call_argument_t *last_argument = NULL;
3771
3772                 while(true) {
3773                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
3774
3775                         argument->expression = parse_assignment_expression();
3776                         if(last_argument == NULL) {
3777                                 call->arguments = argument;
3778                         } else {
3779                                 last_argument->next = argument;
3780                         }
3781                         last_argument = argument;
3782
3783                         if(token.type != ',')
3784                                 break;
3785                         next_token();
3786                 }
3787         }
3788         expect(')');
3789
3790         if(function_type != NULL) {
3791                 function_parameter_t *parameter = function_type->parameters;
3792                 call_argument_t      *argument  = call->arguments;
3793                 for( ; parameter != NULL && argument != NULL;
3794                                 parameter = parameter->next, argument = argument->next) {
3795                         type_t *expected_type = parameter->type;
3796                         /* TODO report context in error messages */
3797                         expression_t *const arg_expr = argument->expression;
3798                         type_t       *const res_type = semantic_assign(expected_type, arg_expr, "function call");
3799                         if (res_type == NULL) {
3800                                 /* TODO improve error message */
3801                                 errorf(arg_expr->base.source_position,
3802                                         "Cannot call function with argument '%E' of type '%T' where type '%T' is expected",
3803                                         arg_expr, arg_expr->base.datatype, expected_type);
3804                         } else {
3805                                 argument->expression = create_implicit_cast(argument->expression, expected_type);
3806                         }
3807                 }
3808                 /* too few parameters */
3809                 if(parameter != NULL) {
3810                         errorf(HERE, "too few arguments to function '%E'", expression);
3811                 } else if(argument != NULL) {
3812                         /* too many parameters */
3813                         if(!function_type->variadic
3814                                         && !function_type->unspecified_parameters) {
3815                                 errorf(HERE, "too many arguments to function '%E'", expression);
3816                         } else {
3817                                 /* do default promotion */
3818                                 for( ; argument != NULL; argument = argument->next) {
3819                                         type_t *type = argument->expression->base.datatype;
3820
3821                                         type = skip_typeref(type);
3822                                         if(is_type_integer(type)) {
3823                                                 type = promote_integer(type);
3824                                         } else if(type == type_float) {
3825                                                 type = type_double;
3826                                         }
3827
3828                                         argument->expression
3829                                                 = create_implicit_cast(argument->expression, type);
3830                                 }
3831
3832                                 check_format(&result->call);
3833                         }
3834                 } else {
3835                         check_format(&result->call);
3836                 }
3837         }
3838
3839         return result;
3840 }
3841
3842 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
3843
3844 static bool same_compound_type(const type_t *type1, const type_t *type2)
3845 {
3846         return
3847                 is_type_compound(type1) &&
3848                 type1->kind == type2->kind &&
3849                 type1->compound.declaration == type2->compound.declaration;
3850 }
3851
3852 /**
3853  * Parse a conditional expression, ie. 'expression ? ... : ...'.
3854  *
3855  * @param expression  the conditional expression
3856  */
3857 static expression_t *parse_conditional_expression(unsigned precedence,
3858                                                   expression_t *expression)
3859 {
3860         eat('?');
3861
3862         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
3863
3864         conditional_expression_t *conditional = &result->conditional;
3865         conditional->condition = expression;
3866
3867         /* 6.5.15.2 */
3868         type_t *const condition_type_orig = expression->base.datatype;
3869         type_t *const condition_type      = skip_typeref(condition_type_orig);
3870         if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
3871                 type_error("expected a scalar type in conditional condition",
3872                            expression->base.source_position, condition_type_orig);
3873         }
3874
3875         expression_t *true_expression = parse_expression();
3876         expect(':');
3877         expression_t *false_expression = parse_sub_expression(precedence);
3878
3879         conditional->true_expression  = true_expression;
3880         conditional->false_expression = false_expression;
3881
3882         type_t *const orig_true_type  = true_expression->base.datatype;
3883         type_t *const orig_false_type = false_expression->base.datatype;
3884         type_t *const true_type       = skip_typeref(orig_true_type);
3885         type_t *const false_type      = skip_typeref(orig_false_type);
3886
3887         /* 6.5.15.3 */
3888         type_t *result_type;
3889         if (is_type_arithmetic(true_type) && is_type_arithmetic(false_type)) {
3890                 result_type = semantic_arithmetic(true_type, false_type);
3891
3892                 true_expression  = create_implicit_cast(true_expression, result_type);
3893                 false_expression = create_implicit_cast(false_expression, result_type);
3894
3895                 conditional->true_expression     = true_expression;
3896                 conditional->false_expression    = false_expression;
3897                 conditional->expression.datatype = result_type;
3898         } else if (same_compound_type(true_type, false_type) || (
3899             is_type_atomic(true_type, ATOMIC_TYPE_VOID) &&
3900             is_type_atomic(false_type, ATOMIC_TYPE_VOID)
3901                 )) {
3902                 /* just take 1 of the 2 types */
3903                 result_type = true_type;
3904         } else if (is_type_pointer(true_type) && is_type_pointer(false_type)
3905                         && pointers_compatible(true_type, false_type)) {
3906                 /* ok */
3907                 result_type = true_type;
3908         } else {
3909                 /* TODO */
3910                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
3911                         type_error_incompatible("while parsing conditional",
3912                                                 expression->base.source_position, true_type,
3913                                                 false_type);
3914                 }
3915                 result_type = type_error_type;
3916         }
3917
3918         conditional->expression.datatype = result_type;
3919         return result;
3920 }
3921
3922 /**
3923  * Parse an extension expression.
3924  */
3925 static expression_t *parse_extension(unsigned precedence)
3926 {
3927         eat(T___extension__);
3928
3929         /* TODO enable extensions */
3930         expression_t *expression = parse_sub_expression(precedence);
3931         /* TODO disable extensions */
3932         return expression;
3933 }
3934
3935 static expression_t *parse_builtin_classify_type(const unsigned precedence)
3936 {
3937         eat(T___builtin_classify_type);
3938
3939         expression_t *result  = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
3940         result->base.datatype = type_int;
3941
3942         expect('(');
3943         expression_t *expression = parse_sub_expression(precedence);
3944         expect(')');
3945         result->classify_type.type_expression = expression;
3946
3947         return result;
3948 }
3949
3950 static void semantic_incdec(unary_expression_t *expression)
3951 {
3952         type_t *const orig_type = expression->value->base.datatype;
3953         type_t *const type      = skip_typeref(orig_type);
3954         if(!is_type_arithmetic(type) && type->kind != TYPE_POINTER) {
3955                 if (is_type_valid(type)) {
3956                         /* TODO: improve error message */
3957                         errorf(HERE, "operation needs an arithmetic or pointer type");
3958                 }
3959                 return;
3960         }
3961
3962         expression->expression.datatype = orig_type;
3963 }
3964
3965 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
3966 {
3967         type_t *const orig_type = expression->value->base.datatype;
3968         type_t *const type      = skip_typeref(orig_type);
3969         if(!is_type_arithmetic(type)) {
3970                 if (is_type_valid(type)) {
3971                         /* TODO: improve error message */
3972                         errorf(HERE, "operation needs an arithmetic type");
3973                 }
3974                 return;
3975         }
3976
3977         expression->expression.datatype = orig_type;
3978 }
3979
3980 static void semantic_unexpr_scalar(unary_expression_t *expression)
3981 {
3982         type_t *const orig_type = expression->value->base.datatype;
3983         type_t *const type      = skip_typeref(orig_type);
3984         if (!is_type_scalar(type)) {
3985                 if (is_type_valid(type)) {
3986                         errorf(HERE, "operand of ! must be of scalar type");
3987                 }
3988                 return;
3989         }
3990
3991         expression->expression.datatype = orig_type;
3992 }
3993
3994 static void semantic_unexpr_integer(unary_expression_t *expression)
3995 {
3996         type_t *const orig_type = expression->value->base.datatype;
3997         type_t *const type      = skip_typeref(orig_type);
3998         if (!is_type_integer(type)) {
3999                 if (is_type_valid(type)) {
4000                         errorf(HERE, "operand of ~ must be of integer type");
4001                 }
4002                 return;
4003         }
4004
4005         expression->expression.datatype = orig_type;
4006 }
4007
4008 static void semantic_dereference(unary_expression_t *expression)
4009 {
4010         type_t *const orig_type = expression->value->base.datatype;
4011         type_t *const type      = skip_typeref(orig_type);
4012         if(!is_type_pointer(type)) {
4013                 if (is_type_valid(type)) {
4014                         errorf(HERE, "Unary '*' needs pointer or arrray type, but type '%T' given", orig_type);
4015                 }
4016                 return;
4017         }
4018
4019         type_t *result_type = type->pointer.points_to;
4020         result_type = automatic_type_conversion(result_type);
4021         expression->expression.datatype = result_type;
4022 }
4023
4024 /**
4025  * Check the semantic of the address taken expression.
4026  */
4027 static void semantic_take_addr(unary_expression_t *expression)
4028 {
4029         expression_t *value  = expression->value;
4030         value->base.datatype = revert_automatic_type_conversion(value);
4031
4032         type_t *orig_type = value->base.datatype;
4033         if(!is_type_valid(orig_type))
4034                 return;
4035
4036         if(value->kind == EXPR_REFERENCE) {
4037                 declaration_t *const declaration = value->reference.declaration;
4038                 if(declaration != NULL) {
4039                         if (declaration->storage_class == STORAGE_CLASS_REGISTER) {
4040                                 errorf(expression->expression.source_position,
4041                                         "address of register variable '%Y' requested",
4042                                         declaration->symbol);
4043                         }
4044                         declaration->address_taken = 1;
4045                 }
4046         }
4047
4048         expression->expression.datatype = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
4049 }
4050
4051 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc)   \
4052 static expression_t *parse_##unexpression_type(unsigned precedence)            \
4053 {                                                                              \
4054         eat(token_type);                                                           \
4055                                                                                    \
4056         expression_t *unary_expression                                             \
4057                 = allocate_expression_zero(unexpression_type);                         \
4058         unary_expression->base.source_position = HERE;                             \
4059         unary_expression->unary.value = parse_sub_expression(precedence);          \
4060                                                                                    \
4061         sfunc(&unary_expression->unary);                                           \
4062                                                                                    \
4063         return unary_expression;                                                   \
4064 }
4065
4066 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
4067                                semantic_unexpr_arithmetic)
4068 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
4069                                semantic_unexpr_arithmetic)
4070 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
4071                                semantic_unexpr_scalar)
4072 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
4073                                semantic_dereference)
4074 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
4075                                semantic_take_addr)
4076 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
4077                                semantic_unexpr_integer)
4078 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
4079                                semantic_incdec)
4080 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
4081                                semantic_incdec)
4082
4083 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
4084                                                sfunc)                         \
4085 static expression_t *parse_##unexpression_type(unsigned precedence,           \
4086                                                expression_t *left)            \
4087 {                                                                             \
4088         (void) precedence;                                                        \
4089         eat(token_type);                                                          \
4090                                                                               \
4091         expression_t *unary_expression                                            \
4092                 = allocate_expression_zero(unexpression_type);                        \
4093         unary_expression->unary.value = left;                                     \
4094                                                                                   \
4095         sfunc(&unary_expression->unary);                                          \
4096                                                                               \
4097         return unary_expression;                                                  \
4098 }
4099
4100 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
4101                                        EXPR_UNARY_POSTFIX_INCREMENT,
4102                                        semantic_incdec)
4103 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
4104                                        EXPR_UNARY_POSTFIX_DECREMENT,
4105                                        semantic_incdec)
4106
4107 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
4108 {
4109         /* TODO: handle complex + imaginary types */
4110
4111         /* Â§ 6.3.1.8 Usual arithmetic conversions */
4112         if(type_left == type_long_double || type_right == type_long_double) {
4113                 return type_long_double;
4114         } else if(type_left == type_double || type_right == type_double) {
4115                 return type_double;
4116         } else if(type_left == type_float || type_right == type_float) {
4117                 return type_float;
4118         }
4119
4120         type_right = promote_integer(type_right);
4121         type_left  = promote_integer(type_left);
4122
4123         if(type_left == type_right)
4124                 return type_left;
4125
4126         bool signed_left  = is_type_signed(type_left);
4127         bool signed_right = is_type_signed(type_right);
4128         int  rank_left    = get_rank(type_left);
4129         int  rank_right   = get_rank(type_right);
4130         if(rank_left < rank_right) {
4131                 if(signed_left == signed_right || !signed_right) {
4132                         return type_right;
4133                 } else {
4134                         return type_left;
4135                 }
4136         } else {
4137                 if(signed_left == signed_right || !signed_left) {
4138                         return type_left;
4139                 } else {
4140                         return type_right;
4141                 }
4142         }
4143 }
4144
4145 /**
4146  * Check the semantic restrictions for a binary expression.
4147  */
4148 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
4149 {
4150         expression_t *const left            = expression->left;
4151         expression_t *const right           = expression->right;
4152         type_t       *const orig_type_left  = left->base.datatype;
4153         type_t       *const orig_type_right = right->base.datatype;
4154         type_t       *const type_left       = skip_typeref(orig_type_left);
4155         type_t       *const type_right      = skip_typeref(orig_type_right);
4156
4157         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4158                 /* TODO: improve error message */
4159                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4160                         errorf(HERE, "operation needs arithmetic types");
4161                 }
4162                 return;
4163         }
4164
4165         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4166         expression->left  = create_implicit_cast(left, arithmetic_type);
4167         expression->right = create_implicit_cast(right, arithmetic_type);
4168         expression->expression.datatype = arithmetic_type;
4169 }
4170
4171 static void semantic_shift_op(binary_expression_t *expression)
4172 {
4173         expression_t *const left            = expression->left;
4174         expression_t *const right           = expression->right;
4175         type_t       *const orig_type_left  = left->base.datatype;
4176         type_t       *const orig_type_right = right->base.datatype;
4177         type_t       *      type_left       = skip_typeref(orig_type_left);
4178         type_t       *      type_right      = skip_typeref(orig_type_right);
4179
4180         if(!is_type_integer(type_left) || !is_type_integer(type_right)) {
4181                 /* TODO: improve error message */
4182                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4183                         errorf(HERE, "operation needs integer types");
4184                 }
4185                 return;
4186         }
4187
4188         type_left  = promote_integer(type_left);
4189         type_right = promote_integer(type_right);
4190
4191         expression->left  = create_implicit_cast(left, type_left);
4192         expression->right = create_implicit_cast(right, type_right);
4193         expression->expression.datatype = type_left;
4194 }
4195
4196 static void semantic_add(binary_expression_t *expression)
4197 {
4198         expression_t *const left            = expression->left;
4199         expression_t *const right           = expression->right;
4200         type_t       *const orig_type_left  = left->base.datatype;
4201         type_t       *const orig_type_right = right->base.datatype;
4202         type_t       *const type_left       = skip_typeref(orig_type_left);
4203         type_t       *const type_right      = skip_typeref(orig_type_right);
4204
4205         /* Â§ 5.6.5 */
4206         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4207                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4208                 expression->left  = create_implicit_cast(left, arithmetic_type);
4209                 expression->right = create_implicit_cast(right, arithmetic_type);
4210                 expression->expression.datatype = arithmetic_type;
4211                 return;
4212         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4213                 expression->expression.datatype = type_left;
4214         } else if(is_type_pointer(type_right) && is_type_integer(type_left)) {
4215                 expression->expression.datatype = type_right;
4216         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4217                 errorf(HERE, "invalid operands to binary + ('%T', '%T')", orig_type_left, orig_type_right);
4218         }
4219 }
4220
4221 static void semantic_sub(binary_expression_t *expression)
4222 {
4223         expression_t *const left            = expression->left;
4224         expression_t *const right           = expression->right;
4225         type_t       *const orig_type_left  = left->base.datatype;
4226         type_t       *const orig_type_right = right->base.datatype;
4227         type_t       *const type_left       = skip_typeref(orig_type_left);
4228         type_t       *const type_right      = skip_typeref(orig_type_right);
4229
4230         /* Â§ 5.6.5 */
4231         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4232                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4233                 expression->left  = create_implicit_cast(left, arithmetic_type);
4234                 expression->right = create_implicit_cast(right, arithmetic_type);
4235                 expression->expression.datatype = arithmetic_type;
4236                 return;
4237         } else if(is_type_pointer(type_left) && is_type_integer(type_right)) {
4238                 expression->expression.datatype = type_left;
4239         } else if(is_type_pointer(type_left) && is_type_pointer(type_right)) {
4240                 if(!pointers_compatible(type_left, type_right)) {
4241                         errorf(HERE, "pointers to incompatible objects to binary '-' ('%T', '%T')", orig_type_left, orig_type_right);
4242                 } else {
4243                         expression->expression.datatype = type_ptrdiff_t;
4244                 }
4245         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4246                 errorf(HERE, "invalid operands to binary '-' ('%T', '%T')", orig_type_left, orig_type_right);
4247         }
4248 }
4249
4250 static void semantic_comparison(binary_expression_t *expression)
4251 {
4252         expression_t *left            = expression->left;
4253         expression_t *right           = expression->right;
4254         type_t       *orig_type_left  = left->base.datatype;
4255         type_t       *orig_type_right = right->base.datatype;
4256
4257         type_t *type_left  = skip_typeref(orig_type_left);
4258         type_t *type_right = skip_typeref(orig_type_right);
4259
4260         /* TODO non-arithmetic types */
4261         if(is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4262                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
4263                 expression->left  = create_implicit_cast(left, arithmetic_type);
4264                 expression->right = create_implicit_cast(right, arithmetic_type);
4265                 expression->expression.datatype = arithmetic_type;
4266         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
4267                 /* TODO check compatibility */
4268         } else if (is_type_pointer(type_left)) {
4269                 expression->right = create_implicit_cast(right, type_left);
4270         } else if (is_type_pointer(type_right)) {
4271                 expression->left = create_implicit_cast(left, type_right);
4272         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4273                 type_error_incompatible("invalid operands in comparison",
4274                                         token.source_position, type_left, type_right);
4275         }
4276         expression->expression.datatype = type_int;
4277 }
4278
4279 static void semantic_arithmetic_assign(binary_expression_t *expression)
4280 {
4281         expression_t *left            = expression->left;
4282         expression_t *right           = expression->right;
4283         type_t       *orig_type_left  = left->base.datatype;
4284         type_t       *orig_type_right = right->base.datatype;
4285
4286         type_t *type_left  = skip_typeref(orig_type_left);
4287         type_t *type_right = skip_typeref(orig_type_right);
4288
4289         if(!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
4290                 /* TODO: improve error message */
4291                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4292                         errorf(HERE, "operation needs arithmetic types");
4293                 }
4294                 return;
4295         }
4296
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 *arithmetic_type = semantic_arithmetic(type_left, type_right);
4302         expression->right       = create_implicit_cast(right, arithmetic_type);
4303         expression->expression.datatype = type_left;
4304 }
4305
4306 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
4307 {
4308         expression_t *const left            = expression->left;
4309         expression_t *const right           = expression->right;
4310         type_t       *const orig_type_left  = left->base.datatype;
4311         type_t       *const orig_type_right = right->base.datatype;
4312         type_t       *const type_left       = skip_typeref(orig_type_left);
4313         type_t       *const type_right      = skip_typeref(orig_type_right);
4314
4315         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
4316                 /* combined instructions are tricky. We can't create an implicit cast on
4317                  * the left side, because we need the uncasted form for the store.
4318                  * The ast2firm pass has to know that left_type must be right_type
4319                  * for the arithmetic operation and create a cast by itself */
4320                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
4321                 expression->right = create_implicit_cast(right, arithmetic_type);
4322                 expression->expression.datatype = type_left;
4323         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
4324                 expression->expression.datatype = type_left;
4325         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
4326                 errorf(HERE, "incompatible types '%T' and '%T' in assignment", orig_type_left, orig_type_right);
4327         }
4328 }
4329
4330 /**
4331  * Check the semantic restrictions of a logical expression.
4332  */
4333 static void semantic_logical_op(binary_expression_t *expression)
4334 {
4335         expression_t *const left            = expression->left;
4336         expression_t *const right           = expression->right;
4337         type_t       *const orig_type_left  = left->base.datatype;
4338         type_t       *const orig_type_right = right->base.datatype;
4339         type_t       *const type_left       = skip_typeref(orig_type_left);
4340         type_t       *const type_right      = skip_typeref(orig_type_right);
4341
4342         if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
4343                 /* TODO: improve error message */
4344                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
4345                         errorf(HERE, "operation needs scalar types");
4346                 }
4347                 return;
4348         }
4349
4350         expression->expression.datatype = type_int;
4351 }
4352
4353 /**
4354  * Checks if a compound type has constant fields.
4355  */
4356 static bool has_const_fields(const compound_type_t *type)
4357 {
4358         const context_t     *context = &type->declaration->context;
4359         const declaration_t *declaration = context->declarations;
4360
4361         for (; declaration != NULL; declaration = declaration->next) {
4362                 if (declaration->namespc != NAMESPACE_NORMAL)
4363                         continue;
4364
4365                 const type_t *decl_type = skip_typeref(declaration->type);
4366                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
4367                         return true;
4368         }
4369         /* TODO */
4370         return false;
4371 }
4372
4373 /**
4374  * Check the semantic restrictions of a binary assign expression.
4375  */
4376 static void semantic_binexpr_assign(binary_expression_t *expression)
4377 {
4378         expression_t *left           = expression->left;
4379         type_t       *orig_type_left = left->base.datatype;
4380
4381         type_t *type_left = revert_automatic_type_conversion(left);
4382         type_left         = skip_typeref(orig_type_left);
4383
4384         /* must be a modifiable lvalue */
4385         if (is_type_array(type_left)) {
4386                 errorf(HERE, "cannot assign to arrays ('%E')", left);
4387                 return;
4388         }
4389         if(type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
4390                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
4391                        orig_type_left);
4392                 return;
4393         }
4394         if(is_type_incomplete(type_left)) {
4395                 errorf(HERE,
4396                        "left-hand side of assignment '%E' has incomplete type '%T'",
4397                        left, orig_type_left);
4398                 return;
4399         }
4400         if(is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
4401                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
4402                        left, orig_type_left);
4403                 return;
4404         }
4405
4406         type_t *const res_type = semantic_assign(orig_type_left, expression->right,
4407                                                  "assignment");
4408         if (res_type == NULL) {
4409                 errorf(expression->expression.source_position,
4410                         "cannot assign to '%T' from '%T'",
4411                         orig_type_left, expression->right->base.datatype);
4412         } else {
4413                 expression->right = create_implicit_cast(expression->right, res_type);
4414         }
4415
4416         expression->expression.datatype = orig_type_left;
4417 }
4418
4419 static bool expression_has_effect(const expression_t *const expr)
4420 {
4421         switch (expr->kind) {
4422                 case EXPR_UNKNOWN:                   break;
4423                 case EXPR_INVALID:                   break;
4424                 case EXPR_REFERENCE:                 return false;
4425                 case EXPR_CONST:                     return false;
4426                 case EXPR_STRING_LITERAL:            return false;
4427                 case EXPR_WIDE_STRING_LITERAL:       return false;
4428                 case EXPR_CALL: {
4429                         const call_expression_t *const call = &expr->call;
4430                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
4431                                 return true;
4432
4433                         switch (call->function->builtin_symbol.symbol->ID) {
4434                                 case T___builtin_va_end: return true;
4435                                 default:                 return false;
4436                         }
4437                 }
4438                 case EXPR_CONDITIONAL: {
4439                         const conditional_expression_t *const cond = &expr->conditional;
4440                         return
4441                                 expression_has_effect(cond->true_expression) &&
4442                                 expression_has_effect(cond->false_expression);
4443                 }
4444                 case EXPR_SELECT:                    return false;
4445                 case EXPR_ARRAY_ACCESS:              return false;
4446                 case EXPR_SIZEOF:                    return false;
4447                 case EXPR_CLASSIFY_TYPE:             return false;
4448                 case EXPR_ALIGNOF:                   return false;
4449
4450                 case EXPR_FUNCTION:                  return false;
4451                 case EXPR_PRETTY_FUNCTION:           return false;
4452                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
4453                 case EXPR_BUILTIN_CONSTANT_P:        return false;
4454                 case EXPR_BUILTIN_PREFETCH:          return true;
4455                 case EXPR_OFFSETOF:                  return false;
4456                 case EXPR_VA_START:                  return true;
4457                 case EXPR_VA_ARG:                    return true;
4458                 case EXPR_STATEMENT:                 return true; // TODO
4459
4460                 case EXPR_UNARY_NEGATE:              return false;
4461                 case EXPR_UNARY_PLUS:                return false;
4462                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
4463                 case EXPR_UNARY_NOT:                 return false;
4464                 case EXPR_UNARY_DEREFERENCE:         return false;
4465                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
4466                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
4467                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
4468                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
4469                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
4470                 case EXPR_UNARY_CAST:
4471                         return is_type_atomic(expr->base.datatype, ATOMIC_TYPE_VOID);
4472                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
4473                 case EXPR_UNARY_ASSUME:              return true;
4474                 case EXPR_UNARY_BITFIELD_EXTRACT:    return false;
4475
4476                 case EXPR_BINARY_ADD:                return false;
4477                 case EXPR_BINARY_SUB:                return false;
4478                 case EXPR_BINARY_MUL:                return false;
4479                 case EXPR_BINARY_DIV:                return false;
4480                 case EXPR_BINARY_MOD:                return false;
4481                 case EXPR_BINARY_EQUAL:              return false;
4482                 case EXPR_BINARY_NOTEQUAL:           return false;
4483                 case EXPR_BINARY_LESS:               return false;
4484                 case EXPR_BINARY_LESSEQUAL:          return false;
4485                 case EXPR_BINARY_GREATER:            return false;
4486                 case EXPR_BINARY_GREATEREQUAL:       return false;
4487                 case EXPR_BINARY_BITWISE_AND:        return false;
4488                 case EXPR_BINARY_BITWISE_OR:         return false;
4489                 case EXPR_BINARY_BITWISE_XOR:        return false;
4490                 case EXPR_BINARY_LOGICAL_AND:        return false;
4491                 case EXPR_BINARY_LOGICAL_OR:         return false;
4492                 case EXPR_BINARY_SHIFTLEFT:          return false;
4493                 case EXPR_BINARY_SHIFTRIGHT:         return false;
4494                 case EXPR_BINARY_ASSIGN:             return true;
4495                 case EXPR_BINARY_MUL_ASSIGN:         return true;
4496                 case EXPR_BINARY_DIV_ASSIGN:         return true;
4497                 case EXPR_BINARY_MOD_ASSIGN:         return true;
4498                 case EXPR_BINARY_ADD_ASSIGN:         return true;
4499                 case EXPR_BINARY_SUB_ASSIGN:         return true;
4500                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
4501                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
4502                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
4503                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
4504                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
4505                 case EXPR_BINARY_COMMA:
4506                         return expression_has_effect(expr->binary.right);
4507
4508                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
4509                 case EXPR_BINARY_ISGREATER:          return false;
4510                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
4511                 case EXPR_BINARY_ISLESS:             return false;
4512                 case EXPR_BINARY_ISLESSEQUAL:        return false;
4513                 case EXPR_BINARY_ISLESSGREATER:      return false;
4514                 case EXPR_BINARY_ISUNORDERED:        return false;
4515         }
4516
4517         panic("unexpected statement");
4518 }
4519
4520 static void semantic_comma(binary_expression_t *expression)
4521 {
4522         if (warning.unused_value) {
4523                 const expression_t *const left = expression->left;
4524                 if (!expression_has_effect(left)) {
4525                         warningf(left->base.source_position, "left-hand operand of comma expression has no effect");
4526                 }
4527         }
4528         expression->expression.datatype = expression->right->base.datatype;
4529 }
4530
4531 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, sfunc, lr)  \
4532 static expression_t *parse_##binexpression_type(unsigned precedence,      \
4533                                                 expression_t *left)       \
4534 {                                                                         \
4535         eat(token_type);                                                      \
4536                                                                           \
4537         expression_t *right = parse_sub_expression(precedence + lr);          \
4538                                                                           \
4539         expression_t *binexpr = allocate_expression_zero(binexpression_type); \
4540         binexpr->binary.left  = left;                                         \
4541         binexpr->binary.right = right;                                        \
4542         sfunc(&binexpr->binary);                                              \
4543                                                                           \
4544         return binexpr;                                                       \
4545 }
4546
4547 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA,    semantic_comma, 1)
4548 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL,      semantic_binexpr_arithmetic, 1)
4549 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV,      semantic_binexpr_arithmetic, 1)
4550 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD,      semantic_binexpr_arithmetic, 1)
4551 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD,      semantic_add, 1)
4552 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB,      semantic_sub, 1)
4553 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS,     semantic_comparison, 1)
4554 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER,  semantic_comparison, 1)
4555 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN,   semantic_binexpr_assign, 0)
4556
4557 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,
4558                       semantic_comparison, 1)
4559 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,
4560                       semantic_comparison, 1)
4561 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,
4562                       semantic_comparison, 1)
4563 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,
4564                       semantic_comparison, 1)
4565
4566 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND,
4567                       semantic_binexpr_arithmetic, 1)
4568 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR,
4569                       semantic_binexpr_arithmetic, 1)
4570 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR,
4571                       semantic_binexpr_arithmetic, 1)
4572 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND,
4573                       semantic_logical_op, 1)
4574 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR,
4575                       semantic_logical_op, 1)
4576 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT,
4577                       semantic_shift_op, 1)
4578 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT,
4579                       semantic_shift_op, 1)
4580 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN,
4581                       semantic_arithmetic_addsubb_assign, 0)
4582 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN,
4583                       semantic_arithmetic_addsubb_assign, 0)
4584 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN,
4585                       semantic_arithmetic_assign, 0)
4586 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN,
4587                       semantic_arithmetic_assign, 0)
4588 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN,
4589                       semantic_arithmetic_assign, 0)
4590 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN,
4591                       semantic_arithmetic_assign, 0)
4592 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4593                       semantic_arithmetic_assign, 0)
4594 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN,
4595                       semantic_arithmetic_assign, 0)
4596 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN,
4597                       semantic_arithmetic_assign, 0)
4598 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN,
4599                       semantic_arithmetic_assign, 0)
4600
4601 static expression_t *parse_sub_expression(unsigned precedence)
4602 {
4603         if(token.type < 0) {
4604                 return expected_expression_error();
4605         }
4606
4607         expression_parser_function_t *parser
4608                 = &expression_parsers[token.type];
4609         source_position_t             source_position = token.source_position;
4610         expression_t                 *left;
4611
4612         if(parser->parser != NULL) {
4613                 left = parser->parser(parser->precedence);
4614         } else {
4615                 left = parse_primary_expression();
4616         }
4617         assert(left != NULL);
4618         left->base.source_position = source_position;
4619
4620         while(true) {
4621                 if(token.type < 0) {
4622                         return expected_expression_error();
4623                 }
4624
4625                 parser = &expression_parsers[token.type];
4626                 if(parser->infix_parser == NULL)
4627                         break;
4628                 if(parser->infix_precedence < precedence)
4629                         break;
4630
4631                 left = parser->infix_parser(parser->infix_precedence, left);
4632
4633                 assert(left != NULL);
4634                 assert(left->kind != EXPR_UNKNOWN);
4635                 left->base.source_position = source_position;
4636         }
4637
4638         return left;
4639 }
4640
4641 /**
4642  * Parse an expression.
4643  */
4644 static expression_t *parse_expression(void)
4645 {
4646         return parse_sub_expression(1);
4647 }
4648
4649 /**
4650  * Register a parser for a prefix-like operator with given precedence.
4651  *
4652  * @param parser      the parser function
4653  * @param token_type  the token type of the prefix token
4654  * @param precedence  the precedence of the operator
4655  */
4656 static void register_expression_parser(parse_expression_function parser,
4657                                        int token_type, unsigned precedence)
4658 {
4659         expression_parser_function_t *entry = &expression_parsers[token_type];
4660
4661         if(entry->parser != NULL) {
4662                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4663                 panic("trying to register multiple expression parsers for a token");
4664         }
4665         entry->parser     = parser;
4666         entry->precedence = precedence;
4667 }
4668
4669 /**
4670  * Register a parser for an infix operator with given precedence.
4671  *
4672  * @param parser      the parser function
4673  * @param token_type  the token type of the infix operator
4674  * @param precedence  the precedence of the operator
4675  */
4676 static void register_infix_parser(parse_expression_infix_function parser,
4677                 int token_type, unsigned precedence)
4678 {
4679         expression_parser_function_t *entry = &expression_parsers[token_type];
4680
4681         if(entry->infix_parser != NULL) {
4682                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
4683                 panic("trying to register multiple infix expression parsers for a "
4684                       "token");
4685         }
4686         entry->infix_parser     = parser;
4687         entry->infix_precedence = precedence;
4688 }
4689
4690 /**
4691  * Initialize the expression parsers.
4692  */
4693 static void init_expression_parsers(void)
4694 {
4695         memset(&expression_parsers, 0, sizeof(expression_parsers));
4696
4697         register_infix_parser(parse_array_expression,         '[',              30);
4698         register_infix_parser(parse_call_expression,          '(',              30);
4699         register_infix_parser(parse_select_expression,        '.',              30);
4700         register_infix_parser(parse_select_expression,        T_MINUSGREATER,   30);
4701         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,
4702                                                               T_PLUSPLUS,       30);
4703         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,
4704                                                               T_MINUSMINUS,     30);
4705
4706         register_infix_parser(parse_EXPR_BINARY_MUL,          '*',              16);
4707         register_infix_parser(parse_EXPR_BINARY_DIV,          '/',              16);
4708         register_infix_parser(parse_EXPR_BINARY_MOD,          '%',              16);
4709         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,    T_LESSLESS,       16);
4710         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,   T_GREATERGREATER, 16);
4711         register_infix_parser(parse_EXPR_BINARY_ADD,          '+',              15);
4712         register_infix_parser(parse_EXPR_BINARY_SUB,          '-',              15);
4713         register_infix_parser(parse_EXPR_BINARY_LESS,         '<',              14);
4714         register_infix_parser(parse_EXPR_BINARY_GREATER,      '>',              14);
4715         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,    T_LESSEQUAL,      14);
4716         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL,   14);
4717         register_infix_parser(parse_EXPR_BINARY_EQUAL,        T_EQUALEQUAL,     13);
4718         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,
4719                                                     T_EXCLAMATIONMARKEQUAL, 13);
4720         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,  '&',              12);
4721         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,  '^',              11);
4722         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,   '|',              10);
4723         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,  T_ANDAND,          9);
4724         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,   T_PIPEPIPE,        8);
4725         register_infix_parser(parse_conditional_expression,   '?',               7);
4726         register_infix_parser(parse_EXPR_BINARY_ASSIGN,       '=',               2);
4727         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,   T_PLUSEQUAL,       2);
4728         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,   T_MINUSEQUAL,      2);
4729         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,   T_ASTERISKEQUAL,   2);
4730         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,   T_SLASHEQUAL,      2);
4731         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,   T_PERCENTEQUAL,    2);
4732         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,
4733                                                                 T_LESSLESSEQUAL, 2);
4734         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,
4735                                                           T_GREATERGREATEREQUAL, 2);
4736         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN,
4737                                                                      T_ANDEQUAL, 2);
4738         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,
4739                                                                     T_PIPEEQUAL, 2);
4740         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN,
4741                                                                    T_CARETEQUAL, 2);
4742
4743         register_infix_parser(parse_EXPR_BINARY_COMMA,        ',',               1);
4744
4745         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-',      25);
4746         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+',      25);
4747         register_expression_parser(parse_EXPR_UNARY_NOT,              '!',      25);
4748         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~',      25);
4749         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*',      25);
4750         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&',      25);
4751         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT,
4752                                                                   T_PLUSPLUS,   25);
4753         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT,
4754                                                                   T_MINUSMINUS, 25);
4755         register_expression_parser(parse_sizeof,                  T_sizeof,     25);
4756         register_expression_parser(parse_extension,            T___extension__, 25);
4757         register_expression_parser(parse_builtin_classify_type,
4758                                                      T___builtin_classify_type, 25);
4759 }
4760
4761 /**
4762  * Parse a asm statement constraints specification.
4763  */
4764 static asm_constraint_t *parse_asm_constraints(void)
4765 {
4766         asm_constraint_t *result = NULL;
4767         asm_constraint_t *last   = NULL;
4768
4769         while(token.type == T_STRING_LITERAL || token.type == '[') {
4770                 asm_constraint_t *constraint = allocate_ast_zero(sizeof(constraint[0]));
4771                 memset(constraint, 0, sizeof(constraint[0]));
4772
4773                 if(token.type == '[') {
4774                         eat('[');
4775                         if(token.type != T_IDENTIFIER) {
4776                                 parse_error_expected("while parsing asm constraint",
4777                                                      T_IDENTIFIER, 0);
4778                                 return NULL;
4779                         }
4780                         constraint->symbol = token.v.symbol;
4781
4782                         expect(']');
4783                 }
4784
4785                 constraint->constraints = parse_string_literals();
4786                 expect('(');
4787                 constraint->expression = parse_expression();
4788                 expect(')');
4789
4790                 if(last != NULL) {
4791                         last->next = constraint;
4792                 } else {
4793                         result = constraint;
4794                 }
4795                 last = constraint;
4796
4797                 if(token.type != ',')
4798                         break;
4799                 eat(',');
4800         }
4801
4802         return result;
4803 }
4804
4805 /**
4806  * Parse a asm statement clobber specification.
4807  */
4808 static asm_clobber_t *parse_asm_clobbers(void)
4809 {
4810         asm_clobber_t *result = NULL;
4811         asm_clobber_t *last   = NULL;
4812
4813         while(token.type == T_STRING_LITERAL) {
4814                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
4815                 clobber->clobber       = parse_string_literals();
4816
4817                 if(last != NULL) {
4818                         last->next = clobber;
4819                 } else {
4820                         result = clobber;
4821                 }
4822                 last = clobber;
4823
4824                 if(token.type != ',')
4825                         break;
4826                 eat(',');
4827         }
4828
4829         return result;
4830 }
4831
4832 /**
4833  * Parse an asm statement.
4834  */
4835 static statement_t *parse_asm_statement(void)
4836 {
4837         eat(T_asm);
4838
4839         statement_t *statement          = allocate_statement_zero(STATEMENT_ASM);
4840         statement->base.source_position = token.source_position;
4841
4842         asm_statement_t *asm_statement = &statement->asms;
4843
4844         if(token.type == T_volatile) {
4845                 next_token();
4846                 asm_statement->is_volatile = true;
4847         }
4848
4849         expect('(');
4850         asm_statement->asm_text = parse_string_literals();
4851
4852         if(token.type != ':')
4853                 goto end_of_asm;
4854         eat(':');
4855
4856         asm_statement->inputs = parse_asm_constraints();
4857         if(token.type != ':')
4858                 goto end_of_asm;
4859         eat(':');
4860
4861         asm_statement->outputs = parse_asm_constraints();
4862         if(token.type != ':')
4863                 goto end_of_asm;
4864         eat(':');
4865
4866         asm_statement->clobbers = parse_asm_clobbers();
4867
4868 end_of_asm:
4869         expect(')');
4870         expect(';');
4871         return statement;
4872 }
4873
4874 /**
4875  * Parse a case statement.
4876  */
4877 static statement_t *parse_case_statement(void)
4878 {
4879         eat(T_case);
4880
4881         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4882
4883         statement->base.source_position  = token.source_position;
4884         statement->case_label.expression = parse_expression();
4885
4886         expect(':');
4887
4888         if (! is_constant_expression(statement->case_label.expression)) {
4889                 errorf(statement->base.source_position,
4890                         "case label does not reduce to an integer constant");
4891         } else {
4892                 /* TODO: check if the case label is already known */
4893                 if (current_switch != NULL) {
4894                         /* link all cases into the switch statement */
4895                         if (current_switch->last_case == NULL) {
4896                                 current_switch->first_case =
4897                                 current_switch->last_case  = &statement->case_label;
4898                         } else {
4899                                 current_switch->last_case->next = &statement->case_label;
4900                         }
4901                 } else {
4902                         errorf(statement->base.source_position,
4903                                 "case label not within a switch statement");
4904                 }
4905         }
4906         statement->case_label.label_statement = parse_statement();
4907
4908         return statement;
4909 }
4910
4911 /**
4912  * Finds an existing default label of a switch statement.
4913  */
4914 static case_label_statement_t *
4915 find_default_label(const switch_statement_t *statement)
4916 {
4917         for (case_label_statement_t *label = statement->first_case;
4918              label != NULL;
4919                  label = label->next) {
4920                 if (label->expression == NULL)
4921                         return label;
4922         }
4923         return NULL;
4924 }
4925
4926 /**
4927  * Parse a default statement.
4928  */
4929 static statement_t *parse_default_statement(void)
4930 {
4931         eat(T_default);
4932
4933         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
4934
4935         statement->base.source_position = token.source_position;
4936
4937         expect(':');
4938         if (current_switch != NULL) {
4939                 const case_label_statement_t *def_label = find_default_label(current_switch);
4940                 if (def_label != NULL) {
4941                         errorf(HERE, "multiple default labels in one switch");
4942                         errorf(def_label->statement.source_position,
4943                                 "this is the first default label");
4944                 } else {
4945                         /* link all cases into the switch statement */
4946                         if (current_switch->last_case == NULL) {
4947                                 current_switch->first_case =
4948                                         current_switch->last_case  = &statement->case_label;
4949                         } else {
4950                                 current_switch->last_case->next = &statement->case_label;
4951                         }
4952                 }
4953         } else {
4954                 errorf(statement->base.source_position,
4955                         "'default' label not within a switch statement");
4956         }
4957         statement->label.label_statement = parse_statement();
4958
4959         return statement;
4960 }
4961
4962 /**
4963  * Return the declaration for a given label symbol or create a new one.
4964  */
4965 static declaration_t *get_label(symbol_t *symbol)
4966 {
4967         declaration_t *candidate = get_declaration(symbol, NAMESPACE_LABEL);
4968         assert(current_function != NULL);
4969         /* if we found a label in the same function, then we already created the
4970          * declaration */
4971         if(candidate != NULL
4972                         && candidate->parent_context == &current_function->context) {
4973                 return candidate;
4974         }
4975
4976         /* otherwise we need to create a new one */
4977         declaration_t *const declaration = allocate_declaration_zero();
4978         declaration->namespc       = NAMESPACE_LABEL;
4979         declaration->symbol        = symbol;
4980
4981         label_push(declaration);
4982
4983         return declaration;
4984 }
4985
4986 /**
4987  * Parse a label statement.
4988  */
4989 static statement_t *parse_label_statement(void)
4990 {
4991         assert(token.type == T_IDENTIFIER);
4992         symbol_t *symbol = token.v.symbol;
4993         next_token();
4994
4995         declaration_t *label = get_label(symbol);
4996
4997         /* if source position is already set then the label is defined twice,
4998          * otherwise it was just mentioned in a goto so far */
4999         if(label->source_position.input_name != NULL) {
5000                 errorf(HERE, "duplicate label '%Y'", symbol);
5001                 errorf(label->source_position, "previous definition of '%Y' was here",
5002                        symbol);
5003         } else {
5004                 label->source_position = token.source_position;
5005         }
5006
5007         label_statement_t *label_statement = allocate_ast_zero(sizeof(label[0]));
5008
5009         label_statement->statement.kind            = STATEMENT_LABEL;
5010         label_statement->statement.source_position = token.source_position;
5011         label_statement->label                     = label;
5012
5013         eat(':');
5014
5015         if(token.type == '}') {
5016                 /* TODO only warn? */
5017                 errorf(HERE, "label at end of compound statement");
5018                 return (statement_t*) label_statement;
5019         } else {
5020                 label_statement->label_statement = parse_statement();
5021         }
5022
5023         return (statement_t*) label_statement;
5024 }
5025
5026 /**
5027  * Parse an if statement.
5028  */
5029 static statement_t *parse_if(void)
5030 {
5031         eat(T_if);
5032
5033         if_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5034         statement->statement.kind            = STATEMENT_IF;
5035         statement->statement.source_position = token.source_position;
5036
5037         expect('(');
5038         statement->condition = parse_expression();
5039         expect(')');
5040
5041         statement->true_statement = parse_statement();
5042         if(token.type == T_else) {
5043                 next_token();
5044                 statement->false_statement = parse_statement();
5045         }
5046
5047         return (statement_t*) statement;
5048 }
5049
5050 /**
5051  * Parse a switch statement.
5052  */
5053 static statement_t *parse_switch(void)
5054 {
5055         eat(T_switch);
5056
5057         switch_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5058         statement->statement.kind            = STATEMENT_SWITCH;
5059         statement->statement.source_position = token.source_position;
5060
5061         expect('(');
5062         expression_t *const expr = parse_expression();
5063         type_t       *      type = skip_typeref(expr->base.datatype);
5064         if (is_type_integer(type)) {
5065                 type = promote_integer(type);
5066         } else if (is_type_valid(type)) {
5067                 errorf(expr->base.source_position, "switch quantity is not an integer, but '%T'", type);
5068                 type = type_error_type;
5069         }
5070         statement->expression = create_implicit_cast(expr, type);
5071         expect(')');
5072
5073         switch_statement_t *rem = current_switch;
5074         current_switch  = statement;
5075         statement->body = parse_statement();
5076         current_switch  = rem;
5077
5078         return (statement_t*) statement;
5079 }
5080
5081 static statement_t *parse_loop_body(statement_t *const loop)
5082 {
5083         statement_t *const rem = current_loop;
5084         current_loop = loop;
5085         statement_t *const body = parse_statement();
5086         current_loop = rem;
5087         return body;
5088 }
5089
5090 /**
5091  * Parse a while statement.
5092  */
5093 static statement_t *parse_while(void)
5094 {
5095         eat(T_while);
5096
5097         while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5098         statement->statement.kind            = STATEMENT_WHILE;
5099         statement->statement.source_position = token.source_position;
5100
5101         expect('(');
5102         statement->condition = parse_expression();
5103         expect(')');
5104
5105         statement->body = parse_loop_body((statement_t*)statement);
5106
5107         return (statement_t*) statement;
5108 }
5109
5110 /**
5111  * Parse a do statement.
5112  */
5113 static statement_t *parse_do(void)
5114 {
5115         eat(T_do);
5116
5117         do_while_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5118         statement->statement.kind            = STATEMENT_DO_WHILE;
5119         statement->statement.source_position = token.source_position;
5120
5121         statement->body = parse_loop_body((statement_t*)statement);
5122         expect(T_while);
5123         expect('(');
5124         statement->condition = parse_expression();
5125         expect(')');
5126         expect(';');
5127
5128         return (statement_t*) statement;
5129 }
5130
5131 /**
5132  * Parse a for statement.
5133  */
5134 static statement_t *parse_for(void)
5135 {
5136         eat(T_for);
5137
5138         for_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5139         statement->statement.kind            = STATEMENT_FOR;
5140         statement->statement.source_position = token.source_position;
5141
5142         expect('(');
5143
5144         int         top          = environment_top();
5145         context_t  *last_context = context;
5146         set_context(&statement->context);
5147
5148         if(token.type != ';') {
5149                 if(is_declaration_specifier(&token, false)) {
5150                         parse_declaration(record_declaration);
5151                 } else {
5152                         statement->initialisation = parse_expression();
5153                         expect(';');
5154                 }
5155         } else {
5156                 expect(';');
5157         }
5158
5159         if(token.type != ';') {
5160                 statement->condition = parse_expression();
5161         }
5162         expect(';');
5163         if(token.type != ')') {
5164                 statement->step = parse_expression();
5165         }
5166         expect(')');
5167         statement->body = parse_loop_body((statement_t*)statement);
5168
5169         assert(context == &statement->context);
5170         set_context(last_context);
5171         environment_pop_to(top);
5172
5173         return (statement_t*) statement;
5174 }
5175
5176 /**
5177  * Parse a goto statement.
5178  */
5179 static statement_t *parse_goto(void)
5180 {
5181         eat(T_goto);
5182
5183         if(token.type != T_IDENTIFIER) {
5184                 parse_error_expected("while parsing goto", T_IDENTIFIER, 0);
5185                 eat_statement();
5186                 return NULL;
5187         }
5188         symbol_t *symbol = token.v.symbol;
5189         next_token();
5190
5191         declaration_t *label = get_label(symbol);
5192
5193         goto_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5194
5195         statement->statement.kind            = STATEMENT_GOTO;
5196         statement->statement.source_position = token.source_position;
5197
5198         statement->label = label;
5199
5200         /* remember the goto's in a list for later checking */
5201         if (goto_last == NULL) {
5202                 goto_first = goto_last = statement;
5203         } else {
5204                 goto_last->next = statement;
5205         }
5206
5207         expect(';');
5208
5209         return (statement_t*) statement;
5210 }
5211
5212 /**
5213  * Parse a continue statement.
5214  */
5215 static statement_t *parse_continue(void)
5216 {
5217         statement_t *statement;
5218         if (current_loop == NULL) {
5219                 errorf(HERE, "continue statement not within loop");
5220                 statement = NULL;
5221         } else {
5222                 statement = allocate_statement_zero(STATEMENT_CONTINUE);
5223
5224                 statement->base.source_position = token.source_position;
5225         }
5226
5227         eat(T_continue);
5228         expect(';');
5229
5230         return statement;
5231 }
5232
5233 /**
5234  * Parse a break statement.
5235  */
5236 static statement_t *parse_break(void)
5237 {
5238         statement_t *statement;
5239         if (current_switch == NULL && current_loop == NULL) {
5240                 errorf(HERE, "break statement not within loop or switch");
5241                 statement = NULL;
5242         } else {
5243                 statement = allocate_statement_zero(STATEMENT_BREAK);
5244
5245                 statement->base.source_position = token.source_position;
5246         }
5247
5248         eat(T_break);
5249         expect(';');
5250
5251         return statement;
5252 }
5253
5254 /**
5255  * Check if a given declaration represents a local variable.
5256  */
5257 static bool is_local_var_declaration(const declaration_t *declaration) {
5258         switch ((storage_class_tag_t) declaration->storage_class) {
5259         case STORAGE_CLASS_NONE:
5260         case STORAGE_CLASS_AUTO:
5261         case STORAGE_CLASS_REGISTER: {
5262                 const type_t *type = skip_typeref(declaration->type);
5263                 if(is_type_function(type)) {
5264                         return false;
5265                 } else {
5266                         return true;
5267                 }
5268         }
5269         default:
5270                 return false;
5271         }
5272 }
5273
5274 /**
5275  * Check if a given expression represents a local variable.
5276  */
5277 static bool is_local_variable(const expression_t *expression)
5278 {
5279         if (expression->base.kind != EXPR_REFERENCE) {
5280                 return false;
5281         }
5282         const declaration_t *declaration = expression->reference.declaration;
5283         return is_local_var_declaration(declaration);
5284 }
5285
5286 /**
5287  * Parse a return statement.
5288  */
5289 static statement_t *parse_return(void)
5290 {
5291         eat(T_return);
5292
5293         return_statement_t *statement = allocate_ast_zero(sizeof(statement[0]));
5294
5295         statement->statement.kind            = STATEMENT_RETURN;
5296         statement->statement.source_position = token.source_position;
5297
5298         expression_t *return_value = NULL;
5299         if(token.type != ';') {
5300                 return_value = parse_expression();
5301         }
5302         expect(';');
5303
5304         const type_t *const func_type = current_function->type;
5305         assert(is_type_function(func_type));
5306         type_t *const return_type = skip_typeref(func_type->function.return_type);
5307
5308         if(return_value != NULL) {
5309                 type_t *return_value_type = skip_typeref(return_value->base.datatype);
5310
5311                 if(is_type_atomic(return_type, ATOMIC_TYPE_VOID)
5312                                 && !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
5313                         warningf(statement->statement.source_position,
5314                                 "'return' with a value, in function returning void");
5315                         return_value = NULL;
5316                 } else {
5317                         type_t *const res_type = semantic_assign(return_type,
5318                                 return_value, "'return'");
5319                         if (res_type == NULL) {
5320                                 errorf(statement->statement.source_position,
5321                                         "cannot return something of type '%T' in function returning '%T'",
5322                                         return_value->base.datatype, return_type);
5323                         } else {
5324                                 return_value = create_implicit_cast(return_value, res_type);
5325                         }
5326                 }
5327                 /* check for returning address of a local var */
5328                 if (return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
5329                         const expression_t *expression = return_value->unary.value;
5330                         if (is_local_variable(expression)) {
5331                                 warningf(statement->statement.source_position,
5332                                         "function returns address of local variable");
5333                         }
5334                 }
5335         } else {
5336                 if(!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
5337                         warningf(statement->statement.source_position,
5338                                 "'return' without value, in function returning non-void");
5339                 }
5340         }
5341         statement->return_value = return_value;
5342
5343         return (statement_t*) statement;
5344 }
5345
5346 /**
5347  * Parse a declaration statement.
5348  */
5349 static statement_t *parse_declaration_statement(void)
5350 {
5351         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
5352
5353         statement->base.source_position = token.source_position;
5354
5355         declaration_t *before = last_declaration;
5356         parse_declaration(record_declaration);
5357
5358         if(before == NULL) {
5359                 statement->declaration.declarations_begin = context->declarations;
5360         } else {
5361                 statement->declaration.declarations_begin = before->next;
5362         }
5363         statement->declaration.declarations_end = last_declaration;
5364
5365         return statement;
5366 }
5367
5368 /**
5369  * Parse an expression statement, ie. expr ';'.
5370  */
5371 static statement_t *parse_expression_statement(void)
5372 {
5373         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
5374
5375         statement->base.source_position  = token.source_position;
5376         expression_t *const expr         = parse_expression();
5377         statement->expression.expression = expr;
5378
5379         if (warning.unused_value  && !expression_has_effect(expr)) {
5380                 warningf(expr->base.source_position, "statement has no effect");
5381         }
5382
5383         expect(';');
5384
5385         return statement;
5386 }
5387
5388 /**
5389  * Parse a statement.
5390  */
5391 static statement_t *parse_statement(void)
5392 {
5393         statement_t   *statement = NULL;
5394
5395         /* declaration or statement */
5396         switch(token.type) {
5397         case T_asm:
5398                 statement = parse_asm_statement();
5399                 break;
5400
5401         case T_case:
5402                 statement = parse_case_statement();
5403                 break;
5404
5405         case T_default:
5406                 statement = parse_default_statement();
5407                 break;
5408
5409         case '{':
5410                 statement = parse_compound_statement();
5411                 break;
5412
5413         case T_if:
5414                 statement = parse_if();
5415                 break;
5416
5417         case T_switch:
5418                 statement = parse_switch();
5419                 break;
5420
5421         case T_while:
5422                 statement = parse_while();
5423                 break;
5424
5425         case T_do:
5426                 statement = parse_do();
5427                 break;
5428
5429         case T_for:
5430                 statement = parse_for();
5431                 break;
5432
5433         case T_goto:
5434                 statement = parse_goto();
5435                 break;
5436
5437         case T_continue:
5438                 statement = parse_continue();
5439                 break;
5440
5441         case T_break:
5442                 statement = parse_break();
5443                 break;
5444
5445         case T_return:
5446                 statement = parse_return();
5447                 break;
5448
5449         case ';':
5450                 next_token();
5451                 statement = NULL;
5452                 break;
5453
5454         case T_IDENTIFIER:
5455                 if(look_ahead(1)->type == ':') {
5456                         statement = parse_label_statement();
5457                         break;
5458                 }
5459
5460                 if(is_typedef_symbol(token.v.symbol)) {
5461                         statement = parse_declaration_statement();
5462                         break;
5463                 }
5464
5465                 statement = parse_expression_statement();
5466                 break;
5467
5468         case T___extension__:
5469                 /* this can be a prefix to a declaration or an expression statement */
5470                 /* we simply eat it now and parse the rest with tail recursion */
5471                 do {
5472                         next_token();
5473                 } while(token.type == T___extension__);
5474                 statement = parse_statement();
5475                 break;
5476
5477         DECLARATION_START
5478                 statement = parse_declaration_statement();
5479                 break;
5480
5481         default:
5482                 statement = parse_expression_statement();
5483                 break;
5484         }
5485
5486         assert(statement == NULL
5487                         || statement->base.source_position.input_name != NULL);
5488
5489         return statement;
5490 }
5491
5492 /**
5493  * Parse a compound statement.
5494  */
5495 static statement_t *parse_compound_statement(void)
5496 {
5497         compound_statement_t *const compound_statement
5498                 = allocate_ast_zero(sizeof(compound_statement[0]));
5499         compound_statement->statement.kind            = STATEMENT_COMPOUND;
5500         compound_statement->statement.source_position = token.source_position;
5501
5502         eat('{');
5503
5504         int        top          = environment_top();
5505         context_t *last_context = context;
5506         set_context(&compound_statement->context);
5507
5508         statement_t *last_statement = NULL;
5509
5510         while(token.type != '}' && token.type != T_EOF) {
5511                 statement_t *statement = parse_statement();
5512                 if(statement == NULL)
5513                         continue;
5514
5515                 if(last_statement != NULL) {
5516                         last_statement->base.next = statement;
5517                 } else {
5518                         compound_statement->statements = statement;
5519                 }
5520
5521                 while(statement->base.next != NULL)
5522                         statement = statement->base.next;
5523
5524                 last_statement = statement;
5525         }
5526
5527         if(token.type == '}') {
5528                 next_token();
5529         } else {
5530                 errorf(compound_statement->statement.source_position, "end of file while looking for closing '}'");
5531         }
5532
5533         assert(context == &compound_statement->context);
5534         set_context(last_context);
5535         environment_pop_to(top);
5536
5537         return (statement_t*) compound_statement;
5538 }
5539
5540 /**
5541  * Initialize builtin types.
5542  */
5543 static void initialize_builtin_types(void)
5544 {
5545         type_intmax_t    = make_global_typedef("__intmax_t__",      type_long_long);
5546         type_size_t      = make_global_typedef("__SIZE_TYPE__",     type_unsigned_long);
5547         type_ssize_t     = make_global_typedef("__SSIZE_TYPE__",    type_long);
5548         type_ptrdiff_t   = make_global_typedef("__PTRDIFF_TYPE__",  type_long);
5549         type_uintmax_t   = make_global_typedef("__uintmax_t__",     type_unsigned_long_long);
5550         type_uptrdiff_t  = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
5551         type_wchar_t     = make_global_typedef("__WCHAR_TYPE__",    type_int);
5552         type_wint_t      = make_global_typedef("__WINT_TYPE__",     type_int);
5553
5554         type_intmax_t_ptr  = make_pointer_type(type_intmax_t,  TYPE_QUALIFIER_NONE);
5555         type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
5556         type_ssize_t_ptr   = make_pointer_type(type_ssize_t,   TYPE_QUALIFIER_NONE);
5557         type_wchar_t_ptr   = make_pointer_type(type_wchar_t,   TYPE_QUALIFIER_NONE);
5558 }
5559
5560 /**
5561  * Parse a translation unit.
5562  */
5563 static translation_unit_t *parse_translation_unit(void)
5564 {
5565         translation_unit_t *unit = allocate_ast_zero(sizeof(unit[0]));
5566
5567         assert(global_context == NULL);
5568         global_context = &unit->context;
5569
5570         assert(context == NULL);
5571         set_context(&unit->context);
5572
5573         initialize_builtin_types();
5574
5575         while(token.type != T_EOF) {
5576                 if (token.type == ';') {
5577                         /* TODO error in strict mode */
5578                         warningf(HERE, "stray ';' outside of function");
5579                         next_token();
5580                 } else {
5581                         parse_external_declaration();
5582                 }
5583         }
5584
5585         assert(context == &unit->context);
5586         context          = NULL;
5587         last_declaration = NULL;
5588
5589         assert(global_context == &unit->context);
5590         global_context = NULL;
5591
5592         return unit;
5593 }
5594
5595 /**
5596  * Parse the input.
5597  *
5598  * @return  the translation unit or NULL if errors occurred.
5599  */
5600 translation_unit_t *parse(void)
5601 {
5602         environment_stack = NEW_ARR_F(stack_entry_t, 0);
5603         label_stack       = NEW_ARR_F(stack_entry_t, 0);
5604         diagnostic_count  = 0;
5605         error_count       = 0;
5606         warning_count     = 0;
5607
5608         type_set_output(stderr);
5609         ast_set_output(stderr);
5610
5611         lookahead_bufpos = 0;
5612         for(int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
5613                 next_token();
5614         }
5615         translation_unit_t *unit = parse_translation_unit();
5616
5617         DEL_ARR_F(environment_stack);
5618         DEL_ARR_F(label_stack);
5619
5620         if(error_count > 0)
5621                 return NULL;
5622
5623         return unit;
5624 }
5625
5626 /**
5627  * Initialize the parser.
5628  */
5629 void init_parser(void)
5630 {
5631         init_expression_parsers();
5632         obstack_init(&temp_obst);
5633
5634         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
5635         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
5636 }
5637
5638 /**
5639  * Terminate the parser.
5640  */
5641 void exit_parser(void)
5642 {
5643         obstack_free(&temp_obst, NULL);
5644 }