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