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