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