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