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