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