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