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