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