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