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