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