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