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