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