e16ed1991111c3a98cdfd82882a177a90ec73721
[cparser] / parser.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2009 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 "entity_t.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
40 #include "warning.h"
41 #include "adt/bitfiddle.h"
42 #include "adt/error.h"
43 #include "adt/array.h"
44
45 //#define PRINT_TOKENS
46 #define MAX_LOOKAHEAD 1
47
48 typedef struct {
49         entity_t           *old_entity;
50         symbol_t           *symbol;
51         entity_namespace_t  namespc;
52 } stack_entry_t;
53
54 typedef struct declaration_specifiers_t  declaration_specifiers_t;
55 struct declaration_specifiers_t {
56         source_position_t  source_position;
57         storage_class_t    storage_class;
58         unsigned char      alignment;         /**< Alignment, 0 if not set. */
59         bool               is_inline    : 1;
60         bool               thread_local : 1;  /**< GCC __thread */
61         attribute_t       *attributes;        /**< list of attributes */
62         type_t            *type;
63 };
64
65 /**
66  * An environment for parsing initializers (and compound literals).
67  */
68 typedef struct parse_initializer_env_t {
69         type_t     *type;   /**< the type of the initializer. In case of an
70                                  array type with unspecified size this gets
71                                  adjusted to the actual size. */
72         entity_t   *entity; /**< the variable that is initialized if any */
73         bool        must_be_constant;
74 } parse_initializer_env_t;
75
76 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
77
78 /** The current token. */
79 static token_t              token;
80 /** The lookahead ring-buffer. */
81 static token_t              lookahead_buffer[MAX_LOOKAHEAD];
82 /** Position of the next token in the lookahead buffer. */
83 static size_t               lookahead_bufpos;
84 static stack_entry_t       *environment_stack = NULL;
85 static stack_entry_t       *label_stack       = NULL;
86 static scope_t             *file_scope        = NULL;
87 static scope_t             *current_scope     = NULL;
88 /** Point to the current function declaration if inside a function. */
89 static function_t          *current_function  = NULL;
90 static entity_t            *current_init_decl = NULL;
91 static switch_statement_t  *current_switch    = NULL;
92 static statement_t         *current_loop      = NULL;
93 static statement_t         *current_parent    = NULL;
94 static ms_try_statement_t  *current_try       = NULL;
95 static linkage_kind_t       current_linkage   = LINKAGE_INVALID;
96 static goto_statement_t    *goto_first        = NULL;
97 static goto_statement_t   **goto_anchor       = NULL;
98 static label_statement_t   *label_first       = NULL;
99 static label_statement_t  **label_anchor      = NULL;
100 /** current translation unit. */
101 static translation_unit_t  *unit              = NULL;
102 /** true if we are in a type property context (evaluation only for type. */
103 static bool                 in_type_prop      = false;
104 /** true in we are in a __extension__ context. */
105 static bool                 in_gcc_extension  = false;
106 static struct obstack       temp_obst;
107 static entity_t            *anonymous_entity;
108 static declaration_t      **incomplete_arrays;
109
110
111 #define PUSH_PARENT(stmt)                          \
112         statement_t *const prev_parent = current_parent; \
113         ((void)(current_parent = (stmt)))
114 #define POP_PARENT ((void)(current_parent = prev_parent))
115
116 /** special symbol used for anonymous entities. */
117 static symbol_t *sym_anonymous = NULL;
118
119 /** The token anchor set */
120 static unsigned char token_anchor_set[T_LAST_TOKEN];
121
122 /** The current source position. */
123 #define HERE (&token.source_position)
124
125 /** true if we are in GCC mode. */
126 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
127
128 static statement_t *parse_compound_statement(bool inside_expression_statement);
129 static statement_t *parse_statement(void);
130
131 static expression_t *parse_sub_expression(precedence_t);
132 static expression_t *parse_expression(void);
133 static type_t       *parse_typename(void);
134 static void          parse_externals(void);
135 static void          parse_external(void);
136
137 static void parse_compound_type_entries(compound_t *compound_declaration);
138
139 static void check_call_argument(type_t          *expected_type,
140                                                                 call_argument_t *argument, unsigned pos);
141
142 typedef enum declarator_flags_t {
143         DECL_FLAGS_NONE             = 0,
144         DECL_MAY_BE_ABSTRACT        = 1U << 0,
145         DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
146         DECL_IS_PARAMETER           = 1U << 2
147 } declarator_flags_t;
148
149 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
150                                   declarator_flags_t flags);
151
152 static entity_t *record_entity(entity_t *entity, bool is_definition);
153
154 static void semantic_comparison(binary_expression_t *expression);
155
156 static void create_gnu_builtins(void);
157 static void create_microsoft_intrinsics(void);
158
159 #define STORAGE_CLASSES       \
160         STORAGE_CLASSES_NO_EXTERN \
161         case T_extern:
162
163 #define STORAGE_CLASSES_NO_EXTERN \
164         case T_typedef:         \
165         case T_static:          \
166         case T_auto:            \
167         case T_register:        \
168         case T___thread:
169
170 #define TYPE_QUALIFIERS     \
171         case T_const:           \
172         case T_restrict:        \
173         case T_volatile:        \
174         case T_inline:          \
175         case T__forceinline:    \
176         case T___attribute__:
177
178 #define COMPLEX_SPECIFIERS  \
179         case T__Complex:
180 #define IMAGINARY_SPECIFIERS \
181         case T__Imaginary:
182
183 #define TYPE_SPECIFIERS       \
184         case T__Bool:             \
185         case T___builtin_va_list: \
186         case T___typeof__:        \
187         case T__declspec:         \
188         case T_bool:              \
189         case T_char:              \
190         case T_double:            \
191         case T_enum:              \
192         case T_float:             \
193         case T_int:               \
194         case T_long:              \
195         case T_short:             \
196         case T_signed:            \
197         case T_struct:            \
198         case T_union:             \
199         case T_unsigned:          \
200         case T_void:              \
201         case T_wchar_t:           \
202         case T__int8:             \
203         case T__int16:            \
204         case T__int32:            \
205         case T__int64:            \
206         case T__int128:           \
207         COMPLEX_SPECIFIERS        \
208         IMAGINARY_SPECIFIERS
209
210 #define DECLARATION_START   \
211         STORAGE_CLASSES         \
212         TYPE_QUALIFIERS         \
213         TYPE_SPECIFIERS
214
215 #define DECLARATION_START_NO_EXTERN \
216         STORAGE_CLASSES_NO_EXTERN       \
217         TYPE_QUALIFIERS                 \
218         TYPE_SPECIFIERS
219
220 #define TYPENAME_START      \
221         TYPE_QUALIFIERS         \
222         TYPE_SPECIFIERS
223
224 #define EXPRESSION_START           \
225         case '!':                        \
226         case '&':                        \
227         case '(':                        \
228         case '*':                        \
229         case '+':                        \
230         case '-':                        \
231         case '~':                        \
232         case T_ANDAND:                   \
233         case T_CHARACTER_CONSTANT:       \
234         case T_FLOATINGPOINT:            \
235         case T_INTEGER:                  \
236         case T_MINUSMINUS:               \
237         case T_PLUSPLUS:                 \
238         case T_STRING_LITERAL:           \
239         case T_WIDE_CHARACTER_CONSTANT:  \
240         case T_WIDE_STRING_LITERAL:      \
241         case T___FUNCDNAME__:            \
242         case T___FUNCSIG__:              \
243         case T___FUNCTION__:             \
244         case T___PRETTY_FUNCTION__:      \
245         case T___alignof__:              \
246         case T___builtin_classify_type:  \
247         case T___builtin_constant_p:     \
248         case T___builtin_isgreater:      \
249         case T___builtin_isgreaterequal: \
250         case T___builtin_isless:         \
251         case T___builtin_islessequal:    \
252         case T___builtin_islessgreater:  \
253         case T___builtin_isunordered:    \
254         case T___builtin_offsetof:       \
255         case T___builtin_va_arg:         \
256         case T___builtin_va_start:       \
257         case T___builtin_va_copy:        \
258         case T___func__:                 \
259         case T___noop:                   \
260         case T__assume:                  \
261         case T_delete:                   \
262         case T_false:                    \
263         case T_sizeof:                   \
264         case T_throw:                    \
265         case T_true:
266
267 /**
268  * Allocate an AST node with given size and
269  * initialize all fields with zero.
270  */
271 static void *allocate_ast_zero(size_t size)
272 {
273         void *res = allocate_ast(size);
274         memset(res, 0, size);
275         return res;
276 }
277
278 /**
279  * Returns the size of an entity node.
280  *
281  * @param kind  the entity kind
282  */
283 static size_t get_entity_struct_size(entity_kind_t kind)
284 {
285         static const size_t sizes[] = {
286                 [ENTITY_VARIABLE]        = sizeof(variable_t),
287                 [ENTITY_PARAMETER]       = sizeof(parameter_t),
288                 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
289                 [ENTITY_FUNCTION]        = sizeof(function_t),
290                 [ENTITY_TYPEDEF]         = sizeof(typedef_t),
291                 [ENTITY_STRUCT]          = sizeof(compound_t),
292                 [ENTITY_UNION]           = sizeof(compound_t),
293                 [ENTITY_ENUM]            = sizeof(enum_t),
294                 [ENTITY_ENUM_VALUE]      = sizeof(enum_value_t),
295                 [ENTITY_LABEL]           = sizeof(label_t),
296                 [ENTITY_LOCAL_LABEL]     = sizeof(label_t),
297                 [ENTITY_NAMESPACE]       = sizeof(namespace_t)
298         };
299         assert(kind < lengthof(sizes));
300         assert(sizes[kind] != 0);
301         return sizes[kind];
302 }
303
304 /**
305  * Allocate an entity of given kind and initialize all
306  * fields with zero.
307  *
308  * @param kind   the kind of the entity to allocate
309  */
310 static entity_t *allocate_entity_zero(entity_kind_t kind)
311 {
312         size_t    size   = get_entity_struct_size(kind);
313         entity_t *entity = allocate_ast_zero(size);
314         entity->kind     = kind;
315         return entity;
316 }
317
318 /**
319  * Returns the size of a statement node.
320  *
321  * @param kind  the statement kind
322  */
323 static size_t get_statement_struct_size(statement_kind_t kind)
324 {
325         static const size_t sizes[] = {
326                 [STATEMENT_INVALID]     = sizeof(invalid_statement_t),
327                 [STATEMENT_EMPTY]       = sizeof(empty_statement_t),
328                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
329                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
330                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
331                 [STATEMENT_IF]          = sizeof(if_statement_t),
332                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
333                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
334                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
335                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
336                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
337                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
338                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
339                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
340                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
341                 [STATEMENT_FOR]         = sizeof(for_statement_t),
342                 [STATEMENT_ASM]         = sizeof(asm_statement_t),
343                 [STATEMENT_MS_TRY]      = sizeof(ms_try_statement_t),
344                 [STATEMENT_LEAVE]       = sizeof(leave_statement_t)
345         };
346         assert(kind < lengthof(sizes));
347         assert(sizes[kind] != 0);
348         return sizes[kind];
349 }
350
351 /**
352  * Returns the size of an expression node.
353  *
354  * @param kind  the expression kind
355  */
356 static size_t get_expression_struct_size(expression_kind_t kind)
357 {
358         static const size_t sizes[] = {
359                 [EXPR_INVALID]                    = sizeof(expression_base_t),
360                 [EXPR_REFERENCE]                  = sizeof(reference_expression_t),
361                 [EXPR_REFERENCE_ENUM_VALUE]       = sizeof(reference_expression_t),
362                 [EXPR_CONST]                      = sizeof(const_expression_t),
363                 [EXPR_CHARACTER_CONSTANT]         = sizeof(const_expression_t),
364                 [EXPR_WIDE_CHARACTER_CONSTANT]    = sizeof(const_expression_t),
365                 [EXPR_STRING_LITERAL]             = sizeof(string_literal_expression_t),
366                 [EXPR_WIDE_STRING_LITERAL]        = sizeof(wide_string_literal_expression_t),
367                 [EXPR_COMPOUND_LITERAL]           = sizeof(compound_literal_expression_t),
368                 [EXPR_CALL]                       = sizeof(call_expression_t),
369                 [EXPR_UNARY_FIRST]                = sizeof(unary_expression_t),
370                 [EXPR_BINARY_FIRST]               = sizeof(binary_expression_t),
371                 [EXPR_CONDITIONAL]                = sizeof(conditional_expression_t),
372                 [EXPR_SELECT]                     = sizeof(select_expression_t),
373                 [EXPR_ARRAY_ACCESS]               = sizeof(array_access_expression_t),
374                 [EXPR_SIZEOF]                     = sizeof(typeprop_expression_t),
375                 [EXPR_ALIGNOF]                    = sizeof(typeprop_expression_t),
376                 [EXPR_CLASSIFY_TYPE]              = sizeof(classify_type_expression_t),
377                 [EXPR_FUNCNAME]                   = sizeof(funcname_expression_t),
378                 [EXPR_BUILTIN_CONSTANT_P]         = sizeof(builtin_constant_expression_t),
379                 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
380                 [EXPR_OFFSETOF]                   = sizeof(offsetof_expression_t),
381                 [EXPR_VA_START]                   = sizeof(va_start_expression_t),
382                 [EXPR_VA_ARG]                     = sizeof(va_arg_expression_t),
383                 [EXPR_VA_COPY]                    = sizeof(va_copy_expression_t),
384                 [EXPR_STATEMENT]                  = sizeof(statement_expression_t),
385                 [EXPR_LABEL_ADDRESS]              = sizeof(label_address_expression_t),
386         };
387         if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
388                 return sizes[EXPR_UNARY_FIRST];
389         }
390         if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
391                 return sizes[EXPR_BINARY_FIRST];
392         }
393         assert(kind < lengthof(sizes));
394         assert(sizes[kind] != 0);
395         return sizes[kind];
396 }
397
398 /**
399  * Allocate a statement node of given kind and initialize all
400  * fields with zero. Sets its source position to the position
401  * of the current token.
402  */
403 static statement_t *allocate_statement_zero(statement_kind_t kind)
404 {
405         size_t       size = get_statement_struct_size(kind);
406         statement_t *res  = allocate_ast_zero(size);
407
408         res->base.kind            = kind;
409         res->base.parent          = current_parent;
410         res->base.source_position = token.source_position;
411         return res;
412 }
413
414 /**
415  * Allocate an expression node of given kind and initialize all
416  * fields with zero.
417  *
418  * @param kind  the kind of the expression to allocate
419  */
420 static expression_t *allocate_expression_zero(expression_kind_t kind)
421 {
422         size_t        size = get_expression_struct_size(kind);
423         expression_t *res  = allocate_ast_zero(size);
424
425         res->base.kind            = kind;
426         res->base.type            = type_error_type;
427         res->base.source_position = token.source_position;
428         return res;
429 }
430
431 /**
432  * Creates a new invalid expression at the source position
433  * of the current token.
434  */
435 static expression_t *create_invalid_expression(void)
436 {
437         return allocate_expression_zero(EXPR_INVALID);
438 }
439
440 /**
441  * Creates a new invalid statement.
442  */
443 static statement_t *create_invalid_statement(void)
444 {
445         return allocate_statement_zero(STATEMENT_INVALID);
446 }
447
448 /**
449  * Allocate a new empty statement.
450  */
451 static statement_t *create_empty_statement(void)
452 {
453         return allocate_statement_zero(STATEMENT_EMPTY);
454 }
455
456 /**
457  * Returns the size of a type node.
458  *
459  * @param kind  the type kind
460  */
461 static size_t get_type_struct_size(type_kind_t kind)
462 {
463         static const size_t sizes[] = {
464                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
465                 [TYPE_COMPLEX]         = sizeof(complex_type_t),
466                 [TYPE_IMAGINARY]       = sizeof(imaginary_type_t),
467                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
468                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
469                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
470                 [TYPE_ENUM]            = sizeof(enum_type_t),
471                 [TYPE_FUNCTION]        = sizeof(function_type_t),
472                 [TYPE_POINTER]         = sizeof(pointer_type_t),
473                 [TYPE_ARRAY]           = sizeof(array_type_t),
474                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
475                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
476                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
477         };
478         assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
479         assert(kind <= TYPE_TYPEOF);
480         assert(sizes[kind] != 0);
481         return sizes[kind];
482 }
483
484 /**
485  * Allocate a type node of given kind and initialize all
486  * fields with zero.
487  *
488  * @param kind             type kind to allocate
489  */
490 static type_t *allocate_type_zero(type_kind_t kind)
491 {
492         size_t  size = get_type_struct_size(kind);
493         type_t *res  = obstack_alloc(type_obst, size);
494         memset(res, 0, size);
495         res->base.kind = kind;
496
497         return res;
498 }
499
500 static function_parameter_t *allocate_parameter(type_t *const type)
501 {
502         function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
503         memset(param, 0, sizeof(*param));
504         param->type = type;
505         return param;
506 }
507
508 /**
509  * Returns the size of an initializer node.
510  *
511  * @param kind  the initializer kind
512  */
513 static size_t get_initializer_size(initializer_kind_t kind)
514 {
515         static const size_t sizes[] = {
516                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
517                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
518                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
519                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
520                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
521         };
522         assert(kind < lengthof(sizes));
523         assert(sizes[kind] != 0);
524         return sizes[kind];
525 }
526
527 /**
528  * Allocate an initializer node of given kind and initialize all
529  * fields with zero.
530  */
531 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
532 {
533         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
534         result->kind          = kind;
535
536         return result;
537 }
538
539 /**
540  * Returns the index of the top element of the environment stack.
541  */
542 static size_t environment_top(void)
543 {
544         return ARR_LEN(environment_stack);
545 }
546
547 /**
548  * Returns the index of the top element of the global label stack.
549  */
550 static size_t label_top(void)
551 {
552         return ARR_LEN(label_stack);
553 }
554
555 /**
556  * Return the next token.
557  */
558 static inline void next_token(void)
559 {
560         token                              = lookahead_buffer[lookahead_bufpos];
561         lookahead_buffer[lookahead_bufpos] = lexer_token;
562         lexer_next_token();
563
564         lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
565
566 #ifdef PRINT_TOKENS
567         print_token(stderr, &token);
568         fprintf(stderr, "\n");
569 #endif
570 }
571
572 static inline bool next_if(int const type)
573 {
574         if (token.type == type) {
575                 next_token();
576                 return true;
577         } else {
578                 return false;
579         }
580 }
581
582 /**
583  * Return the next token with a given lookahead.
584  */
585 static inline const token_t *look_ahead(size_t num)
586 {
587         assert(0 < num && num <= MAX_LOOKAHEAD);
588         size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
589         return &lookahead_buffer[pos];
590 }
591
592 /**
593  * Adds a token type to the token type anchor set (a multi-set).
594  */
595 static void add_anchor_token(int token_type)
596 {
597         assert(0 <= token_type && token_type < T_LAST_TOKEN);
598         ++token_anchor_set[token_type];
599 }
600
601 /**
602  * Set the number of tokens types of the given type
603  * to zero and return the old count.
604  */
605 static int save_and_reset_anchor_state(int token_type)
606 {
607         assert(0 <= token_type && token_type < T_LAST_TOKEN);
608         int count = token_anchor_set[token_type];
609         token_anchor_set[token_type] = 0;
610         return count;
611 }
612
613 /**
614  * Restore the number of token types to the given count.
615  */
616 static void restore_anchor_state(int token_type, int count)
617 {
618         assert(0 <= token_type && token_type < T_LAST_TOKEN);
619         token_anchor_set[token_type] = count;
620 }
621
622 /**
623  * Remove a token type from the token type anchor set (a multi-set).
624  */
625 static void rem_anchor_token(int token_type)
626 {
627         assert(0 <= token_type && token_type < T_LAST_TOKEN);
628         assert(token_anchor_set[token_type] != 0);
629         --token_anchor_set[token_type];
630 }
631
632 /**
633  * Return true if the token type of the current token is
634  * in the anchor set.
635  */
636 static bool at_anchor(void)
637 {
638         if (token.type < 0)
639                 return false;
640         return token_anchor_set[token.type];
641 }
642
643 /**
644  * Eat tokens until a matching token type is found.
645  */
646 static void eat_until_matching_token(int type)
647 {
648         int end_token;
649         switch (type) {
650                 case '(': end_token = ')';  break;
651                 case '{': end_token = '}';  break;
652                 case '[': end_token = ']';  break;
653                 default:  end_token = type; break;
654         }
655
656         unsigned parenthesis_count = 0;
657         unsigned brace_count       = 0;
658         unsigned bracket_count     = 0;
659         while (token.type        != end_token ||
660                parenthesis_count != 0         ||
661                brace_count       != 0         ||
662                bracket_count     != 0) {
663                 switch (token.type) {
664                 case T_EOF: return;
665                 case '(': ++parenthesis_count; break;
666                 case '{': ++brace_count;       break;
667                 case '[': ++bracket_count;     break;
668
669                 case ')':
670                         if (parenthesis_count > 0)
671                                 --parenthesis_count;
672                         goto check_stop;
673
674                 case '}':
675                         if (brace_count > 0)
676                                 --brace_count;
677                         goto check_stop;
678
679                 case ']':
680                         if (bracket_count > 0)
681                                 --bracket_count;
682 check_stop:
683                         if (token.type        == end_token &&
684                             parenthesis_count == 0         &&
685                             brace_count       == 0         &&
686                             bracket_count     == 0)
687                                 return;
688                         break;
689
690                 default:
691                         break;
692                 }
693                 next_token();
694         }
695 }
696
697 /**
698  * Eat input tokens until an anchor is found.
699  */
700 static void eat_until_anchor(void)
701 {
702         while (token_anchor_set[token.type] == 0) {
703                 if (token.type == '(' || token.type == '{' || token.type == '[')
704                         eat_until_matching_token(token.type);
705                 next_token();
706         }
707 }
708
709 /**
710  * Eat a whole block from input tokens.
711  */
712 static void eat_block(void)
713 {
714         eat_until_matching_token('{');
715         next_if('}');
716 }
717
718 #define eat(token_type) (assert(token.type == (token_type)), next_token())
719
720 /**
721  * Report a parse error because an expected token was not found.
722  */
723 static
724 #if defined __GNUC__ && __GNUC__ >= 4
725 __attribute__((sentinel))
726 #endif
727 void parse_error_expected(const char *message, ...)
728 {
729         if (message != NULL) {
730                 errorf(HERE, "%s", message);
731         }
732         va_list ap;
733         va_start(ap, message);
734         errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
735         va_end(ap);
736 }
737
738 /**
739  * Report an incompatible type.
740  */
741 static void type_error_incompatible(const char *msg,
742                 const source_position_t *source_position, type_t *type1, type_t *type2)
743 {
744         errorf(source_position, "%s, incompatible types: '%T' - '%T'",
745                msg, type1, type2);
746 }
747
748 /**
749  * Expect the current token is the expected token.
750  * If not, generate an error, eat the current statement,
751  * and goto the end_error label.
752  */
753 #define expect(expected, error_label)                     \
754         do {                                                  \
755                 if (UNLIKELY(token.type != (expected))) {         \
756                         parse_error_expected(NULL, (expected), NULL); \
757                         add_anchor_token(expected);                   \
758                         eat_until_anchor();                           \
759                         next_if((expected));                          \
760                         rem_anchor_token(expected);                   \
761                         goto error_label;                             \
762                 }                                                 \
763                 next_token();                                     \
764         } while (0)
765
766 /**
767  * Push a given scope on the scope stack and make it the
768  * current scope
769  */
770 static scope_t *scope_push(scope_t *new_scope)
771 {
772         if (current_scope != NULL) {
773                 new_scope->depth = current_scope->depth + 1;
774         }
775
776         scope_t *old_scope = current_scope;
777         current_scope      = new_scope;
778         return old_scope;
779 }
780
781 /**
782  * Pop the current scope from the scope stack.
783  */
784 static void scope_pop(scope_t *old_scope)
785 {
786         current_scope = old_scope;
787 }
788
789 /**
790  * Search an entity by its symbol in a given namespace.
791  */
792 static entity_t *get_entity(const symbol_t *const symbol,
793                             namespace_tag_t namespc)
794 {
795         entity_t *entity = symbol->entity;
796         for (; entity != NULL; entity = entity->base.symbol_next) {
797                 if (entity->base.namespc == namespc)
798                         return entity;
799         }
800
801         return NULL;
802 }
803
804 /* §6.2.3:1 24)  There is only one name space for tags even though three are
805  * possible. */
806 static entity_t *get_tag(symbol_t const *const symbol,
807                          entity_kind_tag_t const kind)
808 {
809         entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
810         if (entity != NULL && entity->kind != kind) {
811                 errorf(HERE,
812                                 "'%Y' defined as wrong kind of tag (previous definition %P)",
813                                 symbol, &entity->base.source_position);
814                 entity = NULL;
815         }
816         return entity;
817 }
818
819 /**
820  * pushs an entity on the environment stack and links the corresponding symbol
821  * it.
822  */
823 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
824 {
825         symbol_t           *symbol  = entity->base.symbol;
826         entity_namespace_t  namespc = entity->base.namespc;
827         assert(namespc != NAMESPACE_INVALID);
828
829         /* replace/add entity into entity list of the symbol */
830         entity_t **anchor;
831         entity_t  *iter;
832         for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
833                 iter = *anchor;
834                 if (iter == NULL)
835                         break;
836
837                 /* replace an entry? */
838                 if (iter->base.namespc == namespc) {
839                         entity->base.symbol_next = iter->base.symbol_next;
840                         break;
841                 }
842         }
843         *anchor = entity;
844
845         /* remember old declaration */
846         stack_entry_t entry;
847         entry.symbol     = symbol;
848         entry.old_entity = iter;
849         entry.namespc    = namespc;
850         ARR_APP1(stack_entry_t, *stack_ptr, entry);
851 }
852
853 /**
854  * Push an entity on the environment stack.
855  */
856 static void environment_push(entity_t *entity)
857 {
858         assert(entity->base.source_position.input_name != NULL);
859         assert(entity->base.parent_scope != NULL);
860         stack_push(&environment_stack, entity);
861 }
862
863 /**
864  * Push a declaration on the global label stack.
865  *
866  * @param declaration  the declaration
867  */
868 static void label_push(entity_t *label)
869 {
870         /* we abuse the parameters scope as parent for the labels */
871         label->base.parent_scope = &current_function->parameters;
872         stack_push(&label_stack, label);
873 }
874
875 /**
876  * pops symbols from the environment stack until @p new_top is the top element
877  */
878 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
879 {
880         stack_entry_t *stack = *stack_ptr;
881         size_t         top   = ARR_LEN(stack);
882         size_t         i;
883
884         assert(new_top <= top);
885         if (new_top == top)
886                 return;
887
888         for (i = top; i > new_top; --i) {
889                 stack_entry_t *entry = &stack[i - 1];
890
891                 entity_t           *old_entity = entry->old_entity;
892                 symbol_t           *symbol     = entry->symbol;
893                 entity_namespace_t  namespc    = entry->namespc;
894
895                 /* replace with old_entity/remove */
896                 entity_t **anchor;
897                 entity_t  *iter;
898                 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
899                         iter = *anchor;
900                         assert(iter != NULL);
901                         /* replace an entry? */
902                         if (iter->base.namespc == namespc)
903                                 break;
904                 }
905
906                 /* restore definition from outer scopes (if there was one) */
907                 if (old_entity != NULL) {
908                         old_entity->base.symbol_next = iter->base.symbol_next;
909                         *anchor                      = old_entity;
910                 } else {
911                         /* remove entry from list */
912                         *anchor = iter->base.symbol_next;
913                 }
914         }
915
916         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
917 }
918
919 /**
920  * Pop all entries from the environment stack until the new_top
921  * is reached.
922  *
923  * @param new_top  the new stack top
924  */
925 static void environment_pop_to(size_t new_top)
926 {
927         stack_pop_to(&environment_stack, new_top);
928 }
929
930 /**
931  * Pop all entries from the global label stack until the new_top
932  * is reached.
933  *
934  * @param new_top  the new stack top
935  */
936 static void label_pop_to(size_t new_top)
937 {
938         stack_pop_to(&label_stack, new_top);
939 }
940
941 static int get_akind_rank(atomic_type_kind_t akind)
942 {
943         return (int) akind;
944 }
945
946 /**
947  * Return the type rank for an atomic type.
948  */
949 static int get_rank(const type_t *type)
950 {
951         assert(!is_typeref(type));
952         if (type->kind == TYPE_ENUM)
953                 return get_akind_rank(type->enumt.akind);
954
955         assert(type->kind == TYPE_ATOMIC);
956         return get_akind_rank(type->atomic.akind);
957 }
958
959 /**
960  * §6.3.1.1:2  Do integer promotion for a given type.
961  *
962  * @param type  the type to promote
963  * @return the promoted type
964  */
965 static type_t *promote_integer(type_t *type)
966 {
967         if (type->kind == TYPE_BITFIELD)
968                 type = type->bitfield.base_type;
969
970         if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
971                 type = type_int;
972
973         return type;
974 }
975
976 /**
977  * Create a cast expression.
978  *
979  * @param expression  the expression to cast
980  * @param dest_type   the destination type
981  */
982 static expression_t *create_cast_expression(expression_t *expression,
983                                             type_t *dest_type)
984 {
985         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
986
987         cast->unary.value = expression;
988         cast->base.type   = dest_type;
989
990         return cast;
991 }
992
993 /**
994  * Check if a given expression represents a null pointer constant.
995  *
996  * @param expression  the expression to check
997  */
998 static bool is_null_pointer_constant(const expression_t *expression)
999 {
1000         /* skip void* cast */
1001         if (expression->kind == EXPR_UNARY_CAST ||
1002                         expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1003                 type_t *const type = skip_typeref(expression->base.type);
1004                 if (types_compatible(type, type_void_ptr))
1005                         expression = expression->unary.value;
1006         }
1007
1008         type_t *const type = skip_typeref(expression->base.type);
1009         return
1010                 is_type_integer(type)              &&
1011                 is_constant_expression(expression) &&
1012                 !fold_constant_to_bool(expression);
1013 }
1014
1015 /**
1016  * Create an implicit cast expression.
1017  *
1018  * @param expression  the expression to cast
1019  * @param dest_type   the destination type
1020  */
1021 static expression_t *create_implicit_cast(expression_t *expression,
1022                                           type_t *dest_type)
1023 {
1024         type_t *const source_type = expression->base.type;
1025
1026         if (source_type == dest_type)
1027                 return expression;
1028
1029         return create_cast_expression(expression, dest_type);
1030 }
1031
1032 typedef enum assign_error_t {
1033         ASSIGN_SUCCESS,
1034         ASSIGN_ERROR_INCOMPATIBLE,
1035         ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1036         ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1037         ASSIGN_WARNING_POINTER_FROM_INT,
1038         ASSIGN_WARNING_INT_FROM_POINTER
1039 } assign_error_t;
1040
1041 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1042                                 const expression_t *const right,
1043                                 const char *context,
1044                                 const source_position_t *source_position)
1045 {
1046         type_t *const orig_type_right = right->base.type;
1047         type_t *const type_left       = skip_typeref(orig_type_left);
1048         type_t *const type_right      = skip_typeref(orig_type_right);
1049
1050         switch (error) {
1051         case ASSIGN_SUCCESS:
1052                 return;
1053         case ASSIGN_ERROR_INCOMPATIBLE:
1054                 errorf(source_position,
1055                        "destination type '%T' in %s is incompatible with type '%T'",
1056                        orig_type_left, context, orig_type_right);
1057                 return;
1058
1059         case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1060                 if (warning.other) {
1061                         type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
1062                         type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1063
1064                         /* the left type has all qualifiers from the right type */
1065                         unsigned missing_qualifiers
1066                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1067                         warningf(source_position,
1068                                         "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1069                                         orig_type_left, context, orig_type_right, missing_qualifiers);
1070                 }
1071                 return;
1072         }
1073
1074         case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1075                 if (warning.other) {
1076                         warningf(source_position,
1077                                         "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1078                                         orig_type_left, context, right, orig_type_right);
1079                 }
1080                 return;
1081
1082         case ASSIGN_WARNING_POINTER_FROM_INT:
1083                 if (warning.other) {
1084                         warningf(source_position,
1085                                         "%s makes pointer '%T' from integer '%T' without a cast",
1086                                         context, orig_type_left, orig_type_right);
1087                 }
1088                 return;
1089
1090         case ASSIGN_WARNING_INT_FROM_POINTER:
1091                 if (warning.other) {
1092                         warningf(source_position,
1093                                         "%s makes integer '%T' from pointer '%T' without a cast",
1094                                         context, orig_type_left, orig_type_right);
1095                 }
1096                 return;
1097
1098         default:
1099                 panic("invalid error value");
1100         }
1101 }
1102
1103 /** Implements the rules from §6.5.16.1 */
1104 static assign_error_t semantic_assign(type_t *orig_type_left,
1105                                       const expression_t *const right)
1106 {
1107         type_t *const orig_type_right = right->base.type;
1108         type_t *const type_left       = skip_typeref(orig_type_left);
1109         type_t *const type_right      = skip_typeref(orig_type_right);
1110
1111         if (is_type_pointer(type_left)) {
1112                 if (is_null_pointer_constant(right)) {
1113                         return ASSIGN_SUCCESS;
1114                 } else if (is_type_pointer(type_right)) {
1115                         type_t *points_to_left
1116                                 = skip_typeref(type_left->pointer.points_to);
1117                         type_t *points_to_right
1118                                 = skip_typeref(type_right->pointer.points_to);
1119                         assign_error_t res = ASSIGN_SUCCESS;
1120
1121                         /* the left type has all qualifiers from the right type */
1122                         unsigned missing_qualifiers
1123                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1124                         if (missing_qualifiers != 0) {
1125                                 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1126                         }
1127
1128                         points_to_left  = get_unqualified_type(points_to_left);
1129                         points_to_right = get_unqualified_type(points_to_right);
1130
1131                         if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1132                                 return res;
1133
1134                         if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1135                                 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1136                                 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1137                         }
1138
1139                         if (!types_compatible(points_to_left, points_to_right)) {
1140                                 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1141                         }
1142
1143                         return res;
1144                 } else if (is_type_integer(type_right)) {
1145                         return ASSIGN_WARNING_POINTER_FROM_INT;
1146                 }
1147         } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1148             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1149                 && is_type_pointer(type_right))) {
1150                 return ASSIGN_SUCCESS;
1151         } else if ((is_type_compound(type_left)  && is_type_compound(type_right))
1152                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1153                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
1154                 type_t *const unqual_type_right = get_unqualified_type(type_right);
1155                 if (types_compatible(unqual_type_left, unqual_type_right)) {
1156                         return ASSIGN_SUCCESS;
1157                 }
1158         } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1159                 return ASSIGN_WARNING_INT_FROM_POINTER;
1160         }
1161
1162         if (!is_type_valid(type_left) || !is_type_valid(type_right))
1163                 return ASSIGN_SUCCESS;
1164
1165         return ASSIGN_ERROR_INCOMPATIBLE;
1166 }
1167
1168 static expression_t *parse_constant_expression(void)
1169 {
1170         expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1171
1172         if (!is_constant_expression(result)) {
1173                 errorf(&result->base.source_position,
1174                        "expression '%E' is not constant", result);
1175         }
1176
1177         return result;
1178 }
1179
1180 static expression_t *parse_assignment_expression(void)
1181 {
1182         return parse_sub_expression(PREC_ASSIGNMENT);
1183 }
1184
1185 static string_t parse_string_literals(void)
1186 {
1187         assert(token.type == T_STRING_LITERAL);
1188         string_t result = token.v.string;
1189
1190         next_token();
1191
1192         while (token.type == T_STRING_LITERAL) {
1193                 result = concat_strings(&result, &token.v.string);
1194                 next_token();
1195         }
1196
1197         return result;
1198 }
1199
1200 /**
1201  * compare two string, ignoring double underscores on the second.
1202  */
1203 static int strcmp_underscore(const char *s1, const char *s2)
1204 {
1205         if (s2[0] == '_' && s2[1] == '_') {
1206                 size_t len2 = strlen(s2);
1207                 size_t len1 = strlen(s1);
1208                 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1209                         return strncmp(s1, s2+2, len2-4);
1210                 }
1211         }
1212
1213         return strcmp(s1, s2);
1214 }
1215
1216 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1217 {
1218         attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1219         attribute->kind        = kind;
1220         return attribute;
1221 }
1222
1223 /**
1224  * Parse (gcc) attribute argument. From gcc comments in gcc source:
1225  *
1226  *  attribute:
1227  *    __attribute__ ( ( attribute-list ) )
1228  *
1229  *  attribute-list:
1230  *    attrib
1231  *    attribute_list , attrib
1232  *
1233  *  attrib:
1234  *    empty
1235  *    any-word
1236  *    any-word ( identifier )
1237  *    any-word ( identifier , nonempty-expr-list )
1238  *    any-word ( expr-list )
1239  *
1240  *  where the "identifier" must not be declared as a type, and
1241  *  "any-word" may be any identifier (including one declared as a
1242  *  type), a reserved word storage class specifier, type specifier or
1243  *  type qualifier.  ??? This still leaves out most reserved keywords
1244  *  (following the old parser), shouldn't we include them, and why not
1245  *  allow identifiers declared as types to start the arguments?
1246  *
1247  *  Matze: this all looks confusing and little systematic, so we're even less
1248  *  strict and parse any list of things which are identifiers or
1249  *  (assignment-)expressions.
1250  */
1251 static attribute_argument_t *parse_attribute_arguments(void)
1252 {
1253         attribute_argument_t *first = NULL;
1254         attribute_argument_t *last  = NULL;
1255         if (token.type != ')') do {
1256                 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1257
1258                 /* is it an identifier */
1259                 if (token.type == T_IDENTIFIER
1260                                 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1261                         symbol_t *symbol   = token.v.symbol;
1262                         argument->kind     = ATTRIBUTE_ARGUMENT_SYMBOL;
1263                         argument->v.symbol = symbol;
1264                         next_token();
1265                 } else {
1266                         /* must be an expression */
1267                         expression_t *expression = parse_assignment_expression();
1268
1269                         argument->kind         = ATTRIBUTE_ARGUMENT_EXPRESSION;
1270                         argument->v.expression = expression;
1271                 }
1272
1273                 /* append argument */
1274                 if (last == NULL) {
1275                         first = argument;
1276                 } else {
1277                         last->next = argument;
1278                 }
1279                 last = argument;
1280         } while (next_if(','));
1281         expect(')', end_error);
1282
1283         return first;
1284
1285 end_error:
1286         /* TODO... */
1287         return first;
1288 }
1289
1290 static attribute_t *parse_attribute_asm(void)
1291 {
1292         eat(T_asm);
1293
1294         attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1295
1296         expect('(', end_error);
1297         attribute->a.arguments = parse_attribute_arguments();
1298         return attribute;
1299
1300 end_error:
1301         return NULL;
1302 }
1303
1304 static symbol_t *get_symbol_from_token(void)
1305 {
1306         switch(token.type) {
1307         case T_IDENTIFIER:
1308                 return token.v.symbol;
1309         case T_auto:
1310         case T_char:
1311         case T_double:
1312         case T_enum:
1313         case T_extern:
1314         case T_float:
1315         case T_int:
1316         case T_long:
1317         case T_register:
1318         case T_short:
1319         case T_static:
1320         case T_struct:
1321         case T_union:
1322         case T_unsigned:
1323         case T_void:
1324         case T_bool:
1325         case T__Bool:
1326         case T_class:
1327         case T_explicit:
1328         case T_export:
1329         case T_wchar_t:
1330         case T_const:
1331         case T_signed:
1332         case T___real__:
1333         case T___imag__:
1334         case T_restrict:
1335         case T_volatile:
1336         case T_inline:
1337                 /* maybe we need more tokens ... add them on demand */
1338                 return get_token_symbol(&token);
1339         default:
1340                 return NULL;
1341         }
1342 }
1343
1344 static attribute_t *parse_attribute_gnu_single(void)
1345 {
1346         /* parse "any-word" */
1347         symbol_t *symbol = get_symbol_from_token();
1348         if (symbol == NULL) {
1349                 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1350                 goto end_error;
1351         }
1352
1353         const char *name = symbol->string;
1354         next_token();
1355
1356         attribute_kind_t kind;
1357         for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1358                 const char *attribute_name = get_attribute_name(kind);
1359                 if (attribute_name != NULL
1360                                 && strcmp_underscore(attribute_name, name) == 0)
1361                         break;
1362         }
1363
1364         if (kind >= ATTRIBUTE_GNU_LAST) {
1365                 if (warning.attribute) {
1366                         warningf(HERE, "unknown attribute '%s' ignored", name);
1367                 }
1368                 /* TODO: we should still save the attribute in the list... */
1369                 kind = ATTRIBUTE_UNKNOWN;
1370         }
1371
1372         attribute_t *attribute = allocate_attribute_zero(kind);
1373
1374         /* parse arguments */
1375         if (next_if('('))
1376                 attribute->a.arguments = parse_attribute_arguments();
1377
1378         return attribute;
1379
1380 end_error:
1381         return NULL;
1382 }
1383
1384 static attribute_t *parse_attribute_gnu(void)
1385 {
1386         attribute_t *first = NULL;
1387         attribute_t *last  = NULL;
1388
1389         eat(T___attribute__);
1390         expect('(', end_error);
1391         expect('(', end_error);
1392
1393         if (token.type != ')') do {
1394                 attribute_t *attribute = parse_attribute_gnu_single();
1395                 if (attribute == NULL)
1396                         goto end_error;
1397
1398                 if (last == NULL) {
1399                         first = attribute;
1400                 } else {
1401                         last->next = attribute;
1402                 }
1403                 last = attribute;
1404         } while (next_if(','));
1405         expect(')', end_error);
1406         expect(')', end_error);
1407
1408 end_error:
1409         return first;
1410 }
1411
1412 /** Parse attributes. */
1413 static attribute_t *parse_attributes(attribute_t *first)
1414 {
1415         attribute_t *last = first;
1416         while (true) {
1417                 if (last != NULL) {
1418                         while (last->next != NULL)
1419                                 last = last->next;
1420                 }
1421
1422                 attribute_t *attribute;
1423                 switch (token.type) {
1424                 case T___attribute__:
1425                         attribute = parse_attribute_gnu();
1426                         break;
1427
1428                 case T_asm:
1429                         attribute = parse_attribute_asm();
1430                         break;
1431
1432                 case T_cdecl:
1433                         next_token();
1434                         attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1435                         break;
1436
1437                 case T__fastcall:
1438                         next_token();
1439                         attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1440                         break;
1441
1442                 case T__forceinline:
1443                         next_token();
1444                         attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1445                         break;
1446
1447                 case T__stdcall:
1448                         next_token();
1449                         attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1450                         break;
1451
1452                 case T___thiscall:
1453                         next_token();
1454                         /* TODO record modifier */
1455                         if (warning.other)
1456                                 warningf(HERE, "Ignoring declaration modifier %K", &token);
1457                         attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1458                         break;
1459
1460                 default:
1461                         return first;
1462                 }
1463
1464                 if (last == NULL) {
1465                         first = attribute;
1466                 } else {
1467                         last->next = attribute;
1468                 }
1469                 last = attribute;
1470         }
1471 }
1472
1473 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1474
1475 static entity_t *determine_lhs_ent(expression_t *const expr,
1476                                    entity_t *lhs_ent)
1477 {
1478         switch (expr->kind) {
1479                 case EXPR_REFERENCE: {
1480                         entity_t *const entity = expr->reference.entity;
1481                         /* we should only find variables as lvalues... */
1482                         if (entity->base.kind != ENTITY_VARIABLE
1483                                         && entity->base.kind != ENTITY_PARAMETER)
1484                                 return NULL;
1485
1486                         return entity;
1487                 }
1488
1489                 case EXPR_ARRAY_ACCESS: {
1490                         expression_t *const ref = expr->array_access.array_ref;
1491                         entity_t     *      ent = NULL;
1492                         if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1493                                 ent     = determine_lhs_ent(ref, lhs_ent);
1494                                 lhs_ent = ent;
1495                         } else {
1496                                 mark_vars_read(expr->select.compound, lhs_ent);
1497                         }
1498                         mark_vars_read(expr->array_access.index, lhs_ent);
1499                         return ent;
1500                 }
1501
1502                 case EXPR_SELECT: {
1503                         if (is_type_compound(skip_typeref(expr->base.type))) {
1504                                 return determine_lhs_ent(expr->select.compound, lhs_ent);
1505                         } else {
1506                                 mark_vars_read(expr->select.compound, lhs_ent);
1507                                 return NULL;
1508                         }
1509                 }
1510
1511                 case EXPR_UNARY_DEREFERENCE: {
1512                         expression_t *const val = expr->unary.value;
1513                         if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1514                                 /* *&x is a NOP */
1515                                 return determine_lhs_ent(val->unary.value, lhs_ent);
1516                         } else {
1517                                 mark_vars_read(val, NULL);
1518                                 return NULL;
1519                         }
1520                 }
1521
1522                 default:
1523                         mark_vars_read(expr, NULL);
1524                         return NULL;
1525         }
1526 }
1527
1528 #define ENT_ANY ((entity_t*)-1)
1529
1530 /**
1531  * Mark declarations, which are read.  This is used to detect variables, which
1532  * are never read.
1533  * Example:
1534  * x = x + 1;
1535  *   x is not marked as "read", because it is only read to calculate its own new
1536  *   value.
1537  *
1538  * x += y; y += x;
1539  *   x and y are not detected as "not read", because multiple variables are
1540  *   involved.
1541  */
1542 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1543 {
1544         switch (expr->kind) {
1545                 case EXPR_REFERENCE: {
1546                         entity_t *const entity = expr->reference.entity;
1547                         if (entity->kind != ENTITY_VARIABLE
1548                                         && entity->kind != ENTITY_PARAMETER)
1549                                 return;
1550
1551                         if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1552                                 if (entity->kind == ENTITY_VARIABLE) {
1553                                         entity->variable.read = true;
1554                                 } else {
1555                                         entity->parameter.read = true;
1556                                 }
1557                         }
1558                         return;
1559                 }
1560
1561                 case EXPR_CALL:
1562                         // TODO respect pure/const
1563                         mark_vars_read(expr->call.function, NULL);
1564                         for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1565                                 mark_vars_read(arg->expression, NULL);
1566                         }
1567                         return;
1568
1569                 case EXPR_CONDITIONAL:
1570                         // TODO lhs_decl should depend on whether true/false have an effect
1571                         mark_vars_read(expr->conditional.condition, NULL);
1572                         if (expr->conditional.true_expression != NULL)
1573                                 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1574                         mark_vars_read(expr->conditional.false_expression, lhs_ent);
1575                         return;
1576
1577                 case EXPR_SELECT:
1578                         if (lhs_ent == ENT_ANY
1579                                         && !is_type_compound(skip_typeref(expr->base.type)))
1580                                 lhs_ent = NULL;
1581                         mark_vars_read(expr->select.compound, lhs_ent);
1582                         return;
1583
1584                 case EXPR_ARRAY_ACCESS: {
1585                         expression_t *const ref = expr->array_access.array_ref;
1586                         mark_vars_read(ref, lhs_ent);
1587                         lhs_ent = determine_lhs_ent(ref, lhs_ent);
1588                         mark_vars_read(expr->array_access.index, lhs_ent);
1589                         return;
1590                 }
1591
1592                 case EXPR_VA_ARG:
1593                         mark_vars_read(expr->va_arge.ap, lhs_ent);
1594                         return;
1595
1596                 case EXPR_VA_COPY:
1597                         mark_vars_read(expr->va_copye.src, lhs_ent);
1598                         return;
1599
1600                 case EXPR_UNARY_CAST:
1601                         /* Special case: Use void cast to mark a variable as "read" */
1602                         if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1603                                 lhs_ent = NULL;
1604                         goto unary;
1605
1606
1607                 case EXPR_UNARY_THROW:
1608                         if (expr->unary.value == NULL)
1609                                 return;
1610                         /* FALLTHROUGH */
1611                 case EXPR_UNARY_DEREFERENCE:
1612                 case EXPR_UNARY_DELETE:
1613                 case EXPR_UNARY_DELETE_ARRAY:
1614                         if (lhs_ent == ENT_ANY)
1615                                 lhs_ent = NULL;
1616                         goto unary;
1617
1618                 case EXPR_UNARY_NEGATE:
1619                 case EXPR_UNARY_PLUS:
1620                 case EXPR_UNARY_BITWISE_NEGATE:
1621                 case EXPR_UNARY_NOT:
1622                 case EXPR_UNARY_TAKE_ADDRESS:
1623                 case EXPR_UNARY_POSTFIX_INCREMENT:
1624                 case EXPR_UNARY_POSTFIX_DECREMENT:
1625                 case EXPR_UNARY_PREFIX_INCREMENT:
1626                 case EXPR_UNARY_PREFIX_DECREMENT:
1627                 case EXPR_UNARY_CAST_IMPLICIT:
1628                 case EXPR_UNARY_ASSUME:
1629 unary:
1630                         mark_vars_read(expr->unary.value, lhs_ent);
1631                         return;
1632
1633                 case EXPR_BINARY_ADD:
1634                 case EXPR_BINARY_SUB:
1635                 case EXPR_BINARY_MUL:
1636                 case EXPR_BINARY_DIV:
1637                 case EXPR_BINARY_MOD:
1638                 case EXPR_BINARY_EQUAL:
1639                 case EXPR_BINARY_NOTEQUAL:
1640                 case EXPR_BINARY_LESS:
1641                 case EXPR_BINARY_LESSEQUAL:
1642                 case EXPR_BINARY_GREATER:
1643                 case EXPR_BINARY_GREATEREQUAL:
1644                 case EXPR_BINARY_BITWISE_AND:
1645                 case EXPR_BINARY_BITWISE_OR:
1646                 case EXPR_BINARY_BITWISE_XOR:
1647                 case EXPR_BINARY_LOGICAL_AND:
1648                 case EXPR_BINARY_LOGICAL_OR:
1649                 case EXPR_BINARY_SHIFTLEFT:
1650                 case EXPR_BINARY_SHIFTRIGHT:
1651                 case EXPR_BINARY_COMMA:
1652                 case EXPR_BINARY_ISGREATER:
1653                 case EXPR_BINARY_ISGREATEREQUAL:
1654                 case EXPR_BINARY_ISLESS:
1655                 case EXPR_BINARY_ISLESSEQUAL:
1656                 case EXPR_BINARY_ISLESSGREATER:
1657                 case EXPR_BINARY_ISUNORDERED:
1658                         mark_vars_read(expr->binary.left,  lhs_ent);
1659                         mark_vars_read(expr->binary.right, lhs_ent);
1660                         return;
1661
1662                 case EXPR_BINARY_ASSIGN:
1663                 case EXPR_BINARY_MUL_ASSIGN:
1664                 case EXPR_BINARY_DIV_ASSIGN:
1665                 case EXPR_BINARY_MOD_ASSIGN:
1666                 case EXPR_BINARY_ADD_ASSIGN:
1667                 case EXPR_BINARY_SUB_ASSIGN:
1668                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1669                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1670                 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1671                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1672                 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1673                         if (lhs_ent == ENT_ANY)
1674                                 lhs_ent = NULL;
1675                         lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1676                         mark_vars_read(expr->binary.right, lhs_ent);
1677                         return;
1678                 }
1679
1680                 case EXPR_VA_START:
1681                         determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1682                         return;
1683
1684                 case EXPR_UNKNOWN:
1685                 case EXPR_INVALID:
1686                 case EXPR_CONST:
1687                 case EXPR_CHARACTER_CONSTANT:
1688                 case EXPR_WIDE_CHARACTER_CONSTANT:
1689                 case EXPR_STRING_LITERAL:
1690                 case EXPR_WIDE_STRING_LITERAL:
1691                 case EXPR_COMPOUND_LITERAL: // TODO init?
1692                 case EXPR_SIZEOF:
1693                 case EXPR_CLASSIFY_TYPE:
1694                 case EXPR_ALIGNOF:
1695                 case EXPR_FUNCNAME:
1696                 case EXPR_BUILTIN_CONSTANT_P:
1697                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1698                 case EXPR_OFFSETOF:
1699                 case EXPR_STATEMENT: // TODO
1700                 case EXPR_LABEL_ADDRESS:
1701                 case EXPR_REFERENCE_ENUM_VALUE:
1702                         return;
1703         }
1704
1705         panic("unhandled expression");
1706 }
1707
1708 static designator_t *parse_designation(void)
1709 {
1710         designator_t *result = NULL;
1711         designator_t *last   = NULL;
1712
1713         while (true) {
1714                 designator_t *designator;
1715                 switch (token.type) {
1716                 case '[':
1717                         designator = allocate_ast_zero(sizeof(designator[0]));
1718                         designator->source_position = token.source_position;
1719                         next_token();
1720                         add_anchor_token(']');
1721                         designator->array_index = parse_constant_expression();
1722                         rem_anchor_token(']');
1723                         expect(']', end_error);
1724                         break;
1725                 case '.':
1726                         designator = allocate_ast_zero(sizeof(designator[0]));
1727                         designator->source_position = token.source_position;
1728                         next_token();
1729                         if (token.type != T_IDENTIFIER) {
1730                                 parse_error_expected("while parsing designator",
1731                                                      T_IDENTIFIER, NULL);
1732                                 return NULL;
1733                         }
1734                         designator->symbol = token.v.symbol;
1735                         next_token();
1736                         break;
1737                 default:
1738                         expect('=', end_error);
1739                         return result;
1740                 }
1741
1742                 assert(designator != NULL);
1743                 if (last != NULL) {
1744                         last->next = designator;
1745                 } else {
1746                         result = designator;
1747                 }
1748                 last = designator;
1749         }
1750 end_error:
1751         return NULL;
1752 }
1753
1754 static initializer_t *initializer_from_string(array_type_t *type,
1755                                               const string_t *const string)
1756 {
1757         /* TODO: check len vs. size of array type */
1758         (void) type;
1759
1760         initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1761         initializer->string.string = *string;
1762
1763         return initializer;
1764 }
1765
1766 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1767                                                    wide_string_t *const string)
1768 {
1769         /* TODO: check len vs. size of array type */
1770         (void) type;
1771
1772         initializer_t *const initializer =
1773                 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1774         initializer->wide_string.string = *string;
1775
1776         return initializer;
1777 }
1778
1779 /**
1780  * Build an initializer from a given expression.
1781  */
1782 static initializer_t *initializer_from_expression(type_t *orig_type,
1783                                                   expression_t *expression)
1784 {
1785         /* TODO check that expression is a constant expression */
1786
1787         /* §6.7.8.14/15 char array may be initialized by string literals */
1788         type_t *type           = skip_typeref(orig_type);
1789         type_t *expr_type_orig = expression->base.type;
1790         type_t *expr_type      = skip_typeref(expr_type_orig);
1791         if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1792                 array_type_t *const array_type   = &type->array;
1793                 type_t       *const element_type = skip_typeref(array_type->element_type);
1794
1795                 if (element_type->kind == TYPE_ATOMIC) {
1796                         atomic_type_kind_t akind = element_type->atomic.akind;
1797                         switch (expression->kind) {
1798                                 case EXPR_STRING_LITERAL:
1799                                         if (akind == ATOMIC_TYPE_CHAR
1800                                                         || akind == ATOMIC_TYPE_SCHAR
1801                                                         || akind == ATOMIC_TYPE_UCHAR) {
1802                                                 return initializer_from_string(array_type,
1803                                                         &expression->string.value);
1804                                         }
1805                                         break;
1806
1807                                 case EXPR_WIDE_STRING_LITERAL: {
1808                                         type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1809                                         if (get_unqualified_type(element_type) == bare_wchar_type) {
1810                                                 return initializer_from_wide_string(array_type,
1811                                                         &expression->wide_string.value);
1812                                         }
1813                                         break;
1814                                 }
1815
1816                                 default:
1817                                         break;
1818                         }
1819                 }
1820         }
1821
1822         assign_error_t error = semantic_assign(type, expression);
1823         if (error == ASSIGN_ERROR_INCOMPATIBLE)
1824                 return NULL;
1825         report_assign_error(error, type, expression, "initializer",
1826                             &expression->base.source_position);
1827
1828         initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1829         result->value.value = create_implicit_cast(expression, type);
1830
1831         return result;
1832 }
1833
1834 /**
1835  * Checks if a given expression can be used as an constant initializer.
1836  */
1837 static bool is_initializer_constant(const expression_t *expression)
1838 {
1839         return is_constant_expression(expression)
1840                 || is_address_constant(expression);
1841 }
1842
1843 /**
1844  * Parses an scalar initializer.
1845  *
1846  * §6.7.8.11; eat {} without warning
1847  */
1848 static initializer_t *parse_scalar_initializer(type_t *type,
1849                                                bool must_be_constant)
1850 {
1851         /* there might be extra {} hierarchies */
1852         int braces = 0;
1853         if (next_if('{')) {
1854                 if (warning.other)
1855                         warningf(HERE, "extra curly braces around scalar initializer");
1856                 do {
1857                         ++braces;
1858                 } while (next_if('{'));
1859         }
1860
1861         expression_t *expression = parse_assignment_expression();
1862         mark_vars_read(expression, NULL);
1863         if (must_be_constant && !is_initializer_constant(expression)) {
1864                 errorf(&expression->base.source_position,
1865                        "initialisation expression '%E' is not constant",
1866                        expression);
1867         }
1868
1869         initializer_t *initializer = initializer_from_expression(type, expression);
1870
1871         if (initializer == NULL) {
1872                 errorf(&expression->base.source_position,
1873                        "expression '%E' (type '%T') doesn't match expected type '%T'",
1874                        expression, expression->base.type, type);
1875                 /* TODO */
1876                 return NULL;
1877         }
1878
1879         bool additional_warning_displayed = false;
1880         while (braces > 0) {
1881                 next_if(',');
1882                 if (token.type != '}') {
1883                         if (!additional_warning_displayed && warning.other) {
1884                                 warningf(HERE, "additional elements in scalar initializer");
1885                                 additional_warning_displayed = true;
1886                         }
1887                 }
1888                 eat_block();
1889                 braces--;
1890         }
1891
1892         return initializer;
1893 }
1894
1895 /**
1896  * An entry in the type path.
1897  */
1898 typedef struct type_path_entry_t type_path_entry_t;
1899 struct type_path_entry_t {
1900         type_t *type;       /**< the upper top type. restored to path->top_tye if this entry is popped. */
1901         union {
1902                 size_t         index;          /**< For array types: the current index. */
1903                 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1904         } v;
1905 };
1906
1907 /**
1908  * A type path expression a position inside compound or array types.
1909  */
1910 typedef struct type_path_t type_path_t;
1911 struct type_path_t {
1912         type_path_entry_t *path;         /**< An flexible array containing the current path. */
1913         type_t            *top_type;     /**< type of the element the path points */
1914         size_t             max_index;    /**< largest index in outermost array */
1915 };
1916
1917 /**
1918  * Prints a type path for debugging.
1919  */
1920 static __attribute__((unused)) void debug_print_type_path(
1921                 const type_path_t *path)
1922 {
1923         size_t len = ARR_LEN(path->path);
1924
1925         for (size_t i = 0; i < len; ++i) {
1926                 const type_path_entry_t *entry = & path->path[i];
1927
1928                 type_t *type = skip_typeref(entry->type);
1929                 if (is_type_compound(type)) {
1930                         /* in gcc mode structs can have no members */
1931                         if (entry->v.compound_entry == NULL) {
1932                                 assert(i == len-1);
1933                                 continue;
1934                         }
1935                         fprintf(stderr, ".%s",
1936                                 entry->v.compound_entry->base.symbol->string);
1937                 } else if (is_type_array(type)) {
1938                         fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1939                 } else {
1940                         fprintf(stderr, "-INVALID-");
1941                 }
1942         }
1943         if (path->top_type != NULL) {
1944                 fprintf(stderr, "  (");
1945                 print_type(path->top_type);
1946                 fprintf(stderr, ")");
1947         }
1948 }
1949
1950 /**
1951  * Return the top type path entry, ie. in a path
1952  * (type).a.b returns the b.
1953  */
1954 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1955 {
1956         size_t len = ARR_LEN(path->path);
1957         assert(len > 0);
1958         return &path->path[len-1];
1959 }
1960
1961 /**
1962  * Enlarge the type path by an (empty) element.
1963  */
1964 static type_path_entry_t *append_to_type_path(type_path_t *path)
1965 {
1966         size_t len = ARR_LEN(path->path);
1967         ARR_RESIZE(type_path_entry_t, path->path, len+1);
1968
1969         type_path_entry_t *result = & path->path[len];
1970         memset(result, 0, sizeof(result[0]));
1971         return result;
1972 }
1973
1974 /**
1975  * Descending into a sub-type. Enter the scope of the current top_type.
1976  */
1977 static void descend_into_subtype(type_path_t *path)
1978 {
1979         type_t *orig_top_type = path->top_type;
1980         type_t *top_type      = skip_typeref(orig_top_type);
1981
1982         type_path_entry_t *top = append_to_type_path(path);
1983         top->type              = top_type;
1984
1985         if (is_type_compound(top_type)) {
1986                 compound_t *compound  = top_type->compound.compound;
1987                 entity_t   *entry     = compound->members.entities;
1988
1989                 if (entry != NULL) {
1990                         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1991                         top->v.compound_entry = &entry->declaration;
1992                         path->top_type = entry->declaration.type;
1993                 } else {
1994                         path->top_type = NULL;
1995                 }
1996         } else if (is_type_array(top_type)) {
1997                 top->v.index   = 0;
1998                 path->top_type = top_type->array.element_type;
1999         } else {
2000                 assert(!is_type_valid(top_type));
2001         }
2002 }
2003
2004 /**
2005  * Pop an entry from the given type path, ie. returning from
2006  * (type).a.b to (type).a
2007  */
2008 static void ascend_from_subtype(type_path_t *path)
2009 {
2010         type_path_entry_t *top = get_type_path_top(path);
2011
2012         path->top_type = top->type;
2013
2014         size_t len = ARR_LEN(path->path);
2015         ARR_RESIZE(type_path_entry_t, path->path, len-1);
2016 }
2017
2018 /**
2019  * Pop entries from the given type path until the given
2020  * path level is reached.
2021  */
2022 static void ascend_to(type_path_t *path, size_t top_path_level)
2023 {
2024         size_t len = ARR_LEN(path->path);
2025
2026         while (len > top_path_level) {
2027                 ascend_from_subtype(path);
2028                 len = ARR_LEN(path->path);
2029         }
2030 }
2031
2032 static bool walk_designator(type_path_t *path, const designator_t *designator,
2033                             bool used_in_offsetof)
2034 {
2035         for (; designator != NULL; designator = designator->next) {
2036                 type_path_entry_t *top       = get_type_path_top(path);
2037                 type_t            *orig_type = top->type;
2038
2039                 type_t *type = skip_typeref(orig_type);
2040
2041                 if (designator->symbol != NULL) {
2042                         symbol_t *symbol = designator->symbol;
2043                         if (!is_type_compound(type)) {
2044                                 if (is_type_valid(type)) {
2045                                         errorf(&designator->source_position,
2046                                                "'.%Y' designator used for non-compound type '%T'",
2047                                                symbol, orig_type);
2048                                 }
2049
2050                                 top->type             = type_error_type;
2051                                 top->v.compound_entry = NULL;
2052                                 orig_type             = type_error_type;
2053                         } else {
2054                                 compound_t *compound = type->compound.compound;
2055                                 entity_t   *iter     = compound->members.entities;
2056                                 for (; iter != NULL; iter = iter->base.next) {
2057                                         if (iter->base.symbol == symbol) {
2058                                                 break;
2059                                         }
2060                                 }
2061                                 if (iter == NULL) {
2062                                         errorf(&designator->source_position,
2063                                                "'%T' has no member named '%Y'", orig_type, symbol);
2064                                         goto failed;
2065                                 }
2066                                 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2067                                 if (used_in_offsetof) {
2068                                         type_t *real_type = skip_typeref(iter->declaration.type);
2069                                         if (real_type->kind == TYPE_BITFIELD) {
2070                                                 errorf(&designator->source_position,
2071                                                        "offsetof designator '%Y' may not specify bitfield",
2072                                                        symbol);
2073                                                 goto failed;
2074                                         }
2075                                 }
2076
2077                                 top->type             = orig_type;
2078                                 top->v.compound_entry = &iter->declaration;
2079                                 orig_type             = iter->declaration.type;
2080                         }
2081                 } else {
2082                         expression_t *array_index = designator->array_index;
2083                         assert(designator->array_index != NULL);
2084
2085                         if (!is_type_array(type)) {
2086                                 if (is_type_valid(type)) {
2087                                         errorf(&designator->source_position,
2088                                                "[%E] designator used for non-array type '%T'",
2089                                                array_index, orig_type);
2090                                 }
2091                                 goto failed;
2092                         }
2093
2094                         long index = fold_constant_to_int(array_index);
2095                         if (!used_in_offsetof) {
2096                                 if (index < 0) {
2097                                         errorf(&designator->source_position,
2098                                                "array index [%E] must be positive", array_index);
2099                                 } else if (type->array.size_constant) {
2100                                         long array_size = type->array.size;
2101                                         if (index >= array_size) {
2102                                                 errorf(&designator->source_position,
2103                                                        "designator [%E] (%d) exceeds array size %d",
2104                                                        array_index, index, array_size);
2105                                         }
2106                                 }
2107                         }
2108
2109                         top->type    = orig_type;
2110                         top->v.index = (size_t) index;
2111                         orig_type    = type->array.element_type;
2112                 }
2113                 path->top_type = orig_type;
2114
2115                 if (designator->next != NULL) {
2116                         descend_into_subtype(path);
2117                 }
2118         }
2119         return true;
2120
2121 failed:
2122         return false;
2123 }
2124
2125 static void advance_current_object(type_path_t *path, size_t top_path_level)
2126 {
2127         type_path_entry_t *top = get_type_path_top(path);
2128
2129         type_t *type = skip_typeref(top->type);
2130         if (is_type_union(type)) {
2131                 /* in unions only the first element is initialized */
2132                 top->v.compound_entry = NULL;
2133         } else if (is_type_struct(type)) {
2134                 declaration_t *entry = top->v.compound_entry;
2135
2136                 entity_t *next_entity = entry->base.next;
2137                 if (next_entity != NULL) {
2138                         assert(is_declaration(next_entity));
2139                         entry = &next_entity->declaration;
2140                 } else {
2141                         entry = NULL;
2142                 }
2143
2144                 top->v.compound_entry = entry;
2145                 if (entry != NULL) {
2146                         path->top_type = entry->type;
2147                         return;
2148                 }
2149         } else if (is_type_array(type)) {
2150                 assert(is_type_array(type));
2151
2152                 top->v.index++;
2153
2154                 if (!type->array.size_constant || top->v.index < type->array.size) {
2155                         return;
2156                 }
2157         } else {
2158                 assert(!is_type_valid(type));
2159                 return;
2160         }
2161
2162         /* we're past the last member of the current sub-aggregate, try if we
2163          * can ascend in the type hierarchy and continue with another subobject */
2164         size_t len = ARR_LEN(path->path);
2165
2166         if (len > top_path_level) {
2167                 ascend_from_subtype(path);
2168                 advance_current_object(path, top_path_level);
2169         } else {
2170                 path->top_type = NULL;
2171         }
2172 }
2173
2174 /**
2175  * skip any {...} blocks until a closing bracket is reached.
2176  */
2177 static void skip_initializers(void)
2178 {
2179         next_if('{');
2180
2181         while (token.type != '}') {
2182                 if (token.type == T_EOF)
2183                         return;
2184                 if (token.type == '{') {
2185                         eat_block();
2186                         continue;
2187                 }
2188                 next_token();
2189         }
2190 }
2191
2192 static initializer_t *create_empty_initializer(void)
2193 {
2194         static initializer_t empty_initializer
2195                 = { .list = { { INITIALIZER_LIST }, 0 } };
2196         return &empty_initializer;
2197 }
2198
2199 /**
2200  * Parse a part of an initialiser for a struct or union,
2201  */
2202 static initializer_t *parse_sub_initializer(type_path_t *path,
2203                 type_t *outer_type, size_t top_path_level,
2204                 parse_initializer_env_t *env)
2205 {
2206         if (token.type == '}') {
2207                 /* empty initializer */
2208                 return create_empty_initializer();
2209         }
2210
2211         type_t *orig_type = path->top_type;
2212         type_t *type      = NULL;
2213
2214         if (orig_type == NULL) {
2215                 /* We are initializing an empty compound. */
2216         } else {
2217                 type = skip_typeref(orig_type);
2218         }
2219
2220         initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2221
2222         while (true) {
2223                 designator_t *designator = NULL;
2224                 if (token.type == '.' || token.type == '[') {
2225                         designator = parse_designation();
2226                         goto finish_designator;
2227                 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2228                         /* GNU-style designator ("identifier: value") */
2229                         designator = allocate_ast_zero(sizeof(designator[0]));
2230                         designator->source_position = token.source_position;
2231                         designator->symbol          = token.v.symbol;
2232                         eat(T_IDENTIFIER);
2233                         eat(':');
2234
2235 finish_designator:
2236                         /* reset path to toplevel, evaluate designator from there */
2237                         ascend_to(path, top_path_level);
2238                         if (!walk_designator(path, designator, false)) {
2239                                 /* can't continue after designation error */
2240                                 goto end_error;
2241                         }
2242
2243                         initializer_t *designator_initializer
2244                                 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2245                         designator_initializer->designator.designator = designator;
2246                         ARR_APP1(initializer_t*, initializers, designator_initializer);
2247
2248                         orig_type = path->top_type;
2249                         type      = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2250                 }
2251
2252                 initializer_t *sub;
2253
2254                 if (token.type == '{') {
2255                         if (type != NULL && is_type_scalar(type)) {
2256                                 sub = parse_scalar_initializer(type, env->must_be_constant);
2257                         } else {
2258                                 eat('{');
2259                                 if (type == NULL) {
2260                                         if (env->entity != NULL) {
2261                                                 errorf(HERE,
2262                                                      "extra brace group at end of initializer for '%Y'",
2263                                                      env->entity->base.symbol);
2264                                         } else {
2265                                                 errorf(HERE, "extra brace group at end of initializer");
2266                                         }
2267                                 } else
2268                                         descend_into_subtype(path);
2269
2270                                 add_anchor_token('}');
2271                                 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2272                                                             env);
2273                                 rem_anchor_token('}');
2274
2275                                 if (type != NULL) {
2276                                         ascend_from_subtype(path);
2277                                         expect('}', end_error);
2278                                 } else {
2279                                         expect('}', end_error);
2280                                         goto error_parse_next;
2281                                 }
2282                         }
2283                 } else {
2284                         /* must be an expression */
2285                         expression_t *expression = parse_assignment_expression();
2286                         mark_vars_read(expression, NULL);
2287
2288                         if (env->must_be_constant && !is_initializer_constant(expression)) {
2289                                 errorf(&expression->base.source_position,
2290                                        "Initialisation expression '%E' is not constant",
2291                                        expression);
2292                         }
2293
2294                         if (type == NULL) {
2295                                 /* we are already outside, ... */
2296                                 if (outer_type == NULL)
2297                                         goto error_parse_next;
2298                                 type_t *const outer_type_skip = skip_typeref(outer_type);
2299                                 if (is_type_compound(outer_type_skip) &&
2300                                     !outer_type_skip->compound.compound->complete) {
2301                                         goto error_parse_next;
2302                                 }
2303                                 goto error_excess;
2304                         }
2305
2306                         /* handle { "string" } special case */
2307                         if ((expression->kind == EXPR_STRING_LITERAL
2308                                         || expression->kind == EXPR_WIDE_STRING_LITERAL)
2309                                         && outer_type != NULL) {
2310                                 sub = initializer_from_expression(outer_type, expression);
2311                                 if (sub != NULL) {
2312                                         next_if(',');
2313                                         if (token.type != '}' && warning.other) {
2314                                                 warningf(HERE, "excessive elements in initializer for type '%T'",
2315                                                                  orig_type);
2316                                         }
2317                                         /* TODO: eat , ... */
2318                                         return sub;
2319                                 }
2320                         }
2321
2322                         /* descend into subtypes until expression matches type */
2323                         while (true) {
2324                                 orig_type = path->top_type;
2325                                 type      = skip_typeref(orig_type);
2326
2327                                 sub = initializer_from_expression(orig_type, expression);
2328                                 if (sub != NULL) {
2329                                         break;
2330                                 }
2331                                 if (!is_type_valid(type)) {
2332                                         goto end_error;
2333                                 }
2334                                 if (is_type_scalar(type)) {
2335                                         errorf(&expression->base.source_position,
2336                                                         "expression '%E' doesn't match expected type '%T'",
2337                                                         expression, orig_type);
2338                                         goto end_error;
2339                                 }
2340
2341                                 descend_into_subtype(path);
2342                         }
2343                 }
2344
2345                 /* update largest index of top array */
2346                 const type_path_entry_t *first      = &path->path[0];
2347                 type_t                  *first_type = first->type;
2348                 first_type                          = skip_typeref(first_type);
2349                 if (is_type_array(first_type)) {
2350                         size_t index = first->v.index;
2351                         if (index > path->max_index)
2352                                 path->max_index = index;
2353                 }
2354
2355                 if (type != NULL) {
2356                         /* append to initializers list */
2357                         ARR_APP1(initializer_t*, initializers, sub);
2358                 } else {
2359 error_excess:
2360                         if (warning.other) {
2361                                 if (env->entity != NULL) {
2362                                         warningf(HERE, "excess elements in initializer for '%Y'",
2363                                                  env->entity->base.symbol);
2364                                 } else {
2365                                         warningf(HERE, "excess elements in initializer");
2366                                 }
2367                         }
2368                 }
2369
2370 error_parse_next:
2371                 if (token.type == '}') {
2372                         break;
2373                 }
2374                 expect(',', end_error);
2375                 if (token.type == '}') {
2376                         break;
2377                 }
2378
2379                 if (type != NULL) {
2380                         /* advance to the next declaration if we are not at the end */
2381                         advance_current_object(path, top_path_level);
2382                         orig_type = path->top_type;
2383                         if (orig_type != NULL)
2384                                 type = skip_typeref(orig_type);
2385                         else
2386                                 type = NULL;
2387                 }
2388         }
2389
2390         size_t len  = ARR_LEN(initializers);
2391         size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2392         initializer_t *result = allocate_ast_zero(size);
2393         result->kind          = INITIALIZER_LIST;
2394         result->list.len      = len;
2395         memcpy(&result->list.initializers, initializers,
2396                len * sizeof(initializers[0]));
2397
2398         DEL_ARR_F(initializers);
2399         ascend_to(path, top_path_level+1);
2400
2401         return result;
2402
2403 end_error:
2404         skip_initializers();
2405         DEL_ARR_F(initializers);
2406         ascend_to(path, top_path_level+1);
2407         return NULL;
2408 }
2409
2410 /**
2411  * Parses an initializer. Parsers either a compound literal
2412  * (env->declaration == NULL) or an initializer of a declaration.
2413  */
2414 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2415 {
2416         type_t        *type      = skip_typeref(env->type);
2417         size_t         max_index = 0xdeadbeaf;   // TODO: Resolve this uninitialized variable problem
2418         initializer_t *result;
2419
2420         if (is_type_scalar(type)) {
2421                 result = parse_scalar_initializer(type, env->must_be_constant);
2422         } else if (token.type == '{') {
2423                 eat('{');
2424
2425                 type_path_t path;
2426                 memset(&path, 0, sizeof(path));
2427                 path.top_type = env->type;
2428                 path.path     = NEW_ARR_F(type_path_entry_t, 0);
2429
2430                 descend_into_subtype(&path);
2431
2432                 add_anchor_token('}');
2433                 result = parse_sub_initializer(&path, env->type, 1, env);
2434                 rem_anchor_token('}');
2435
2436                 max_index = path.max_index;
2437                 DEL_ARR_F(path.path);
2438
2439                 expect('}', end_error);
2440         } else {
2441                 /* parse_scalar_initializer() also works in this case: we simply
2442                  * have an expression without {} around it */
2443                 result = parse_scalar_initializer(type, env->must_be_constant);
2444         }
2445
2446         /* §6.7.8:22 array initializers for arrays with unknown size determine
2447          * the array type size */
2448         if (is_type_array(type) && type->array.size_expression == NULL
2449                         && result != NULL) {
2450                 size_t size;
2451                 switch (result->kind) {
2452                 case INITIALIZER_LIST:
2453                         assert(max_index != 0xdeadbeaf);
2454                         size = max_index + 1;
2455                         break;
2456
2457                 case INITIALIZER_STRING:
2458                         size = result->string.string.size;
2459                         break;
2460
2461                 case INITIALIZER_WIDE_STRING:
2462                         size = result->wide_string.string.size;
2463                         break;
2464
2465                 case INITIALIZER_DESIGNATOR:
2466                 case INITIALIZER_VALUE:
2467                         /* can happen for parse errors */
2468                         size = 0;
2469                         break;
2470
2471                 default:
2472                         internal_errorf(HERE, "invalid initializer type");
2473                 }
2474
2475                 expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
2476                 cnst->base.type          = type_size_t;
2477                 cnst->conste.v.int_value = size;
2478
2479                 type_t *new_type = duplicate_type(type);
2480
2481                 new_type->array.size_expression   = cnst;
2482                 new_type->array.size_constant     = true;
2483                 new_type->array.has_implicit_size = true;
2484                 new_type->array.size              = size;
2485                 env->type = new_type;
2486         }
2487
2488         return result;
2489 end_error:
2490         return NULL;
2491 }
2492
2493 static void append_entity(scope_t *scope, entity_t *entity)
2494 {
2495         if (scope->last_entity != NULL) {
2496                 scope->last_entity->base.next = entity;
2497         } else {
2498                 scope->entities = entity;
2499         }
2500         scope->last_entity = entity;
2501 }
2502
2503
2504 static compound_t *parse_compound_type_specifier(bool is_struct)
2505 {
2506         eat(is_struct ? T_struct : T_union);
2507
2508         symbol_t    *symbol   = NULL;
2509         compound_t  *compound = NULL;
2510         attribute_t *attributes = NULL;
2511
2512         if (token.type == T___attribute__) {
2513                 attributes = parse_attributes(NULL);
2514         }
2515
2516         entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2517         if (token.type == T_IDENTIFIER) {
2518                 /* the compound has a name, check if we have seen it already */
2519                 symbol = token.v.symbol;
2520                 next_token();
2521
2522                 entity_t *entity = get_tag(symbol, kind);
2523                 if (entity != NULL) {
2524                         compound = &entity->compound;
2525                         if (compound->base.parent_scope != current_scope &&
2526                             (token.type == '{' || token.type == ';')) {
2527                                 /* we're in an inner scope and have a definition. Shadow
2528                                  * existing definition in outer scope */
2529                                 compound = NULL;
2530                         } else if (compound->complete && token.type == '{') {
2531                                 assert(symbol != NULL);
2532                                 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2533                                        is_struct ? "struct" : "union", symbol,
2534                                        &compound->base.source_position);
2535                                 /* clear members in the hope to avoid further errors */
2536                                 compound->members.entities = NULL;
2537                         }
2538                 }
2539         } else if (token.type != '{') {
2540                 if (is_struct) {
2541                         parse_error_expected("while parsing struct type specifier",
2542                                              T_IDENTIFIER, '{', NULL);
2543                 } else {
2544                         parse_error_expected("while parsing union type specifier",
2545                                              T_IDENTIFIER, '{', NULL);
2546                 }
2547
2548                 return NULL;
2549         }
2550
2551         if (compound == NULL) {
2552                 entity_t *entity = allocate_entity_zero(kind);
2553                 compound         = &entity->compound;
2554
2555                 compound->alignment            = 1;
2556                 compound->base.namespc         = NAMESPACE_TAG;
2557                 compound->base.source_position = token.source_position;
2558                 compound->base.symbol          = symbol;
2559                 compound->base.parent_scope    = current_scope;
2560                 if (symbol != NULL) {
2561                         environment_push(entity);
2562                 }
2563                 append_entity(current_scope, entity);
2564         }
2565
2566         if (token.type == '{') {
2567                 parse_compound_type_entries(compound);
2568
2569                 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2570                 if (symbol == NULL) {
2571                         assert(anonymous_entity == NULL);
2572                         anonymous_entity = (entity_t*)compound;
2573                 }
2574         }
2575
2576         if (attributes != NULL) {
2577                 handle_entity_attributes(attributes, (entity_t*) compound);
2578         }
2579
2580         return compound;
2581 }
2582
2583 static void parse_enum_entries(type_t *const enum_type)
2584 {
2585         eat('{');
2586
2587         if (token.type == '}') {
2588                 errorf(HERE, "empty enum not allowed");
2589                 next_token();
2590                 return;
2591         }
2592
2593         add_anchor_token('}');
2594         do {
2595                 if (token.type != T_IDENTIFIER) {
2596                         parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2597                         eat_block();
2598                         rem_anchor_token('}');
2599                         return;
2600                 }
2601
2602                 entity_t *entity             = allocate_entity_zero(ENTITY_ENUM_VALUE);
2603                 entity->enum_value.enum_type = enum_type;
2604                 entity->base.symbol          = token.v.symbol;
2605                 entity->base.source_position = token.source_position;
2606                 next_token();
2607
2608                 if (next_if('=')) {
2609                         expression_t *value = parse_constant_expression();
2610
2611                         value = create_implicit_cast(value, enum_type);
2612                         entity->enum_value.value = value;
2613
2614                         /* TODO semantic */
2615                 }
2616
2617                 record_entity(entity, false);
2618         } while (next_if(',') && token.type != '}');
2619         rem_anchor_token('}');
2620
2621         expect('}', end_error);
2622
2623 end_error:
2624         ;
2625 }
2626
2627 static type_t *parse_enum_specifier(void)
2628 {
2629         entity_t        *entity;
2630         symbol_t        *symbol;
2631
2632         eat(T_enum);
2633         if (token.type == T_IDENTIFIER) {
2634                 symbol = token.v.symbol;
2635                 next_token();
2636
2637                 entity = get_tag(symbol, ENTITY_ENUM);
2638                 if (entity != NULL) {
2639                         if (entity->base.parent_scope != current_scope &&
2640                                         (token.type == '{' || token.type == ';')) {
2641                                 /* we're in an inner scope and have a definition. Shadow
2642                                  * existing definition in outer scope */
2643                                 entity = NULL;
2644                         } else if (entity->enume.complete && token.type == '{') {
2645                                 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2646                                                 symbol, &entity->base.source_position);
2647                         }
2648                 }
2649         } else if (token.type != '{') {
2650                 parse_error_expected("while parsing enum type specifier",
2651                                      T_IDENTIFIER, '{', NULL);
2652                 return NULL;
2653         } else {
2654                 entity  = NULL;
2655                 symbol  = NULL;
2656         }
2657
2658         if (entity == NULL) {
2659                 entity                       = allocate_entity_zero(ENTITY_ENUM);
2660                 entity->base.namespc         = NAMESPACE_TAG;
2661                 entity->base.source_position = token.source_position;
2662                 entity->base.symbol          = symbol;
2663                 entity->base.parent_scope    = current_scope;
2664         }
2665
2666         type_t *const type = allocate_type_zero(TYPE_ENUM);
2667         type->enumt.enume  = &entity->enume;
2668         type->enumt.akind  = ATOMIC_TYPE_INT;
2669
2670         if (token.type == '{') {
2671                 if (symbol != NULL) {
2672                         environment_push(entity);
2673                 }
2674                 append_entity(current_scope, entity);
2675                 entity->enume.complete = true;
2676
2677                 parse_enum_entries(type);
2678                 parse_attributes(NULL);
2679
2680                 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2681                 if (symbol == NULL) {
2682                         assert(anonymous_entity == NULL);
2683                         anonymous_entity = entity;
2684                 }
2685         } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2686                 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2687                        symbol);
2688         }
2689
2690         return type;
2691 }
2692
2693 /**
2694  * if a symbol is a typedef to another type, return true
2695  */
2696 static bool is_typedef_symbol(symbol_t *symbol)
2697 {
2698         const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2699         return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2700 }
2701
2702 static type_t *parse_typeof(void)
2703 {
2704         eat(T___typeof__);
2705
2706         type_t *type;
2707
2708         expect('(', end_error);
2709         add_anchor_token(')');
2710
2711         expression_t *expression  = NULL;
2712
2713         bool old_type_prop     = in_type_prop;
2714         bool old_gcc_extension = in_gcc_extension;
2715         in_type_prop           = true;
2716
2717         while (next_if(T___extension__)) {
2718                 /* This can be a prefix to a typename or an expression. */
2719                 in_gcc_extension = true;
2720         }
2721         switch (token.type) {
2722         case T_IDENTIFIER:
2723                 if (is_typedef_symbol(token.v.symbol)) {
2724                         type = parse_typename();
2725                 } else {
2726                         expression = parse_expression();
2727                         type       = revert_automatic_type_conversion(expression);
2728                 }
2729                 break;
2730
2731         TYPENAME_START
2732                 type = parse_typename();
2733                 break;
2734
2735         default:
2736                 expression = parse_expression();
2737                 type       = expression->base.type;
2738                 break;
2739         }
2740         in_type_prop     = old_type_prop;
2741         in_gcc_extension = old_gcc_extension;
2742
2743         rem_anchor_token(')');
2744         expect(')', end_error);
2745
2746         type_t *typeof_type              = allocate_type_zero(TYPE_TYPEOF);
2747         typeof_type->typeoft.expression  = expression;
2748         typeof_type->typeoft.typeof_type = type;
2749
2750         return typeof_type;
2751 end_error:
2752         return NULL;
2753 }
2754
2755 typedef enum specifiers_t {
2756         SPECIFIER_SIGNED    = 1 << 0,
2757         SPECIFIER_UNSIGNED  = 1 << 1,
2758         SPECIFIER_LONG      = 1 << 2,
2759         SPECIFIER_INT       = 1 << 3,
2760         SPECIFIER_DOUBLE    = 1 << 4,
2761         SPECIFIER_CHAR      = 1 << 5,
2762         SPECIFIER_WCHAR_T   = 1 << 6,
2763         SPECIFIER_SHORT     = 1 << 7,
2764         SPECIFIER_LONG_LONG = 1 << 8,
2765         SPECIFIER_FLOAT     = 1 << 9,
2766         SPECIFIER_BOOL      = 1 << 10,
2767         SPECIFIER_VOID      = 1 << 11,
2768         SPECIFIER_INT8      = 1 << 12,
2769         SPECIFIER_INT16     = 1 << 13,
2770         SPECIFIER_INT32     = 1 << 14,
2771         SPECIFIER_INT64     = 1 << 15,
2772         SPECIFIER_INT128    = 1 << 16,
2773         SPECIFIER_COMPLEX   = 1 << 17,
2774         SPECIFIER_IMAGINARY = 1 << 18,
2775 } specifiers_t;
2776
2777 static type_t *create_builtin_type(symbol_t *const symbol,
2778                                    type_t *const real_type)
2779 {
2780         type_t *type            = allocate_type_zero(TYPE_BUILTIN);
2781         type->builtin.symbol    = symbol;
2782         type->builtin.real_type = real_type;
2783         return identify_new_type(type);
2784 }
2785
2786 static type_t *get_typedef_type(symbol_t *symbol)
2787 {
2788         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2789         if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2790                 return NULL;
2791
2792         type_t *type            = allocate_type_zero(TYPE_TYPEDEF);
2793         type->typedeft.typedefe = &entity->typedefe;
2794
2795         return type;
2796 }
2797
2798 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2799 {
2800         expect('(', end_error);
2801
2802         attribute_property_argument_t *property
2803                 = allocate_ast_zero(sizeof(*property));
2804
2805         do {
2806                 if (token.type != T_IDENTIFIER) {
2807                         parse_error_expected("while parsing property declspec",
2808                                              T_IDENTIFIER, NULL);
2809                         goto end_error;
2810                 }
2811
2812                 bool is_put;
2813                 symbol_t *symbol = token.v.symbol;
2814                 next_token();
2815                 if (strcmp(symbol->string, "put") == 0) {
2816                         is_put = true;
2817                 } else if (strcmp(symbol->string, "get") == 0) {
2818                         is_put = false;
2819                 } else {
2820                         errorf(HERE, "expected put or get in property declspec");
2821                         goto end_error;
2822                 }
2823                 expect('=', end_error);
2824                 if (token.type != T_IDENTIFIER) {
2825                         parse_error_expected("while parsing property declspec",
2826                                              T_IDENTIFIER, NULL);
2827                         goto end_error;
2828                 }
2829                 if (is_put) {
2830                         property->put_symbol = token.v.symbol;
2831                 } else {
2832                         property->get_symbol = token.v.symbol;
2833                 }
2834                 next_token();
2835         } while (next_if(','));
2836
2837         attribute->a.property = property;
2838
2839         expect(')', end_error);
2840
2841 end_error:
2842         return attribute;
2843 }
2844
2845 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2846 {
2847         attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2848         if (next_if(T_restrict)) {
2849                 kind = ATTRIBUTE_MS_RESTRICT;
2850         } else if (token.type == T_IDENTIFIER) {
2851                 const char *name = token.v.symbol->string;
2852                 next_token();
2853                 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2854                      ++k) {
2855                         const char *attribute_name = get_attribute_name(k);
2856                         if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2857                                 kind = k;
2858                                 break;
2859                         }
2860                 }
2861
2862                 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2863                         warningf(HERE, "unknown __declspec '%s' ignored", name);
2864                 }
2865         } else {
2866                 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2867                 return NULL;
2868         }
2869
2870         attribute_t *attribute = allocate_attribute_zero(kind);
2871
2872         if (kind == ATTRIBUTE_MS_PROPERTY) {
2873                 return parse_attribute_ms_property(attribute);
2874         }
2875
2876         /* parse arguments */
2877         if (next_if('('))
2878                 attribute->a.arguments = parse_attribute_arguments();
2879
2880         return attribute;
2881 }
2882
2883 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2884 {
2885         eat(T__declspec);
2886
2887         expect('(', end_error);
2888
2889         if (next_if(')'))
2890                 return NULL;
2891
2892         add_anchor_token(')');
2893
2894         attribute_t *last = first;
2895         do {
2896                 if (last != NULL) {
2897                         while (last->next != NULL)
2898                                 last = last->next;
2899                 }
2900
2901                 attribute_t *attribute
2902                         = parse_microsoft_extended_decl_modifier_single();
2903                 if (attribute == NULL)
2904                         goto end_error;
2905
2906                 if (last == NULL) {
2907                         first = attribute;
2908                 } else {
2909                         last->next = attribute;
2910                 }
2911                 last = attribute;
2912         } while (next_if(','));
2913
2914         rem_anchor_token(')');
2915         expect(')', end_error);
2916         return first;
2917
2918 end_error:
2919         rem_anchor_token(')');
2920         return first;
2921 }
2922
2923 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2924 {
2925         entity_t *entity             = allocate_entity_zero(kind);
2926         entity->base.source_position = *HERE;
2927         entity->base.symbol          = symbol;
2928         if (is_declaration(entity)) {
2929                 entity->declaration.type     = type_error_type;
2930                 entity->declaration.implicit = true;
2931         } else if (kind == ENTITY_TYPEDEF) {
2932                 entity->typedefe.type    = type_error_type;
2933                 entity->typedefe.builtin = true;
2934         }
2935         if (kind != ENTITY_COMPOUND_MEMBER)
2936                 record_entity(entity, false);
2937         return entity;
2938 }
2939
2940 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2941 {
2942         type_t            *type              = NULL;
2943         type_qualifiers_t  qualifiers        = TYPE_QUALIFIER_NONE;
2944         unsigned           type_specifiers   = 0;
2945         bool               newtype           = false;
2946         bool               saw_error         = false;
2947         bool               old_gcc_extension = in_gcc_extension;
2948
2949         specifiers->source_position = token.source_position;
2950
2951         while (true) {
2952                 specifiers->attributes = parse_attributes(specifiers->attributes);
2953
2954                 switch (token.type) {
2955                 /* storage class */
2956 #define MATCH_STORAGE_CLASS(token, class)                                  \
2957                 case token:                                                        \
2958                         if (specifiers->storage_class != STORAGE_CLASS_NONE) {         \
2959                                 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2960                         }                                                              \
2961                         specifiers->storage_class = class;                             \
2962                         if (specifiers->thread_local)                                  \
2963                                 goto check_thread_storage_class;                           \
2964                         next_token();                                                  \
2965                         break;
2966
2967                 MATCH_STORAGE_CLASS(T_typedef,  STORAGE_CLASS_TYPEDEF)
2968                 MATCH_STORAGE_CLASS(T_extern,   STORAGE_CLASS_EXTERN)
2969                 MATCH_STORAGE_CLASS(T_static,   STORAGE_CLASS_STATIC)
2970                 MATCH_STORAGE_CLASS(T_auto,     STORAGE_CLASS_AUTO)
2971                 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2972
2973                 case T__declspec:
2974                         specifiers->attributes
2975                                 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2976                         break;
2977
2978                 case T___thread:
2979                         if (specifiers->thread_local) {
2980                                 errorf(HERE, "duplicate '__thread'");
2981                         } else {
2982                                 specifiers->thread_local = true;
2983 check_thread_storage_class:
2984                                 switch (specifiers->storage_class) {
2985                                         case STORAGE_CLASS_EXTERN:
2986                                         case STORAGE_CLASS_NONE:
2987                                         case STORAGE_CLASS_STATIC:
2988                                                 break;
2989
2990                                                 char const* wrong;
2991                                         case STORAGE_CLASS_AUTO:     wrong = "auto";     goto wrong_thread_stoarge_class;
2992                                         case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2993                                         case STORAGE_CLASS_TYPEDEF:  wrong = "typedef";  goto wrong_thread_stoarge_class;
2994 wrong_thread_stoarge_class:
2995                                                 errorf(HERE, "'__thread' used with '%s'", wrong);
2996                                                 break;
2997                                 }
2998                         }
2999                         next_token();
3000                         break;
3001
3002                 /* type qualifiers */
3003 #define MATCH_TYPE_QUALIFIER(token, qualifier)                          \
3004                 case token:                                                     \
3005                         qualifiers |= qualifier;                                    \
3006                         next_token();                                               \
3007                         break
3008
3009                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3010                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3011                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3012                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3013                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3014                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3015                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3016                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3017
3018                 case T___extension__:
3019                         next_token();
3020                         in_gcc_extension = true;
3021                         break;
3022
3023                 /* type specifiers */
3024 #define MATCH_SPECIFIER(token, specifier, name)                         \
3025                 case token:                                                     \
3026                         if (type_specifiers & specifier) {                           \
3027                                 errorf(HERE, "multiple " name " type specifiers given"); \
3028                         } else {                                                    \
3029                                 type_specifiers |= specifier;                           \
3030                         }                                                           \
3031                         next_token();                                               \
3032                         break
3033
3034                 MATCH_SPECIFIER(T__Bool,      SPECIFIER_BOOL,      "_Bool");
3035                 MATCH_SPECIFIER(T__Complex,   SPECIFIER_COMPLEX,   "_Complex");
3036                 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3037                 MATCH_SPECIFIER(T__int128,    SPECIFIER_INT128,    "_int128");
3038                 MATCH_SPECIFIER(T__int16,     SPECIFIER_INT16,     "_int16");
3039                 MATCH_SPECIFIER(T__int32,     SPECIFIER_INT32,     "_int32");
3040                 MATCH_SPECIFIER(T__int64,     SPECIFIER_INT64,     "_int64");
3041                 MATCH_SPECIFIER(T__int8,      SPECIFIER_INT8,      "_int8");
3042                 MATCH_SPECIFIER(T_bool,       SPECIFIER_BOOL,      "bool");
3043                 MATCH_SPECIFIER(T_char,       SPECIFIER_CHAR,      "char");
3044                 MATCH_SPECIFIER(T_double,     SPECIFIER_DOUBLE,    "double");
3045                 MATCH_SPECIFIER(T_float,      SPECIFIER_FLOAT,     "float");
3046                 MATCH_SPECIFIER(T_int,        SPECIFIER_INT,       "int");
3047                 MATCH_SPECIFIER(T_short,      SPECIFIER_SHORT,     "short");
3048                 MATCH_SPECIFIER(T_signed,     SPECIFIER_SIGNED,    "signed");
3049                 MATCH_SPECIFIER(T_unsigned,   SPECIFIER_UNSIGNED,  "unsigned");
3050                 MATCH_SPECIFIER(T_void,       SPECIFIER_VOID,      "void");
3051                 MATCH_SPECIFIER(T_wchar_t,    SPECIFIER_WCHAR_T,   "wchar_t");
3052
3053                 case T_inline:
3054                         next_token();
3055                         specifiers->is_inline = true;
3056                         break;
3057
3058 #if 0
3059                 case T__forceinline:
3060                         next_token();
3061                         specifiers->modifiers |= DM_FORCEINLINE;
3062                         break;
3063 #endif
3064
3065                 case T_long:
3066                         if (type_specifiers & SPECIFIER_LONG_LONG) {
3067                                 errorf(HERE, "multiple type specifiers given");
3068                         } else if (type_specifiers & SPECIFIER_LONG) {
3069                                 type_specifiers |= SPECIFIER_LONG_LONG;
3070                         } else {
3071                                 type_specifiers |= SPECIFIER_LONG;
3072                         }
3073                         next_token();
3074                         break;
3075
3076 #define CHECK_DOUBLE_TYPE()        \
3077                         if ( type != NULL)     \
3078                                 errorf(HERE, "multiple data types in declaration specifiers");
3079
3080                 case T_struct:
3081                         CHECK_DOUBLE_TYPE();
3082                         type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3083
3084                         type->compound.compound = parse_compound_type_specifier(true);
3085                         break;
3086                 case T_union:
3087                         CHECK_DOUBLE_TYPE();
3088                         type = allocate_type_zero(TYPE_COMPOUND_UNION);
3089                         type->compound.compound = parse_compound_type_specifier(false);
3090                         break;
3091                 case T_enum:
3092                         CHECK_DOUBLE_TYPE();
3093                         type = parse_enum_specifier();
3094                         break;
3095                 case T___typeof__:
3096                         CHECK_DOUBLE_TYPE();
3097                         type = parse_typeof();
3098                         break;
3099                 case T___builtin_va_list:
3100                         CHECK_DOUBLE_TYPE();
3101                         type = duplicate_type(type_valist);
3102                         next_token();
3103                         break;
3104
3105                 case T_IDENTIFIER: {
3106                         /* only parse identifier if we haven't found a type yet */
3107                         if (type != NULL || type_specifiers != 0) {
3108                                 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3109                                  * declaration, so it doesn't generate errors about expecting '(' or
3110                                  * '{' later on. */
3111                                 switch (look_ahead(1)->type) {
3112                                         STORAGE_CLASSES
3113                                         TYPE_SPECIFIERS
3114                                         case T_const:
3115                                         case T_restrict:
3116                                         case T_volatile:
3117                                         case T_inline:
3118                                         case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3119                                         case T_IDENTIFIER:
3120                                         case '&':
3121                                         case '*':
3122                                                 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3123                                                 next_token();
3124                                                 continue;
3125
3126                                         default:
3127                                                 goto finish_specifiers;
3128                                 }
3129                         }
3130
3131                         type_t *const typedef_type = get_typedef_type(token.v.symbol);
3132                         if (typedef_type == NULL) {
3133                                 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3134                                  * declaration, so it doesn't generate 'implicit int' followed by more
3135                                  * errors later on. */
3136                                 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3137                                 switch (la1_type) {
3138                                         DECLARATION_START
3139                                         case T_IDENTIFIER:
3140                                         case '&':
3141                                         case '*': {
3142                                                 errorf(HERE, "%K does not name a type", &token);
3143
3144                                                 entity_t *entity =
3145                                                         create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3146
3147                                                 type = allocate_type_zero(TYPE_TYPEDEF);
3148                                                 type->typedeft.typedefe = &entity->typedefe;
3149
3150                                                 next_token();
3151                                                 saw_error = true;
3152                                                 if (la1_type == '&' || la1_type == '*')
3153                                                         goto finish_specifiers;
3154                                                 continue;
3155                                         }
3156
3157                                         default:
3158                                                 goto finish_specifiers;
3159                                 }
3160                         }
3161
3162                         next_token();
3163                         type = typedef_type;
3164                         break;
3165                 }
3166
3167                 /* function specifier */
3168                 default:
3169                         goto finish_specifiers;
3170                 }
3171         }
3172
3173 finish_specifiers:
3174         specifiers->attributes = parse_attributes(specifiers->attributes);
3175
3176         in_gcc_extension = old_gcc_extension;
3177
3178         if (type == NULL || (saw_error && type_specifiers != 0)) {
3179                 atomic_type_kind_t atomic_type;
3180
3181                 /* match valid basic types */
3182                 switch (type_specifiers) {
3183                 case SPECIFIER_VOID:
3184                         atomic_type = ATOMIC_TYPE_VOID;
3185                         break;
3186                 case SPECIFIER_WCHAR_T:
3187                         atomic_type = ATOMIC_TYPE_WCHAR_T;
3188                         break;
3189                 case SPECIFIER_CHAR:
3190                         atomic_type = ATOMIC_TYPE_CHAR;
3191                         break;
3192                 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3193                         atomic_type = ATOMIC_TYPE_SCHAR;
3194                         break;
3195                 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3196                         atomic_type = ATOMIC_TYPE_UCHAR;
3197                         break;
3198                 case SPECIFIER_SHORT:
3199                 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3200                 case SPECIFIER_SHORT | SPECIFIER_INT:
3201                 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3202                         atomic_type = ATOMIC_TYPE_SHORT;
3203                         break;
3204                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3205                 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3206                         atomic_type = ATOMIC_TYPE_USHORT;
3207                         break;
3208                 case SPECIFIER_INT:
3209                 case SPECIFIER_SIGNED:
3210                 case SPECIFIER_SIGNED | SPECIFIER_INT:
3211                         atomic_type = ATOMIC_TYPE_INT;
3212                         break;
3213                 case SPECIFIER_UNSIGNED:
3214                 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3215                         atomic_type = ATOMIC_TYPE_UINT;
3216                         break;
3217                 case SPECIFIER_LONG:
3218                 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3219                 case SPECIFIER_LONG | SPECIFIER_INT:
3220                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3221                         atomic_type = ATOMIC_TYPE_LONG;
3222                         break;
3223                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3224                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3225                         atomic_type = ATOMIC_TYPE_ULONG;
3226                         break;
3227
3228                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3229                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3230                 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3231                 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3232                         | SPECIFIER_INT:
3233                         atomic_type = ATOMIC_TYPE_LONGLONG;
3234                         goto warn_about_long_long;
3235
3236                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3237                 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3238                         | SPECIFIER_INT:
3239                         atomic_type = ATOMIC_TYPE_ULONGLONG;
3240 warn_about_long_long:
3241                         if (warning.long_long) {
3242                                 warningf(&specifiers->source_position,
3243                                          "ISO C90 does not support 'long long'");
3244                         }
3245                         break;
3246
3247                 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3248                         atomic_type = unsigned_int8_type_kind;
3249                         break;
3250
3251                 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3252                         atomic_type = unsigned_int16_type_kind;
3253                         break;
3254
3255                 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3256                         atomic_type = unsigned_int32_type_kind;
3257                         break;
3258
3259                 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3260                         atomic_type = unsigned_int64_type_kind;
3261                         break;
3262
3263                 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3264                         atomic_type = unsigned_int128_type_kind;
3265                         break;
3266
3267                 case SPECIFIER_INT8:
3268                 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3269                         atomic_type = int8_type_kind;
3270                         break;
3271
3272                 case SPECIFIER_INT16:
3273                 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3274                         atomic_type = int16_type_kind;
3275                         break;
3276
3277                 case SPECIFIER_INT32:
3278                 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3279                         atomic_type = int32_type_kind;
3280                         break;
3281
3282                 case SPECIFIER_INT64:
3283                 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3284                         atomic_type = int64_type_kind;
3285                         break;
3286
3287                 case SPECIFIER_INT128:
3288                 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3289                         atomic_type = int128_type_kind;
3290                         break;
3291
3292                 case SPECIFIER_FLOAT:
3293                         atomic_type = ATOMIC_TYPE_FLOAT;
3294                         break;
3295                 case SPECIFIER_DOUBLE:
3296                         atomic_type = ATOMIC_TYPE_DOUBLE;
3297                         break;
3298                 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3299                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3300                         break;
3301                 case SPECIFIER_BOOL:
3302                         atomic_type = ATOMIC_TYPE_BOOL;
3303                         break;
3304                 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3305                 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3306                         atomic_type = ATOMIC_TYPE_FLOAT;
3307                         break;
3308                 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3309                 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3310                         atomic_type = ATOMIC_TYPE_DOUBLE;
3311                         break;
3312                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3313                 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3314                         atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3315                         break;
3316                 default:
3317                         /* invalid specifier combination, give an error message */
3318                         if (type_specifiers == 0) {
3319                                 if (saw_error)
3320                                         goto end_error;
3321
3322                                 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3323                                 if (!(c_mode & _CXX) && !strict_mode) {
3324                                         if (warning.implicit_int) {
3325                                                 warningf(HERE, "no type specifiers in declaration, using 'int'");
3326                                         }
3327                                         atomic_type = ATOMIC_TYPE_INT;
3328                                         break;
3329                                 } else {
3330                                         errorf(HERE, "no type specifiers given in declaration");
3331                                 }
3332                         } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3333                                   (type_specifiers & SPECIFIER_UNSIGNED)) {
3334                                 errorf(HERE, "signed and unsigned specifiers given");
3335                         } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3336                                 errorf(HERE, "only integer types can be signed or unsigned");
3337                         } else {
3338                                 errorf(HERE, "multiple datatypes in declaration");
3339                         }
3340                         goto end_error;
3341                 }
3342
3343                 if (type_specifiers & SPECIFIER_COMPLEX) {
3344                         type                = allocate_type_zero(TYPE_COMPLEX);
3345                         type->complex.akind = atomic_type;
3346                 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3347                         type                  = allocate_type_zero(TYPE_IMAGINARY);
3348                         type->imaginary.akind = atomic_type;
3349                 } else {
3350                         type                 = allocate_type_zero(TYPE_ATOMIC);
3351                         type->atomic.akind   = atomic_type;
3352                 }
3353                 newtype = true;
3354         } else if (type_specifiers != 0) {
3355                 errorf(HERE, "multiple datatypes in declaration");
3356         }
3357
3358         /* FIXME: check type qualifiers here */
3359         type->base.qualifiers = qualifiers;
3360
3361         if (newtype) {
3362                 type = identify_new_type(type);
3363         } else {
3364                 type = typehash_insert(type);
3365         }
3366
3367         if (specifiers->attributes != NULL)
3368                 type = handle_type_attributes(specifiers->attributes, type);
3369         specifiers->type = type;
3370         return;
3371
3372 end_error:
3373         specifiers->type = type_error_type;
3374 }
3375
3376 static type_qualifiers_t parse_type_qualifiers(void)
3377 {
3378         type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3379
3380         while (true) {
3381                 switch (token.type) {
3382                 /* type qualifiers */
3383                 MATCH_TYPE_QUALIFIER(T_const,    TYPE_QUALIFIER_CONST);
3384                 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3385                 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3386                 /* microsoft extended type modifiers */
3387                 MATCH_TYPE_QUALIFIER(T__w64,     TYPE_QUALIFIER_W64);
3388                 MATCH_TYPE_QUALIFIER(T___ptr32,  TYPE_QUALIFIER_PTR32);
3389                 MATCH_TYPE_QUALIFIER(T___ptr64,  TYPE_QUALIFIER_PTR64);
3390                 MATCH_TYPE_QUALIFIER(T___uptr,   TYPE_QUALIFIER_UPTR);
3391                 MATCH_TYPE_QUALIFIER(T___sptr,   TYPE_QUALIFIER_SPTR);
3392
3393                 default:
3394                         return qualifiers;
3395                 }
3396         }
3397 }
3398
3399 /**
3400  * Parses an K&R identifier list
3401  */
3402 static void parse_identifier_list(scope_t *scope)
3403 {
3404         do {
3405                 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3406                 entity->base.source_position = token.source_position;
3407                 entity->base.namespc         = NAMESPACE_NORMAL;
3408                 entity->base.symbol          = token.v.symbol;
3409                 /* a K&R parameter has no type, yet */
3410                 next_token();
3411
3412                 if (scope != NULL)
3413                         append_entity(scope, entity);
3414         } while (next_if(',') && token.type == T_IDENTIFIER);
3415 }
3416
3417 static entity_t *parse_parameter(void)
3418 {
3419         declaration_specifiers_t specifiers;
3420         memset(&specifiers, 0, sizeof(specifiers));
3421
3422         parse_declaration_specifiers(&specifiers);
3423
3424         entity_t *entity = parse_declarator(&specifiers,
3425                         DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3426         anonymous_entity = NULL;
3427         return entity;
3428 }
3429
3430 static void semantic_parameter_incomplete(const entity_t *entity)
3431 {
3432         assert(entity->kind == ENTITY_PARAMETER);
3433
3434         /* §6.7.5.3:4  After adjustment, the parameters in a parameter type
3435          *             list in a function declarator that is part of a
3436          *             definition of that function shall not have
3437          *             incomplete type. */
3438         type_t *type = skip_typeref(entity->declaration.type);
3439         if (is_type_incomplete(type)) {
3440                 errorf(&entity->base.source_position,
3441                                 "parameter '%#T' has incomplete type",
3442                                 entity->declaration.type, entity->base.symbol);
3443         }
3444 }
3445
3446 static bool has_parameters(void)
3447 {
3448         /* func(void) is not a parameter */
3449         if (token.type == T_IDENTIFIER) {
3450                 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3451                 if (entity == NULL)
3452                         return true;
3453                 if (entity->kind != ENTITY_TYPEDEF)
3454                         return true;
3455                 if (skip_typeref(entity->typedefe.type) != type_void)
3456                         return true;
3457         } else if (token.type != T_void) {
3458                 return true;
3459         }
3460         if (look_ahead(1)->type != ')')
3461                 return true;
3462         next_token();
3463         return false;
3464 }
3465
3466 /**
3467  * Parses function type parameters (and optionally creates variable_t entities
3468  * for them in a scope)
3469  */
3470 static void parse_parameters(function_type_t *type, scope_t *scope)
3471 {
3472         eat('(');
3473         add_anchor_token(')');
3474         int saved_comma_state = save_and_reset_anchor_state(',');
3475
3476         if (token.type == T_IDENTIFIER &&
3477             !is_typedef_symbol(token.v.symbol)) {
3478                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3479                 if (la1_type == ',' || la1_type == ')') {
3480                         type->kr_style_parameters = true;
3481                         parse_identifier_list(scope);
3482                         goto parameters_finished;
3483                 }
3484         }
3485
3486         if (token.type == ')') {
3487                 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3488                 if (!(c_mode & _CXX))
3489                         type->unspecified_parameters = true;
3490                 goto parameters_finished;
3491         }
3492
3493         if (has_parameters()) {
3494                 function_parameter_t **anchor = &type->parameters;
3495                 do {
3496                         switch (token.type) {
3497                         case T_DOTDOTDOT:
3498                                 next_token();
3499                                 type->variadic = true;
3500                                 goto parameters_finished;
3501
3502                         case T_IDENTIFIER:
3503                         case T___extension__:
3504                         DECLARATION_START
3505                         {
3506                                 entity_t *entity = parse_parameter();
3507                                 if (entity->kind == ENTITY_TYPEDEF) {
3508                                         errorf(&entity->base.source_position,
3509                                                         "typedef not allowed as function parameter");
3510                                         break;
3511                                 }
3512                                 assert(is_declaration(entity));
3513
3514                                 semantic_parameter_incomplete(entity);
3515
3516                                 function_parameter_t *const parameter =
3517                                         allocate_parameter(entity->declaration.type);
3518
3519                                 if (scope != NULL) {
3520                                         append_entity(scope, entity);
3521                                 }
3522
3523                                 *anchor = parameter;
3524                                 anchor  = &parameter->next;
3525                                 break;
3526                         }
3527
3528                         default:
3529                                 goto parameters_finished;
3530                         }
3531                 } while (next_if(','));
3532         }
3533
3534
3535 parameters_finished:
3536         rem_anchor_token(')');
3537         expect(')', end_error);
3538
3539 end_error:
3540         restore_anchor_state(',', saved_comma_state);
3541 }
3542
3543 typedef enum construct_type_kind_t {
3544         CONSTRUCT_INVALID,
3545         CONSTRUCT_POINTER,
3546         CONSTRUCT_REFERENCE,
3547         CONSTRUCT_FUNCTION,
3548         CONSTRUCT_ARRAY
3549 } construct_type_kind_t;
3550
3551 typedef union construct_type_t construct_type_t;
3552
3553 typedef struct construct_type_base_t {
3554         construct_type_kind_t  kind;
3555         construct_type_t      *next;
3556 } construct_type_base_t;
3557
3558 typedef struct parsed_pointer_t {
3559         construct_type_base_t  base;
3560         type_qualifiers_t      type_qualifiers;
3561         variable_t            *base_variable;  /**< MS __based extension. */
3562 } parsed_pointer_t;
3563
3564 typedef struct parsed_reference_t {
3565         construct_type_base_t base;
3566 } parsed_reference_t;
3567
3568 typedef struct construct_function_type_t {
3569         construct_type_base_t  base;
3570         type_t                *function_type;
3571 } construct_function_type_t;
3572
3573 typedef struct parsed_array_t {
3574         construct_type_base_t  base;
3575         type_qualifiers_t      type_qualifiers;
3576         bool                   is_static;
3577         bool                   is_variable;
3578         expression_t          *size;
3579 } parsed_array_t;
3580
3581 union construct_type_t {
3582         construct_type_kind_t     kind;
3583         construct_type_base_t     base;
3584         parsed_pointer_t          pointer;
3585         parsed_reference_t        reference;
3586         construct_function_type_t function;
3587         parsed_array_t            array;
3588 };
3589
3590 static construct_type_t *parse_pointer_declarator(void)
3591 {
3592         eat('*');
3593
3594         parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3595         memset(pointer, 0, sizeof(pointer[0]));
3596         pointer->base.kind       = CONSTRUCT_POINTER;
3597         pointer->type_qualifiers = parse_type_qualifiers();
3598         //pointer->base_variable       = base_variable;
3599
3600         return (construct_type_t*) pointer;
3601 }
3602
3603 static construct_type_t *parse_reference_declarator(void)
3604 {
3605         eat('&');
3606
3607         construct_type_t   *cons      = obstack_alloc(&temp_obst, sizeof(cons->reference));
3608         parsed_reference_t *reference = &cons->reference;
3609         memset(reference, 0, sizeof(*reference));
3610         cons->kind = CONSTRUCT_REFERENCE;
3611
3612         return cons;
3613 }
3614
3615 static construct_type_t *parse_array_declarator(void)
3616 {
3617         eat('[');
3618         add_anchor_token(']');
3619
3620         construct_type_t *cons  = obstack_alloc(&temp_obst, sizeof(cons->array));
3621         parsed_array_t   *array = &cons->array;
3622         memset(array, 0, sizeof(*array));
3623         cons->kind = CONSTRUCT_ARRAY;
3624
3625         if (next_if(T_static))
3626                 array->is_static = true;
3627
3628         type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3629         if (type_qualifiers != 0 && next_if(T_static))
3630                         array->is_static = true;
3631         array->type_qualifiers = type_qualifiers;
3632
3633         if (token.type == '*' && look_ahead(1)->type == ']') {
3634                 array->is_variable = true;
3635                 next_token();
3636         } else if (token.type != ']') {
3637                 expression_t *const size = parse_assignment_expression();
3638
3639                 /* §6.7.5.2:1  Array size must have integer type */
3640                 type_t *const orig_type = size->base.type;
3641                 type_t *const type      = skip_typeref(orig_type);
3642                 if (!is_type_integer(type) && is_type_valid(type)) {
3643                         errorf(&size->base.source_position,
3644                                "array size '%E' must have integer type but has type '%T'",
3645                                size, orig_type);
3646                 }
3647
3648                 array->size = size;
3649                 mark_vars_read(size, NULL);
3650         }
3651
3652         rem_anchor_token(']');
3653         expect(']', end_error);
3654
3655 end_error:
3656         return cons;
3657 }
3658
3659 static construct_type_t *parse_function_declarator(scope_t *scope)
3660 {
3661         type_t          *type  = allocate_type_zero(TYPE_FUNCTION);
3662         function_type_t *ftype = &type->function;
3663
3664         ftype->linkage            = current_linkage;
3665         ftype->calling_convention = CC_DEFAULT;
3666
3667         parse_parameters(ftype, scope);
3668
3669         construct_type_t          *cons     = obstack_alloc(&temp_obst, sizeof(cons->function));
3670         construct_function_type_t *function = &cons->function;
3671         memset(function, 0, sizeof(*function));
3672         cons->kind              = CONSTRUCT_FUNCTION;
3673         function->function_type = type;
3674
3675         return cons;
3676 }
3677
3678 typedef struct parse_declarator_env_t {
3679         bool               may_be_abstract : 1;
3680         bool               must_be_abstract : 1;
3681         decl_modifiers_t   modifiers;
3682         symbol_t          *symbol;
3683         source_position_t  source_position;
3684         scope_t            parameters;
3685         attribute_t       *attributes;
3686 } parse_declarator_env_t;
3687
3688 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3689 {
3690         /* construct a single linked list of construct_type_t's which describe
3691          * how to construct the final declarator type */
3692         construct_type_t  *first      = NULL;
3693         construct_type_t **anchor     = &first;
3694
3695         env->attributes = parse_attributes(env->attributes);
3696
3697         for (;;) {
3698                 construct_type_t *type;
3699                 //variable_t       *based = NULL; /* MS __based extension */
3700                 switch (token.type) {
3701                         case '&':
3702                                 if (!(c_mode & _CXX))
3703                                         errorf(HERE, "references are only available for C++");
3704                                 type = parse_reference_declarator();
3705                                 break;
3706
3707                         case T__based: {
3708 #if 0
3709                                 source_position_t const pos = *HERE;
3710                                 next_token();
3711                                 expect('(', end_error);
3712                                 add_anchor_token(')');
3713                                 based = parse_microsoft_based();
3714                                 rem_anchor_token(')');
3715                                 expect(')', end_error);
3716                                 if (token.type != '*') {
3717                                         if (token.type == T__based) {
3718                                                 errorf(&pos, "__based type modifier specified more than once");
3719                                         } else if (warning.other) {
3720                                                 warningf(&pos,
3721                                                                 "__based does not precede a pointer declarator, ignored");
3722                                         }
3723                                         continue;
3724                                 }
3725 #else
3726                                 panic("based currently disabled");
3727 #endif
3728                                 /* FALLTHROUGH */
3729                         }
3730
3731                         case '*':
3732                                 type = parse_pointer_declarator();
3733                                 break;
3734
3735                         default:
3736                                 goto ptr_operator_end;
3737                 }
3738
3739                 *anchor = type;
3740                 anchor  = &type->base.next;
3741
3742                 /* TODO: find out if this is correct */
3743                 env->attributes = parse_attributes(env->attributes);
3744         }
3745
3746 ptr_operator_end: ;
3747 #if 0
3748         modifiers      |= env->modifiers;
3749         env->modifiers  = modifiers;
3750 #endif
3751
3752         construct_type_t *inner_types = NULL;
3753
3754         switch (token.type) {
3755         case T_IDENTIFIER:
3756                 if (env->must_be_abstract) {
3757                         errorf(HERE, "no identifier expected in typename");
3758                 } else {
3759                         env->symbol          = token.v.symbol;
3760                         env->source_position = token.source_position;
3761                 }
3762                 next_token();
3763                 break;
3764         case '(':
3765                 /* §6.7.6:2 footnote 126:  Empty parentheses in a type name are
3766                  * interpreted as ``function with no parameter specification'', rather
3767                  * than redundant parentheses around the omitted identifier. */
3768                 if (look_ahead(1)->type != ')') {
3769                         next_token();
3770                         add_anchor_token(')');
3771                         inner_types = parse_inner_declarator(env);
3772                         if (inner_types != NULL) {
3773                                 /* All later declarators only modify the return type */
3774                                 env->must_be_abstract = true;
3775                         }
3776                         rem_anchor_token(')');
3777                         expect(')', end_error);
3778                 }
3779                 break;
3780         default:
3781                 if (env->may_be_abstract)
3782                         break;
3783                 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3784                 eat_until_anchor();
3785                 return NULL;
3786         }
3787
3788         construct_type_t **const p = anchor;
3789
3790         for (;;) {
3791                 construct_type_t *type;
3792                 switch (token.type) {
3793                 case '(': {
3794                         scope_t *scope = NULL;
3795                         if (!env->must_be_abstract) {
3796                                 scope = &env->parameters;
3797                         }
3798
3799                         type = parse_function_declarator(scope);
3800                         break;
3801                 }
3802                 case '[':
3803                         type = parse_array_declarator();
3804                         break;
3805                 default:
3806                         goto declarator_finished;
3807                 }
3808
3809                 /* insert in the middle of the list (at p) */
3810                 type->base.next = *p;
3811                 *p              = type;
3812                 if (anchor == p)
3813                         anchor = &type->base.next;
3814         }
3815
3816 declarator_finished:
3817         /* append inner_types at the end of the list, we don't to set anchor anymore
3818          * as it's not needed anymore */
3819         *anchor = inner_types;
3820
3821         return first;
3822 end_error:
3823         return NULL;
3824 }
3825
3826 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3827 {
3828         construct_type_t *iter = construct_list;
3829         for (; iter != NULL; iter = iter->base.next) {
3830                 switch (iter->kind) {
3831                 case CONSTRUCT_INVALID:
3832                         break;
3833                 case CONSTRUCT_FUNCTION: {
3834                         construct_function_type_t *function      = &iter->function;
3835                         type_t                    *function_type = function->function_type;
3836
3837                         function_type->function.return_type = type;
3838
3839                         type_t *skipped_return_type = skip_typeref(type);
3840                         /* §6.7.5.3:1 */
3841                         if (is_type_function(skipped_return_type)) {
3842                                 errorf(HERE, "function returning function is not allowed");
3843                         } else if (is_type_array(skipped_return_type)) {
3844                                 errorf(HERE, "function returning array is not allowed");
3845                         } else {
3846                                 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3847                                         warningf(HERE,
3848                                                 "type qualifiers in return type of function type are meaningless");
3849                                 }
3850                         }
3851
3852                         /* The function type was constructed earlier.  Freeing it here will
3853                          * destroy other types. */
3854                         type = typehash_insert(function_type);
3855                         continue;
3856                 }
3857
3858                 case CONSTRUCT_POINTER: {
3859                         if (is_type_reference(skip_typeref(type)))
3860                                 errorf(HERE, "cannot declare a pointer to reference");
3861
3862                         parsed_pointer_t *pointer = &iter->pointer;
3863                         type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3864                         continue;
3865                 }
3866
3867                 case CONSTRUCT_REFERENCE:
3868                         if (is_type_reference(skip_typeref(type)))
3869                                 errorf(HERE, "cannot declare a reference to reference");
3870
3871                         type = make_reference_type(type);
3872                         continue;
3873
3874                 case CONSTRUCT_ARRAY: {
3875                         if (is_type_reference(skip_typeref(type)))
3876                                 errorf(HERE, "cannot declare an array of references");
3877
3878                         parsed_array_t *array      = &iter->array;
3879                         type_t         *array_type = allocate_type_zero(TYPE_ARRAY);
3880
3881                         expression_t *size_expression = array->size;
3882                         if (size_expression != NULL) {
3883                                 size_expression
3884                                         = create_implicit_cast(size_expression, type_size_t);
3885                         }
3886
3887                         array_type->base.qualifiers       = array->type_qualifiers;
3888                         array_type->array.element_type    = type;
3889                         array_type->array.is_static       = array->is_static;
3890                         array_type->array.is_variable     = array->is_variable;
3891                         array_type->array.size_expression = size_expression;
3892
3893                         if (size_expression != NULL) {
3894                                 if (is_constant_expression(size_expression)) {
3895                                         long const size
3896                                                 = fold_constant_to_int(size_expression);
3897                                         array_type->array.size          = size;
3898                                         array_type->array.size_constant = true;
3899                                         /* §6.7.5.2:1  If the expression is a constant expression, it shall
3900                                          * have a value greater than zero. */
3901                                         if (size <= 0) {
3902                                                 if (size < 0 || !GNU_MODE) {
3903                                                         errorf(&size_expression->base.source_position,
3904                                                                         "size of array must be greater than zero");
3905                                                 } else if (warning.other) {
3906                                                         warningf(&size_expression->base.source_position,
3907                                                                         "zero length arrays are a GCC extension");
3908                                                 }
3909                                         }
3910                                 } else {
3911                                         array_type->array.is_vla = true;
3912                                 }
3913                         }
3914
3915                         type_t *skipped_type = skip_typeref(type);
3916                         /* §6.7.5.2:1 */
3917                         if (is_type_incomplete(skipped_type)) {
3918                                 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3919                         } else if (is_type_function(skipped_type)) {
3920                                 errorf(HERE, "array of functions is not allowed");
3921                         }
3922                         type = identify_new_type(array_type);
3923                         continue;
3924                 }
3925                 }
3926                 internal_errorf(HERE, "invalid type construction found");
3927         }
3928
3929         return type;
3930 }
3931
3932 static type_t *automatic_type_conversion(type_t *orig_type);
3933
3934 static type_t *semantic_parameter(const source_position_t *pos,
3935                                   type_t *type,
3936                                   const declaration_specifiers_t *specifiers,
3937                                   symbol_t *symbol)
3938 {
3939         /* §6.7.5.3:7  A declaration of a parameter as ``array of type''
3940          *             shall be adjusted to ``qualified pointer to type'',
3941          *             [...]
3942          * §6.7.5.3:8  A declaration of a parameter as ``function returning
3943          *             type'' shall be adjusted to ``pointer to function
3944          *             returning type'', as in 6.3.2.1. */
3945         type = automatic_type_conversion(type);
3946
3947         if (specifiers->is_inline && is_type_valid(type)) {
3948                 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3949         }
3950
3951         /* §6.9.1:6  The declarations in the declaration list shall contain
3952          *           no storage-class specifier other than register and no
3953          *           initializations. */
3954         if (specifiers->thread_local || (
3955                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
3956                         specifiers->storage_class != STORAGE_CLASS_REGISTER)
3957            ) {
3958                 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3959         }
3960
3961         /* delay test for incomplete type, because we might have (void)
3962          * which is legal but incomplete... */
3963
3964         return type;
3965 }
3966
3967 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3968                                   declarator_flags_t flags)
3969 {
3970         parse_declarator_env_t env;
3971         memset(&env, 0, sizeof(env));
3972         env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3973
3974         construct_type_t *construct_type = parse_inner_declarator(&env);
3975         type_t           *orig_type      =
3976                 construct_declarator_type(construct_type, specifiers->type);
3977         type_t           *type           = skip_typeref(orig_type);
3978
3979         if (construct_type != NULL) {
3980                 obstack_free(&temp_obst, construct_type);
3981         }
3982
3983         attribute_t *attributes = parse_attributes(env.attributes);
3984         /* append (shared) specifier attribute behind attributes of this
3985            declarator */
3986         if (attributes != NULL) {
3987                 attribute_t *last = attributes;
3988                 while (last->next != NULL)
3989                         last = last->next;
3990                 last->next = specifiers->attributes;
3991         } else {
3992                 attributes = specifiers->attributes;
3993         }
3994
3995         entity_t *entity;
3996         if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3997                 entity                       = allocate_entity_zero(ENTITY_TYPEDEF);
3998                 entity->base.symbol          = env.symbol;
3999                 entity->base.source_position = env.source_position;
4000                 entity->typedefe.type        = orig_type;
4001
4002                 if (anonymous_entity != NULL) {
4003                         if (is_type_compound(type)) {
4004                                 assert(anonymous_entity->compound.alias == NULL);
4005                                 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4006                                        anonymous_entity->kind == ENTITY_UNION);
4007                                 anonymous_entity->compound.alias = entity;
4008                                 anonymous_entity = NULL;
4009                         } else if (is_type_enum(type)) {
4010                                 assert(anonymous_entity->enume.alias == NULL);
4011                                 assert(anonymous_entity->kind == ENTITY_ENUM);
4012                                 anonymous_entity->enume.alias = entity;
4013                                 anonymous_entity = NULL;
4014                         }
4015                 }
4016         } else {
4017                 /* create a declaration type entity */
4018                 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4019                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4020
4021                         if (env.symbol != NULL) {
4022                                 if (specifiers->is_inline && is_type_valid(type)) {
4023                                         errorf(&env.source_position,
4024                                                         "compound member '%Y' declared 'inline'", env.symbol);
4025                                 }
4026
4027                                 if (specifiers->thread_local ||
4028                                                 specifiers->storage_class != STORAGE_CLASS_NONE) {
4029                                         errorf(&env.source_position,
4030                                                         "compound member '%Y' must have no storage class",
4031                                                         env.symbol);
4032                                 }
4033                         }
4034                 } else if (flags & DECL_IS_PARAMETER) {
4035                         orig_type = semantic_parameter(&env.source_position, orig_type,
4036                                                        specifiers, env.symbol);
4037
4038                         entity = allocate_entity_zero(ENTITY_PARAMETER);
4039                 } else if (is_type_function(type)) {
4040                         entity = allocate_entity_zero(ENTITY_FUNCTION);
4041
4042                         entity->function.is_inline  = specifiers->is_inline;
4043                         entity->function.parameters = env.parameters;
4044
4045                         if (env.symbol != NULL) {
4046                                 /* this needs fixes for C++ */
4047                                 bool in_function_scope = current_function != NULL;
4048
4049                                 if (specifiers->thread_local || (
4050                                       specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4051                                           specifiers->storage_class != STORAGE_CLASS_NONE   &&
4052                                           (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4053                                    )) {
4054                                         errorf(&env.source_position,
4055                                                         "invalid storage class for function '%Y'", env.symbol);
4056                                 }
4057                         }
4058                 } else {
4059                         entity = allocate_entity_zero(ENTITY_VARIABLE);
4060
4061                         entity->variable.thread_local = specifiers->thread_local;
4062
4063                         if (env.symbol != NULL) {
4064                                 if (specifiers->is_inline && is_type_valid(type)) {
4065                                         errorf(&env.source_position,
4066                                                         "variable '%Y' declared 'inline'", env.symbol);
4067                                 }
4068
4069                                 bool invalid_storage_class = false;
4070                                 if (current_scope == file_scope) {
4071                                         if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4072                                                         specifiers->storage_class != STORAGE_CLASS_NONE   &&
4073                                                         specifiers->storage_class != STORAGE_CLASS_STATIC) {
4074                                                 invalid_storage_class = true;
4075                                         }
4076                                 } else {
4077                                         if (specifiers->thread_local &&
4078                                                         specifiers->storage_class == STORAGE_CLASS_NONE) {
4079                                                 invalid_storage_class = true;
4080                                         }
4081                                 }
4082                                 if (invalid_storage_class) {
4083                                         errorf(&env.source_position,
4084                                                         "invalid storage class for variable '%Y'", env.symbol);
4085                                 }
4086                         }
4087                 }
4088
4089                 if (env.symbol != NULL) {
4090                         entity->base.symbol          = env.symbol;
4091                         entity->base.source_position = env.source_position;
4092                 } else {
4093                         entity->base.source_position = specifiers->source_position;
4094                 }
4095                 entity->base.namespc           = NAMESPACE_NORMAL;
4096                 entity->declaration.type       = orig_type;
4097                 entity->declaration.alignment  = get_type_alignment(orig_type);
4098                 entity->declaration.modifiers  = env.modifiers;
4099                 entity->declaration.attributes = attributes;
4100
4101                 storage_class_t storage_class = specifiers->storage_class;
4102                 entity->declaration.declared_storage_class = storage_class;
4103
4104                 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4105                         storage_class = STORAGE_CLASS_AUTO;
4106                 entity->declaration.storage_class = storage_class;
4107         }
4108
4109         if (attributes != NULL) {
4110                 handle_entity_attributes(attributes, entity);
4111         }
4112
4113         return entity;
4114 }
4115
4116 static type_t *parse_abstract_declarator(type_t *base_type)
4117 {
4118         parse_declarator_env_t env;
4119         memset(&env, 0, sizeof(env));
4120         env.may_be_abstract = true;
4121         env.must_be_abstract = true;
4122
4123         construct_type_t *construct_type = parse_inner_declarator(&env);
4124
4125         type_t *result = construct_declarator_type(construct_type, base_type);
4126         if (construct_type != NULL) {
4127                 obstack_free(&temp_obst, construct_type);
4128         }
4129         result = handle_type_attributes(env.attributes, result);
4130
4131         return result;
4132 }
4133
4134 /**
4135  * Check if the declaration of main is suspicious.  main should be a
4136  * function with external linkage, returning int, taking either zero
4137  * arguments, two, or three arguments of appropriate types, ie.
4138  *
4139  * int main([ int argc, char **argv [, char **env ] ]).
4140  *
4141  * @param decl    the declaration to check
4142  * @param type    the function type of the declaration
4143  */
4144 static void check_main(const entity_t *entity)
4145 {
4146         const source_position_t *pos = &entity->base.source_position;
4147         if (entity->kind != ENTITY_FUNCTION) {
4148                 warningf(pos, "'main' is not a function");
4149                 return;
4150         }
4151
4152         if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4153                 warningf(pos, "'main' is normally a non-static function");
4154         }
4155
4156         type_t *type = skip_typeref(entity->declaration.type);
4157         assert(is_type_function(type));
4158
4159         function_type_t *func_type = &type->function;
4160         if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4161                 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4162                          func_type->return_type);
4163         }
4164         const function_parameter_t *parm = func_type->parameters;
4165         if (parm != NULL) {
4166                 type_t *const first_type = parm->type;
4167                 if (!types_compatible(skip_typeref(first_type), type_int)) {
4168                         warningf(pos,
4169                                  "first argument of 'main' should be 'int', but is '%T'",
4170                                  first_type);
4171                 }
4172                 parm = parm->next;
4173                 if (parm != NULL) {
4174                         type_t *const second_type = parm->type;
4175                         if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4176                                 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4177                         }
4178                         parm = parm->next;
4179                         if (parm != NULL) {
4180                                 type_t *const third_type = parm->type;
4181                                 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4182                                         warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4183                                 }
4184                                 parm = parm->next;
4185                                 if (parm != NULL)
4186                                         goto warn_arg_count;
4187                         }
4188                 } else {
4189 warn_arg_count:
4190                         warningf(pos, "'main' takes only zero, two or three arguments");
4191                 }
4192         }
4193 }
4194
4195 /**
4196  * Check if a symbol is the equal to "main".
4197  */
4198 static bool is_sym_main(const symbol_t *const sym)
4199 {
4200         return strcmp(sym->string, "main") == 0;
4201 }
4202
4203 static void error_redefined_as_different_kind(const source_position_t *pos,
4204                 const entity_t *old, entity_kind_t new_kind)
4205 {
4206         errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4207                get_entity_kind_name(old->kind), old->base.symbol,
4208                get_entity_kind_name(new_kind), &old->base.source_position);
4209 }
4210
4211 static bool is_error_entity(entity_t *const ent)
4212 {
4213         if (is_declaration(ent)) {
4214                 return is_type_valid(skip_typeref(ent->declaration.type));
4215         } else if (ent->kind == ENTITY_TYPEDEF) {
4216                 return is_type_valid(skip_typeref(ent->typedefe.type));
4217         }
4218         return false;
4219 }
4220
4221 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4222 {
4223         for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4224                 if (attributes_equal(tattr, attr))
4225                         return true;
4226         }
4227         return false;
4228 }
4229
4230 /**
4231  * test wether new_list contains any attributes not included in old_list
4232  */
4233 static bool has_new_attributes(const attribute_t *old_list,
4234                                const attribute_t *new_list)
4235 {
4236         for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4237                 if (!contains_attribute(old_list, attr))
4238                         return true;
4239         }
4240         return false;
4241 }
4242
4243 /**
4244  * Merge in attributes from an attribute list (probably from a previous
4245  * declaration with the same name). Warning: destroys the old structure
4246  * of the attribute list - don't reuse attributes after this call.
4247  */
4248 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4249 {
4250         attribute_t *next;
4251         for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4252                 next = attr->next;
4253                 if (contains_attribute(decl->attributes, attr))
4254                         continue;
4255
4256                 /* move attribute to new declarations attributes list */
4257                 attr->next       = decl->attributes;
4258                 decl->attributes = attr;
4259         }
4260 }
4261
4262 /**
4263  * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4264  * for various problems that occur for multiple definitions
4265  */
4266 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4267 {
4268         const symbol_t *const    symbol  = entity->base.symbol;
4269         const namespace_tag_t    namespc = (namespace_tag_t)entity->base.namespc;
4270         const source_position_t *pos     = &entity->base.source_position;
4271
4272         /* can happen in error cases */
4273         if (symbol == NULL)
4274                 return entity;
4275
4276         entity_t *const previous_entity = get_entity(symbol, namespc);
4277         /* pushing the same entity twice will break the stack structure */
4278         assert(previous_entity != entity);
4279
4280         if (entity->kind == ENTITY_FUNCTION) {
4281                 type_t *const orig_type = entity->declaration.type;
4282                 type_t *const type      = skip_typeref(orig_type);
4283
4284                 assert(is_type_function(type));
4285                 if (type->function.unspecified_parameters &&
4286                                 warning.strict_prototypes &&
4287                                 previous_entity == NULL) {
4288                         warningf(pos, "function declaration '%#T' is not a prototype",
4289                                          orig_type, symbol);
4290                 }
4291
4292                 if (warning.main && current_scope == file_scope
4293                                 && is_sym_main(symbol)) {
4294                         check_main(entity);
4295                 }
4296         }
4297
4298         if (is_declaration(entity) &&
4299                         warning.nested_externs &&
4300                         entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4301                         current_scope != file_scope) {
4302                 warningf(pos, "nested extern declaration of '%#T'",
4303                          entity->declaration.type, symbol);
4304         }
4305
4306         if (previous_entity != NULL) {
4307                 if (previous_entity->base.parent_scope == &current_function->parameters &&
4308                                 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4309                         assert(previous_entity->kind == ENTITY_PARAMETER);
4310                         errorf(pos,
4311                                         "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4312                                         entity->declaration.type, symbol,
4313                                         previous_entity->declaration.type, symbol,
4314                                         &previous_entity->base.source_position);
4315                         goto finish;
4316                 }
4317
4318                 if (previous_entity->base.parent_scope == current_scope) {
4319                         if (previous_entity->kind != entity->kind) {
4320                                 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4321                                         error_redefined_as_different_kind(pos, previous_entity,
4322                                                         entity->kind);
4323                                 }
4324                                 goto finish;
4325                         }
4326                         if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4327                                 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4328                                                 symbol, &previous_entity->base.source_position);
4329                                 goto finish;
4330                         }
4331                         if (previous_entity->kind == ENTITY_TYPEDEF) {
4332                                 /* TODO: C++ allows this for exactly the same type */
4333                                 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4334                                                 symbol, &previous_entity->base.source_position);
4335                                 goto finish;
4336                         }
4337
4338                         /* at this point we should have only VARIABLES or FUNCTIONS */
4339                         assert(is_declaration(previous_entity) && is_declaration(entity));
4340
4341                         declaration_t *const prev_decl = &previous_entity->declaration;
4342                         declaration_t *const decl      = &entity->declaration;
4343
4344                         /* can happen for K&R style declarations */
4345                         if (prev_decl->type       == NULL             &&
4346                                         previous_entity->kind == ENTITY_PARAMETER &&
4347                                         entity->kind          == ENTITY_PARAMETER) {
4348                                 prev_decl->type                   = decl->type;
4349                                 prev_decl->storage_class          = decl->storage_class;
4350                                 prev_decl->declared_storage_class = decl->declared_storage_class;
4351                                 prev_decl->modifiers              = decl->modifiers;
4352                                 return previous_entity;
4353                         }
4354
4355                         type_t *const orig_type = decl->type;
4356                         assert(orig_type != NULL);
4357                         type_t *const type      = skip_typeref(orig_type);
4358                         type_t *const prev_type = skip_typeref(prev_decl->type);
4359
4360                         if (!types_compatible(type, prev_type)) {
4361                                 errorf(pos,
4362                                                 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4363                                                 orig_type, symbol, prev_decl->type, symbol,
4364                                                 &previous_entity->base.source_position);
4365                         } else {
4366                                 unsigned old_storage_class = prev_decl->storage_class;
4367
4368                                 if (warning.redundant_decls               &&
4369                                                 is_definition                     &&
4370                                                 !prev_decl->used                  &&
4371                                                 !(prev_decl->modifiers & DM_USED) &&
4372                                                 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4373                                         warningf(&previous_entity->base.source_position,
4374                                                         "unnecessary static forward declaration for '%#T'",
4375                                                         prev_decl->type, symbol);
4376                                 }
4377
4378                                 storage_class_t new_storage_class = decl->storage_class;
4379
4380                                 /* pretend no storage class means extern for function
4381                                  * declarations (except if the previous declaration is neither
4382                                  * none nor extern) */
4383                                 if (entity->kind == ENTITY_FUNCTION) {
4384                                         /* the previous declaration could have unspecified parameters or
4385                                          * be a typedef, so use the new type */
4386                                         if (prev_type->function.unspecified_parameters || is_definition)
4387                                                 prev_decl->type = type;
4388
4389                                         switch (old_storage_class) {
4390                                                 case STORAGE_CLASS_NONE:
4391                                                         old_storage_class = STORAGE_CLASS_EXTERN;
4392                                                         /* FALLTHROUGH */
4393
4394                                                 case STORAGE_CLASS_EXTERN:
4395                                                         if (is_definition) {
4396                                                                 if (warning.missing_prototypes &&
4397                                                                                 prev_type->function.unspecified_parameters &&
4398                                                                                 !is_sym_main(symbol)) {
4399                                                                         warningf(pos, "no previous prototype for '%#T'",
4400                                                                                         orig_type, symbol);
4401                                                                 }
4402                                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
4403                                                                 new_storage_class = STORAGE_CLASS_EXTERN;
4404                                                         }
4405                                                         break;
4406
4407                                                 default:
4408                                                         break;
4409                                         }
4410                                 } else if (is_type_incomplete(prev_type)) {
4411                                         prev_decl->type = type;
4412                                 }
4413
4414                                 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4415                                                 new_storage_class == STORAGE_CLASS_EXTERN) {
4416
4417 warn_redundant_declaration: ;
4418                                         bool has_new_attrs
4419                                                 = has_new_attributes(prev_decl->attributes,
4420                                                                      decl->attributes);
4421                                         if (has_new_attrs) {
4422                                                 merge_in_attributes(decl, prev_decl->attributes);
4423                                         } else if (!is_definition        &&
4424                                                         warning.redundant_decls  &&
4425                                                         is_type_valid(prev_type) &&
4426                                                         strcmp(previous_entity->base.source_position.input_name,
4427                                                                 "<builtin>") != 0) {
4428                                                 warningf(pos,
4429                                                                 "redundant declaration for '%Y' (declared %P)",
4430                                                                 symbol, &previous_entity->base.source_position);
4431                                         }
4432                                 } else if (current_function == NULL) {
4433                                         if (old_storage_class != STORAGE_CLASS_STATIC &&
4434                                                         new_storage_class == STORAGE_CLASS_STATIC) {
4435                                                 errorf(pos,
4436                                                                 "static declaration of '%Y' follows non-static declaration (declared %P)",
4437                                                                 symbol, &previous_entity->base.source_position);
4438                                         } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4439                                                 prev_decl->storage_class          = STORAGE_CLASS_NONE;
4440                                                 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4441                                         } else {
4442                                                 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4443                                                 if (c_mode & _CXX)
4444                                                         goto error_redeclaration;
4445                                                 goto warn_redundant_declaration;
4446                                         }
4447                                 } else if (is_type_valid(prev_type)) {
4448                                         if (old_storage_class == new_storage_class) {
4449 error_redeclaration:
4450                                                 errorf(pos, "redeclaration of '%Y' (declared %P)",
4451                                                                 symbol, &previous_entity->base.source_position);
4452                                         } else {
4453                                                 errorf(pos,
4454                                                                 "redeclaration of '%Y' with different linkage (declared %P)",
4455                                                                 symbol, &previous_entity->base.source_position);
4456                                         }
4457                                 }
4458                         }
4459
4460                         prev_decl->modifiers |= decl->modifiers;
4461                         if (entity->kind == ENTITY_FUNCTION) {
4462                                 previous_entity->function.is_inline |= entity->function.is_inline;
4463                         }
4464                         return previous_entity;
4465                 }
4466
4467                 if (warning.shadow) {
4468                         warningf(pos, "%s '%Y' shadows %s (declared %P)",
4469                                         get_entity_kind_name(entity->kind), symbol,
4470                                         get_entity_kind_name(previous_entity->kind),
4471                                         &previous_entity->base.source_position);
4472                 }
4473         }
4474
4475         if (entity->kind == ENTITY_FUNCTION) {
4476                 if (is_definition &&
4477                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4478                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
4479                                 warningf(pos, "no previous prototype for '%#T'",
4480                                          entity->declaration.type, symbol);
4481                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4482                                 warningf(pos, "no previous declaration for '%#T'",
4483                                          entity->declaration.type, symbol);
4484                         }
4485                 }
4486         } else if (warning.missing_declarations &&
4487                         entity->kind == ENTITY_VARIABLE &&
4488                         current_scope == file_scope) {
4489                 declaration_t *declaration = &entity->declaration;
4490                 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4491                         warningf(pos, "no previous declaration for '%#T'",
4492                                  declaration->type, symbol);
4493                 }
4494         }
4495
4496 finish:
4497         assert(entity->base.parent_scope == NULL);
4498         assert(current_scope != NULL);
4499
4500         entity->base.parent_scope = current_scope;
4501         entity->base.namespc      = NAMESPACE_NORMAL;
4502         environment_push(entity);
4503         append_entity(current_scope, entity);
4504
4505         return entity;
4506 }
4507
4508 static void parser_error_multiple_definition(entity_t *entity,
4509                 const source_position_t *source_position)
4510 {
4511         errorf(source_position, "multiple definition of '%Y' (declared %P)",
4512                entity->base.symbol, &entity->base.source_position);
4513 }
4514
4515 static bool is_declaration_specifier(const token_t *token,
4516                                      bool only_specifiers_qualifiers)
4517 {
4518         switch (token->type) {
4519                 TYPE_SPECIFIERS
4520                 TYPE_QUALIFIERS
4521                         return true;
4522                 case T_IDENTIFIER:
4523                         return is_typedef_symbol(token->v.symbol);
4524
4525                 case T___extension__:
4526                 STORAGE_CLASSES
4527                         return !only_specifiers_qualifiers;
4528
4529                 default:
4530                         return false;
4531         }
4532 }
4533
4534 static void parse_init_declarator_rest(entity_t *entity)
4535 {
4536         assert(is_declaration(entity));
4537         declaration_t *const declaration = &entity->declaration;
4538
4539         eat('=');
4540
4541         type_t *orig_type = declaration->type;
4542         type_t *type      = skip_typeref(orig_type);
4543
4544         if (entity->kind == ENTITY_VARIABLE
4545                         && entity->variable.initializer != NULL) {
4546                 parser_error_multiple_definition(entity, HERE);
4547         }
4548
4549         bool must_be_constant = false;
4550         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4551             entity->base.parent_scope  == file_scope) {
4552                 must_be_constant = true;
4553         }
4554
4555         if (is_type_function(type)) {
4556                 errorf(&entity->base.source_position,
4557                        "function '%#T' is initialized like a variable",
4558                        orig_type, entity->base.symbol);
4559                 orig_type = type_error_type;
4560         }
4561
4562         parse_initializer_env_t env;
4563         env.type             = orig_type;
4564         env.must_be_constant = must_be_constant;
4565         env.entity           = entity;
4566         current_init_decl    = entity;
4567
4568         initializer_t *initializer = parse_initializer(&env);
4569         current_init_decl = NULL;
4570
4571         if (entity->kind == ENTITY_VARIABLE) {
4572                 /* §6.7.5:22  array initializers for arrays with unknown size
4573                  * determine the array type size */
4574                 declaration->type            = env.type;
4575                 entity->variable.initializer = initializer;
4576         }
4577 }
4578
4579 /* parse rest of a declaration without any declarator */
4580 static void parse_anonymous_declaration_rest(
4581                 const declaration_specifiers_t *specifiers)
4582 {
4583         eat(';');
4584         anonymous_entity = NULL;
4585
4586         if (warning.other) {
4587                 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4588                                 specifiers->thread_local) {
4589                         warningf(&specifiers->source_position,
4590                                  "useless storage class in empty declaration");
4591                 }
4592
4593                 type_t *type = specifiers->type;
4594                 switch (type->kind) {
4595                         case TYPE_COMPOUND_STRUCT:
4596                         case TYPE_COMPOUND_UNION: {
4597                                 if (type->compound.compound->base.symbol == NULL) {
4598                                         warningf(&specifiers->source_position,
4599                                                  "unnamed struct/union that defines no instances");
4600                                 }
4601                                 break;
4602                         }
4603
4604                         case TYPE_ENUM:
4605                                 break;
4606
4607                         default:
4608                                 warningf(&specifiers->source_position, "empty declaration");
4609                                 break;
4610                 }
4611         }
4612 }
4613
4614 static void check_variable_type_complete(entity_t *ent)
4615 {
4616         if (ent->kind != ENTITY_VARIABLE)
4617                 return;
4618
4619         /* §6.7:7  If an identifier for an object is declared with no linkage, the
4620          *         type for the object shall be complete [...] */
4621         declaration_t *decl = &ent->declaration;
4622         if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4623                         decl->storage_class == STORAGE_CLASS_STATIC)
4624                 return;
4625
4626         type_t *const orig_type = decl->type;
4627         type_t *const type      = skip_typeref(orig_type);
4628         if (!is_type_incomplete(type))
4629                 return;
4630
4631         /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4632          * are given length one. */
4633         if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4634                 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4635                 return;
4636         }
4637
4638         errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4639                         orig_type, ent->base.symbol);
4640 }
4641
4642
4643 static void parse_declaration_rest(entity_t *ndeclaration,
4644                 const declaration_specifiers_t *specifiers,
4645                 parsed_declaration_func         finished_declaration,
4646                 declarator_flags_t              flags)
4647 {
4648         add_anchor_token(';');
4649         add_anchor_token(',');
4650         while (true) {
4651                 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4652
4653                 if (token.type == '=') {
4654                         parse_init_declarator_rest(entity);
4655                 } else if (entity->kind == ENTITY_VARIABLE) {
4656                         /* ISO/IEC 14882:1998(E) §8.5.3:3  The initializer can be omitted
4657                          * [...] where the extern specifier is explicitly used. */
4658                         declaration_t *decl = &entity->declaration;
4659                         if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4660                                 type_t *type = decl->type;
4661                                 if (is_type_reference(skip_typeref(type))) {
4662                                         errorf(&entity->base.source_position,
4663                                                         "reference '%#T' must be initialized",
4664                                                         type, entity->base.symbol);
4665                                 }
4666                         }
4667                 }
4668
4669                 check_variable_type_complete(entity);
4670
4671                 if (!next_if(','))
4672                         break;
4673
4674                 add_anchor_token('=');
4675                 ndeclaration = parse_declarator(specifiers, flags);
4676                 rem_anchor_token('=');
4677         }
4678         expect(';', end_error);
4679
4680 end_error:
4681         anonymous_entity = NULL;
4682         rem_anchor_token(';');
4683         rem_anchor_token(',');
4684 }
4685
4686 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4687 {
4688         symbol_t *symbol = entity->base.symbol;
4689         if (symbol == NULL) {
4690                 errorf(HERE, "anonymous declaration not valid as function parameter");
4691                 return entity;
4692         }
4693
4694         assert(entity->base.namespc == NAMESPACE_NORMAL);
4695         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4696         if (previous_entity == NULL
4697                         || previous_entity->base.parent_scope != current_scope) {
4698                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4699                        symbol);
4700                 return entity;
4701         }
4702
4703         if (is_definition) {
4704                 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4705         }
4706
4707         return record_entity(entity, false);
4708 }
4709
4710 static void parse_declaration(parsed_declaration_func finished_declaration,
4711                               declarator_flags_t      flags)
4712 {
4713         declaration_specifiers_t specifiers;
4714         memset(&specifiers, 0, sizeof(specifiers));
4715
4716         add_anchor_token(';');
4717         parse_declaration_specifiers(&specifiers);
4718         rem_anchor_token(';');
4719
4720         if (token.type == ';') {
4721                 parse_anonymous_declaration_rest(&specifiers);
4722         } else {
4723                 entity_t *entity = parse_declarator(&specifiers, flags);
4724                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4725         }
4726 }
4727
4728 /* §6.5.2.2:6 */
4729 static type_t *get_default_promoted_type(type_t *orig_type)
4730 {
4731         type_t *result = orig_type;
4732
4733         type_t *type = skip_typeref(orig_type);
4734         if (is_type_integer(type)) {
4735                 result = promote_integer(type);
4736         } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4737                 result = type_double;
4738         }
4739
4740         return result;
4741 }
4742
4743 static void parse_kr_declaration_list(entity_t *entity)
4744 {
4745         if (entity->kind != ENTITY_FUNCTION)
4746                 return;
4747
4748         type_t *type = skip_typeref(entity->declaration.type);
4749         assert(is_type_function(type));
4750         if (!type->function.kr_style_parameters)
4751                 return;
4752
4753         add_anchor_token('{');
4754
4755         /* push function parameters */
4756         size_t const  top       = environment_top();
4757         scope_t      *old_scope = scope_push(&entity->function.parameters);
4758
4759         entity_t *parameter = entity->function.parameters.entities;
4760         for ( ; parameter != NULL; parameter = parameter->base.next) {
4761                 assert(parameter->base.parent_scope == NULL);
4762                 parameter->base.parent_scope = current_scope;
4763                 environment_push(parameter);
4764         }
4765
4766         /* parse declaration list */
4767         for (;;) {
4768                 switch (token.type) {
4769                         DECLARATION_START
4770                         case T___extension__:
4771                         /* This covers symbols, which are no type, too, and results in
4772                          * better error messages.  The typical cases are misspelled type
4773                          * names and missing includes. */
4774                         case T_IDENTIFIER:
4775                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4776                                 break;
4777                         default:
4778                                 goto decl_list_end;
4779                 }
4780         }
4781 decl_list_end:
4782
4783         /* pop function parameters */
4784         assert(current_scope == &entity->function.parameters);
4785         scope_pop(old_scope);
4786         environment_pop_to(top);
4787
4788         /* update function type */
4789         type_t *new_type = duplicate_type(type);
4790
4791         function_parameter_t  *parameters = NULL;
4792         function_parameter_t **anchor     = &parameters;
4793
4794         /* did we have an earlier prototype? */
4795         entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4796         if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4797                 proto_type = NULL;
4798
4799         function_parameter_t *proto_parameter = NULL;
4800         if (proto_type != NULL) {
4801                 type_t *proto_type_type = proto_type->declaration.type;
4802                 proto_parameter         = proto_type_type->function.parameters;
4803                 /* If a K&R function definition has a variadic prototype earlier, then
4804                  * make the function definition variadic, too. This should conform to
4805                  * §6.7.5.3:15 and §6.9.1:8. */
4806                 new_type->function.variadic = proto_type_type->function.variadic;
4807         } else {
4808                 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4809                  * prototype */
4810                 new_type->function.unspecified_parameters = true;
4811         }
4812
4813         bool need_incompatible_warning = false;
4814         parameter = entity->function.parameters.entities;
4815         for (; parameter != NULL; parameter = parameter->base.next,
4816                         proto_parameter =
4817                                 proto_parameter == NULL ? NULL : proto_parameter->next) {
4818                 if (parameter->kind != ENTITY_PARAMETER)
4819                         continue;
4820
4821                 type_t *parameter_type = parameter->declaration.type;
4822                 if (parameter_type == NULL) {
4823                         if (strict_mode) {
4824                                 errorf(HERE, "no type specified for function parameter '%Y'",
4825                                        parameter->base.symbol);
4826                                 parameter_type = type_error_type;
4827                         } else {
4828                                 if (warning.implicit_int) {
4829                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4830                                                  parameter->base.symbol);
4831                                 }
4832                                 parameter_type = type_int;
4833                         }
4834                         parameter->declaration.type = parameter_type;
4835                 }
4836
4837                 semantic_parameter_incomplete(parameter);
4838
4839                 /* we need the default promoted types for the function type */
4840                 type_t *not_promoted = parameter_type;
4841                 parameter_type       = get_default_promoted_type(parameter_type);
4842
4843                 /* gcc special: if the type of the prototype matches the unpromoted
4844                  * type don't promote */
4845                 if (!strict_mode && proto_parameter != NULL) {
4846                         type_t *proto_p_type = skip_typeref(proto_parameter->type);
4847                         type_t *promo_skip   = skip_typeref(parameter_type);
4848                         type_t *param_skip   = skip_typeref(not_promoted);
4849                         if (!types_compatible(proto_p_type, promo_skip)
4850                                 && types_compatible(proto_p_type, param_skip)) {
4851                                 /* don't promote */
4852                                 need_incompatible_warning = true;
4853                                 parameter_type = not_promoted;
4854                         }
4855                 }
4856                 function_parameter_t *const parameter
4857                         = allocate_parameter(parameter_type);
4858
4859                 *anchor = parameter;
4860                 anchor  = &parameter->next;
4861         }
4862
4863         new_type->function.parameters = parameters;
4864         new_type = identify_new_type(new_type);
4865
4866         if (warning.other && need_incompatible_warning) {
4867                 type_t *proto_type_type = proto_type->declaration.type;
4868                 warningf(HERE,
4869                          "declaration '%#T' is incompatible with '%#T' (declared %P)",
4870                          proto_type_type, proto_type->base.symbol,
4871                          new_type, entity->base.symbol,
4872                          &proto_type->base.source_position);
4873         }
4874
4875         entity->declaration.type = new_type;
4876
4877         rem_anchor_token('{');
4878 }
4879
4880 static bool first_err = true;
4881
4882 /**
4883  * When called with first_err set, prints the name of the current function,
4884  * else does noting.
4885  */
4886 static void print_in_function(void)
4887 {
4888         if (first_err) {
4889                 first_err = false;
4890                 diagnosticf("%s: In function '%Y':\n",
4891                             current_function->base.base.source_position.input_name,
4892                             current_function->base.base.symbol);
4893         }
4894 }
4895
4896 /**
4897  * Check if all labels are defined in the current function.
4898  * Check if all labels are used in the current function.
4899  */
4900 static void check_labels(void)
4901 {
4902         for (const goto_statement_t *goto_statement = goto_first;
4903             goto_statement != NULL;
4904             goto_statement = goto_statement->next) {
4905                 /* skip computed gotos */
4906                 if (goto_statement->expression != NULL)
4907                         continue;
4908
4909                 label_t *label = goto_statement->label;
4910
4911                 label->used = true;
4912                 if (label->base.source_position.input_name == NULL) {
4913                         print_in_function();
4914                         errorf(&goto_statement->base.source_position,
4915                                "label '%Y' used but not defined", label->base.symbol);
4916                  }
4917         }
4918
4919         if (warning.unused_label) {
4920                 for (const label_statement_t *label_statement = label_first;
4921                          label_statement != NULL;
4922                          label_statement = label_statement->next) {
4923                         label_t *label = label_statement->label;
4924
4925                         if (! label->used) {
4926                                 print_in_function();
4927                                 warningf(&label_statement->base.source_position,
4928                                          "label '%Y' defined but not used", label->base.symbol);
4929                         }
4930                 }
4931         }
4932 }
4933
4934 static void warn_unused_entity(entity_t *entity, entity_t *last)
4935 {
4936         entity_t const *const end = last != NULL ? last->base.next : NULL;
4937         for (; entity != end; entity = entity->base.next) {
4938                 if (!is_declaration(entity))
4939                         continue;
4940
4941                 declaration_t *declaration = &entity->declaration;
4942                 if (declaration->implicit)
4943                         continue;
4944
4945                 if (!declaration->used) {
4946                         print_in_function();
4947                         const char *what = get_entity_kind_name(entity->kind);
4948                         warningf(&entity->base.source_position, "%s '%Y' is unused",
4949                                  what, entity->base.symbol);
4950                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4951                         print_in_function();
4952                         const char *what = get_entity_kind_name(entity->kind);
4953                         warningf(&entity->base.source_position, "%s '%Y' is never read",
4954                                  what, entity->base.symbol);
4955                 }
4956         }
4957 }
4958
4959 static void check_unused_variables(statement_t *const stmt, void *const env)
4960 {
4961         (void)env;
4962
4963         switch (stmt->kind) {
4964                 case STATEMENT_DECLARATION: {
4965                         declaration_statement_t const *const decls = &stmt->declaration;
4966                         warn_unused_entity(decls->declarations_begin,
4967                                            decls->declarations_end);
4968                         return;
4969                 }
4970
4971                 case STATEMENT_FOR:
4972                         warn_unused_entity(stmt->fors.scope.entities, NULL);
4973                         return;
4974
4975                 default:
4976                         return;
4977         }
4978 }
4979
4980 /**
4981  * Check declarations of current_function for unused entities.
4982  */
4983 static void check_declarations(void)
4984 {
4985         if (warning.unused_parameter) {
4986                 const scope_t *scope = &current_function->parameters;
4987
4988                 /* do not issue unused warnings for main */
4989                 if (!is_sym_main(current_function->base.base.symbol)) {
4990                         warn_unused_entity(scope->entities, NULL);
4991                 }
4992         }
4993         if (warning.unused_variable) {
4994                 walk_statements(current_function->statement, check_unused_variables,
4995                                 NULL);
4996         }
4997 }
4998
4999 static int determine_truth(expression_t const* const cond)
5000 {
5001         return
5002                 !is_constant_expression(cond) ? 0 :
5003                 fold_constant_to_bool(cond)   ? 1 :
5004                 -1;
5005 }
5006
5007 static void check_reachable(statement_t *);
5008 static bool reaches_end;
5009
5010 static bool expression_returns(expression_t const *const expr)
5011 {
5012         switch (expr->kind) {
5013                 case EXPR_CALL: {
5014                         expression_t const *const func = expr->call.function;
5015                         if (func->kind == EXPR_REFERENCE) {
5016                                 entity_t *entity = func->reference.entity;
5017                                 if (entity->kind == ENTITY_FUNCTION
5018                                                 && entity->declaration.modifiers & DM_NORETURN)
5019                                         return false;
5020                         }
5021
5022                         if (!expression_returns(func))
5023                                 return false;
5024
5025                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5026                                 if (!expression_returns(arg->expression))
5027                                         return false;
5028                         }
5029
5030                         return true;
5031                 }
5032
5033                 case EXPR_REFERENCE:
5034                 case EXPR_REFERENCE_ENUM_VALUE:
5035                 case EXPR_CONST:
5036                 case EXPR_CHARACTER_CONSTANT:
5037                 case EXPR_WIDE_CHARACTER_CONSTANT:
5038                 case EXPR_STRING_LITERAL:
5039                 case EXPR_WIDE_STRING_LITERAL:
5040                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5041                 case EXPR_LABEL_ADDRESS:
5042                 case EXPR_CLASSIFY_TYPE:
5043                 case EXPR_SIZEOF: // TODO handle obscure VLA case
5044                 case EXPR_ALIGNOF:
5045                 case EXPR_FUNCNAME:
5046                 case EXPR_BUILTIN_CONSTANT_P:
5047                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5048                 case EXPR_OFFSETOF:
5049                 case EXPR_INVALID:
5050                         return true;
5051
5052                 case EXPR_STATEMENT: {
5053                         bool old_reaches_end = reaches_end;
5054                         reaches_end = false;
5055                         check_reachable(expr->statement.statement);
5056                         bool returns = reaches_end;
5057                         reaches_end = old_reaches_end;
5058                         return returns;
5059                 }
5060
5061                 case EXPR_CONDITIONAL:
5062                         // TODO handle constant expression
5063
5064                         if (!expression_returns(expr->conditional.condition))
5065                                 return false;
5066
5067                         if (expr->conditional.true_expression != NULL
5068                                         && expression_returns(expr->conditional.true_expression))
5069                                 return true;
5070
5071                         return expression_returns(expr->conditional.false_expression);
5072
5073                 case EXPR_SELECT:
5074                         return expression_returns(expr->select.compound);
5075
5076                 case EXPR_ARRAY_ACCESS:
5077                         return
5078                                 expression_returns(expr->array_access.array_ref) &&
5079                                 expression_returns(expr->array_access.index);
5080
5081                 case EXPR_VA_START:
5082                         return expression_returns(expr->va_starte.ap);
5083
5084                 case EXPR_VA_ARG:
5085                         return expression_returns(expr->va_arge.ap);
5086
5087                 case EXPR_VA_COPY:
5088                         return expression_returns(expr->va_copye.src);
5089
5090                 EXPR_UNARY_CASES_MANDATORY
5091                         return expression_returns(expr->unary.value);
5092
5093                 case EXPR_UNARY_THROW:
5094                         return false;
5095
5096                 EXPR_BINARY_CASES
5097                         // TODO handle constant lhs of && and ||
5098                         return
5099                                 expression_returns(expr->binary.left) &&
5100                                 expression_returns(expr->binary.right);
5101
5102                 case EXPR_UNKNOWN:
5103                         break;
5104         }
5105
5106         panic("unhandled expression");
5107 }
5108
5109 static bool initializer_returns(initializer_t const *const init)
5110 {
5111         switch (init->kind) {
5112                 case INITIALIZER_VALUE:
5113                         return expression_returns(init->value.value);
5114
5115                 case INITIALIZER_LIST: {
5116                         initializer_t * const*       i       = init->list.initializers;
5117                         initializer_t * const* const end     = i + init->list.len;
5118                         bool                         returns = true;
5119                         for (; i != end; ++i) {
5120                                 if (!initializer_returns(*i))
5121                                         returns = false;
5122                         }
5123                         return returns;
5124                 }
5125
5126                 case INITIALIZER_STRING:
5127                 case INITIALIZER_WIDE_STRING:
5128                 case INITIALIZER_DESIGNATOR: // designators have no payload
5129                         return true;
5130         }
5131         panic("unhandled initializer");
5132 }
5133
5134 static bool noreturn_candidate;
5135
5136 static void check_reachable(statement_t *const stmt)
5137 {
5138         if (stmt->base.reachable)
5139                 return;
5140         if (stmt->kind != STATEMENT_DO_WHILE)
5141                 stmt->base.reachable = true;
5142
5143         statement_t *last = stmt;
5144         statement_t *next;
5145         switch (stmt->kind) {
5146                 case STATEMENT_INVALID:
5147                 case STATEMENT_EMPTY:
5148                 case STATEMENT_ASM:
5149                         next = stmt->base.next;
5150                         break;
5151
5152                 case STATEMENT_DECLARATION: {
5153                         declaration_statement_t const *const decl = &stmt->declaration;
5154                         entity_t                const *      ent  = decl->declarations_begin;
5155                         entity_t                const *const last = decl->declarations_end;
5156                         if (ent != NULL) {
5157                                 for (;; ent = ent->base.next) {
5158                                         if (ent->kind                 == ENTITY_VARIABLE &&
5159                                                         ent->variable.initializer != NULL            &&
5160                                                         !initializer_returns(ent->variable.initializer)) {
5161                                                 return;
5162                                         }
5163                                         if (ent == last)
5164                                                 break;
5165                                 }
5166                         }
5167                         next = stmt->base.next;
5168                         break;
5169                 }
5170
5171                 case STATEMENT_COMPOUND:
5172                         next = stmt->compound.statements;
5173                         if (next == NULL)
5174                                 next = stmt->base.next;
5175                         break;
5176
5177                 case STATEMENT_RETURN: {
5178                         expression_t const *const val = stmt->returns.value;
5179                         if (val == NULL || expression_returns(val))
5180                                 noreturn_candidate = false;
5181                         return;
5182                 }
5183
5184                 case STATEMENT_IF: {
5185                         if_statement_t const *const ifs  = &stmt->ifs;
5186                         expression_t   const *const cond = ifs->condition;
5187
5188                         if (!expression_returns(cond))
5189                                 return;
5190
5191                         int const val = determine_truth(cond);
5192
5193                         if (val >= 0)
5194                                 check_reachable(ifs->true_statement);
5195
5196                         if (val > 0)
5197                                 return;
5198
5199                         if (ifs->false_statement != NULL) {
5200                                 check_reachable(ifs->false_statement);
5201                                 return;
5202                         }
5203
5204                         next = stmt->base.next;
5205                         break;
5206                 }
5207
5208                 case STATEMENT_SWITCH: {
5209                         switch_statement_t const *const switchs = &stmt->switchs;
5210                         expression_t       const *const expr    = switchs->expression;
5211
5212                         if (!expression_returns(expr))
5213                                 return;
5214
5215                         if (is_constant_expression(expr)) {
5216                                 long                    const val      = fold_constant_to_int(expr);
5217                                 case_label_statement_t *      defaults = NULL;
5218                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5219                                         if (i->expression == NULL) {
5220                                                 defaults = i;
5221                                                 continue;
5222                                         }
5223
5224                                         if (i->first_case <= val && val <= i->last_case) {
5225                                                 check_reachable((statement_t*)i);
5226                                                 return;
5227                                         }
5228                                 }
5229
5230                                 if (defaults != NULL) {
5231                                         check_reachable((statement_t*)defaults);
5232                                         return;
5233                                 }
5234                         } else {
5235                                 bool has_default = false;
5236                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5237                                         if (i->expression == NULL)
5238                                                 has_default = true;
5239
5240                                         check_reachable((statement_t*)i);
5241                                 }
5242
5243                                 if (has_default)
5244                                         return;
5245                         }
5246
5247                         next = stmt->base.next;
5248                         break;
5249                 }
5250
5251                 case STATEMENT_EXPRESSION: {
5252                         /* Check for noreturn function call */
5253                         expression_t const *const expr = stmt->expression.expression;
5254                         if (!expression_returns(expr))
5255                                 return;
5256
5257                         next = stmt->base.next;
5258                         break;
5259                 }
5260
5261                 case STATEMENT_CONTINUE:
5262                         for (statement_t *parent = stmt;;) {
5263                                 parent = parent->base.parent;
5264                                 if (parent == NULL) /* continue not within loop */
5265                                         return;
5266
5267                                 next = parent;
5268                                 switch (parent->kind) {
5269                                         case STATEMENT_WHILE:    goto continue_while;
5270                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5271                                         case STATEMENT_FOR:      goto continue_for;
5272
5273                                         default: break;
5274                                 }
5275                         }
5276
5277                 case STATEMENT_BREAK:
5278                         for (statement_t *parent = stmt;;) {
5279                                 parent = parent->base.parent;
5280                                 if (parent == NULL) /* break not within loop/switch */
5281                                         return;
5282
5283                                 switch (parent->kind) {
5284                                         case STATEMENT_SWITCH:
5285                                         case STATEMENT_WHILE:
5286                                         case STATEMENT_DO_WHILE:
5287                                         case STATEMENT_FOR:
5288                                                 last = parent;
5289                                                 next = parent->base.next;
5290                                                 goto found_break_parent;
5291
5292                                         default: break;
5293                                 }
5294                         }
5295 found_break_parent:
5296                         break;
5297
5298                 case STATEMENT_GOTO:
5299                         if (stmt->gotos.expression) {
5300                                 if (!expression_returns(stmt->gotos.expression))
5301                                         return;
5302
5303                                 statement_t *parent = stmt->base.parent;
5304                                 if (parent == NULL) /* top level goto */
5305                                         return;
5306                                 next = parent;
5307                         } else {
5308                                 next = stmt->gotos.label->statement;
5309                                 if (next == NULL) /* missing label */
5310                                         return;
5311                         }
5312                         break;
5313
5314                 case STATEMENT_LABEL:
5315                         next = stmt->label.statement;
5316                         break;
5317
5318                 case STATEMENT_CASE_LABEL:
5319                         next = stmt->case_label.statement;
5320                         break;
5321
5322                 case STATEMENT_WHILE: {
5323                         while_statement_t const *const whiles = &stmt->whiles;
5324                         expression_t      const *const cond   = whiles->condition;
5325
5326                         if (!expression_returns(cond))
5327                                 return;
5328
5329                         int const val = determine_truth(cond);
5330
5331                         if (val >= 0)
5332                                 check_reachable(whiles->body);
5333
5334                         if (val > 0)
5335                                 return;
5336
5337                         next = stmt->base.next;
5338                         break;
5339                 }
5340
5341                 case STATEMENT_DO_WHILE:
5342                         next = stmt->do_while.body;
5343                         break;
5344
5345                 case STATEMENT_FOR: {
5346                         for_statement_t *const fors = &stmt->fors;
5347
5348                         if (fors->condition_reachable)
5349                                 return;
5350                         fors->condition_reachable = true;
5351
5352                         expression_t const *const cond = fors->condition;
5353
5354                         int val;
5355                         if (cond == NULL) {
5356                                 val = 1;
5357                         } else if (expression_returns(cond)) {
5358                                 val = determine_truth(cond);
5359                         } else {
5360                                 return;
5361                         }
5362
5363                         if (val >= 0)
5364                                 check_reachable(fors->body);
5365
5366                         if (val > 0)
5367                                 return;
5368
5369                         next = stmt->base.next;
5370                         break;
5371                 }
5372
5373                 case STATEMENT_MS_TRY: {
5374                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5375                         check_reachable(ms_try->try_statement);
5376                         next = ms_try->final_statement;
5377                         break;
5378                 }
5379
5380                 case STATEMENT_LEAVE: {
5381                         statement_t *parent = stmt;
5382                         for (;;) {
5383                                 parent = parent->base.parent;
5384                                 if (parent == NULL) /* __leave not within __try */
5385                                         return;
5386
5387                                 if (parent->kind == STATEMENT_MS_TRY) {
5388                                         last = parent;
5389                                         next = parent->ms_try.final_statement;
5390                                         break;
5391                                 }
5392                         }
5393                         break;
5394                 }
5395
5396                 default:
5397                         panic("invalid statement kind");
5398         }
5399
5400         while (next == NULL) {
5401                 next = last->base.parent;
5402                 if (next == NULL) {
5403                         noreturn_candidate = false;
5404
5405                         type_t *const type = skip_typeref(current_function->base.type);
5406                         assert(is_type_function(type));
5407                         type_t *const ret  = skip_typeref(type->function.return_type);
5408                         if (warning.return_type                    &&
5409                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5410                             is_type_valid(ret)                     &&
5411                             !is_sym_main(current_function->base.base.symbol)) {
5412                                 warningf(&stmt->base.source_position,
5413                                          "control reaches end of non-void function");
5414                         }
5415                         return;
5416                 }
5417
5418                 switch (next->kind) {
5419                         case STATEMENT_INVALID:
5420                         case STATEMENT_EMPTY:
5421                         case STATEMENT_DECLARATION:
5422                         case STATEMENT_EXPRESSION:
5423                         case STATEMENT_ASM:
5424                         case STATEMENT_RETURN:
5425                         case STATEMENT_CONTINUE:
5426                         case STATEMENT_BREAK:
5427                         case STATEMENT_GOTO:
5428                         case STATEMENT_LEAVE:
5429                                 panic("invalid control flow in function");
5430
5431                         case STATEMENT_COMPOUND:
5432                                 if (next->compound.stmt_expr) {
5433                                         reaches_end = true;
5434                                         return;
5435                                 }
5436                                 /* FALLTHROUGH */
5437                         case STATEMENT_IF:
5438                         case STATEMENT_SWITCH:
5439                         case STATEMENT_LABEL:
5440                         case STATEMENT_CASE_LABEL:
5441                                 last = next;
5442                                 next = next->base.next;
5443                                 break;
5444
5445                         case STATEMENT_WHILE: {
5446 continue_while:
5447                                 if (next->base.reachable)
5448                                         return;
5449                                 next->base.reachable = true;
5450
5451                                 while_statement_t const *const whiles = &next->whiles;
5452                                 expression_t      const *const cond   = whiles->condition;
5453
5454                                 if (!expression_returns(cond))
5455                                         return;
5456
5457                                 int const val = determine_truth(cond);
5458
5459                                 if (val >= 0)
5460                                         check_reachable(whiles->body);
5461
5462                                 if (val > 0)
5463                                         return;
5464
5465                                 last = next;
5466                                 next = next->base.next;
5467                                 break;
5468                         }
5469
5470                         case STATEMENT_DO_WHILE: {
5471 continue_do_while:
5472                                 if (next->base.reachable)
5473                                         return;
5474                                 next->base.reachable = true;
5475
5476                                 do_while_statement_t const *const dw   = &next->do_while;
5477                                 expression_t         const *const cond = dw->condition;
5478
5479                                 if (!expression_returns(cond))
5480                                         return;
5481
5482                                 int const val = determine_truth(cond);
5483
5484                                 if (val >= 0)
5485                                         check_reachable(dw->body);
5486
5487                                 if (val > 0)
5488                                         return;
5489
5490                                 last = next;
5491                                 next = next->base.next;
5492                                 break;
5493                         }
5494
5495                         case STATEMENT_FOR: {
5496 continue_for:;
5497                                 for_statement_t *const fors = &next->fors;
5498
5499                                 fors->step_reachable = true;
5500
5501                                 if (fors->condition_reachable)
5502                                         return;
5503                                 fors->condition_reachable = true;
5504
5505                                 expression_t const *const cond = fors->condition;
5506
5507                                 int val;
5508                                 if (cond == NULL) {
5509                                         val = 1;
5510                                 } else if (expression_returns(cond)) {
5511                                         val = determine_truth(cond);
5512                                 } else {
5513                                         return;
5514                                 }
5515
5516                                 if (val >= 0)
5517                                         check_reachable(fors->body);
5518
5519                                 if (val > 0)
5520                                         return;
5521
5522                                 last = next;
5523                                 next = next->base.next;
5524                                 break;
5525                         }
5526
5527                         case STATEMENT_MS_TRY:
5528                                 last = next;
5529                                 next = next->ms_try.final_statement;
5530                                 break;
5531                 }
5532         }
5533
5534         check_reachable(next);
5535 }
5536
5537 static void check_unreachable(statement_t* const stmt, void *const env)
5538 {
5539         (void)env;
5540
5541         switch (stmt->kind) {
5542                 case STATEMENT_DO_WHILE:
5543                         if (!stmt->base.reachable) {
5544                                 expression_t const *const cond = stmt->do_while.condition;
5545                                 if (determine_truth(cond) >= 0) {
5546                                         warningf(&cond->base.source_position,
5547                                                  "condition of do-while-loop is unreachable");
5548                                 }
5549                         }
5550                         return;
5551
5552                 case STATEMENT_FOR: {
5553                         for_statement_t const* const fors = &stmt->fors;
5554
5555                         // if init and step are unreachable, cond is unreachable, too
5556                         if (!stmt->base.reachable && !fors->step_reachable) {
5557                                 warningf(&stmt->base.source_position, "statement is unreachable");
5558                         } else {
5559                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
5560                                         warningf(&fors->initialisation->base.source_position,
5561                                                  "initialisation of for-statement is unreachable");
5562                                 }
5563
5564                                 if (!fors->condition_reachable && fors->condition != NULL) {
5565                                         warningf(&fors->condition->base.source_position,
5566                                                  "condition of for-statement is unreachable");
5567                                 }
5568
5569                                 if (!fors->step_reachable && fors->step != NULL) {
5570                                         warningf(&fors->step->base.source_position,
5571                                                  "step of for-statement is unreachable");
5572                                 }
5573                         }
5574                         return;
5575                 }
5576
5577                 case STATEMENT_COMPOUND:
5578                         if (stmt->compound.statements != NULL)
5579                                 return;
5580                         goto warn_unreachable;
5581
5582                 case STATEMENT_DECLARATION: {
5583                         /* Only warn if there is at least one declarator with an initializer.
5584                          * This typically occurs in switch statements. */
5585                         declaration_statement_t const *const decl = &stmt->declaration;
5586                         entity_t                const *      ent  = decl->declarations_begin;
5587                         entity_t                const *const last = decl->declarations_end;
5588                         if (ent != NULL) {
5589                                 for (;; ent = ent->base.next) {
5590                                         if (ent->kind                 == ENTITY_VARIABLE &&
5591                                                         ent->variable.initializer != NULL) {
5592                                                 goto warn_unreachable;
5593                                         }
5594                                         if (ent == last)
5595                                                 return;
5596                                 }
5597                         }
5598                 }
5599
5600                 default:
5601 warn_unreachable:
5602                         if (!stmt->base.reachable)
5603                                 warningf(&stmt->base.source_position, "statement is unreachable");
5604                         return;
5605         }
5606 }
5607
5608 static void parse_external_declaration(void)
5609 {
5610         /* function-definitions and declarations both start with declaration
5611          * specifiers */
5612         declaration_specifiers_t specifiers;
5613         memset(&specifiers, 0, sizeof(specifiers));
5614
5615         add_anchor_token(';');
5616         parse_declaration_specifiers(&specifiers);
5617         rem_anchor_token(';');
5618
5619         /* must be a declaration */
5620         if (token.type == ';') {
5621                 parse_anonymous_declaration_rest(&specifiers);
5622                 return;
5623         }
5624
5625         add_anchor_token(',');
5626         add_anchor_token('=');
5627         add_anchor_token(';');
5628         add_anchor_token('{');
5629
5630         /* declarator is common to both function-definitions and declarations */
5631         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5632
5633         rem_anchor_token('{');
5634         rem_anchor_token(';');
5635         rem_anchor_token('=');
5636         rem_anchor_token(',');
5637
5638         /* must be a declaration */
5639         switch (token.type) {
5640                 case ',':
5641                 case ';':
5642                 case '=':
5643                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5644                                         DECL_FLAGS_NONE);
5645                         return;
5646         }
5647
5648         /* must be a function definition */
5649         parse_kr_declaration_list(ndeclaration);
5650
5651         if (token.type != '{') {
5652                 parse_error_expected("while parsing function definition", '{', NULL);
5653                 eat_until_matching_token(';');
5654                 return;
5655         }
5656
5657         assert(is_declaration(ndeclaration));
5658         type_t *const orig_type = ndeclaration->declaration.type;
5659         type_t *      type      = skip_typeref(orig_type);
5660
5661         if (!is_type_function(type)) {
5662                 if (is_type_valid(type)) {
5663                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
5664                                type, ndeclaration->base.symbol);
5665                 }
5666                 eat_block();
5667                 return;
5668         } else if (is_typeref(orig_type)) {
5669                 /* §6.9.1:2 */
5670                 errorf(&ndeclaration->base.source_position,
5671                                 "type of function definition '%#T' is a typedef",
5672                                 orig_type, ndeclaration->base.symbol);
5673         }
5674
5675         if (warning.aggregate_return &&
5676             is_type_compound(skip_typeref(type->function.return_type))) {
5677                 warningf(HERE, "function '%Y' returns an aggregate",
5678                          ndeclaration->base.symbol);
5679         }
5680         if (warning.traditional && !type->function.unspecified_parameters) {
5681                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5682                         ndeclaration->base.symbol);
5683         }
5684         if (warning.old_style_definition && type->function.unspecified_parameters) {
5685                 warningf(HERE, "old-style function definition '%Y'",
5686                         ndeclaration->base.symbol);
5687         }
5688
5689         /* §6.7.5.3:14 a function definition with () means no
5690          * parameters (and not unspecified parameters) */
5691         if (type->function.unspecified_parameters &&
5692                         type->function.parameters == NULL) {
5693                 type_t *copy                          = duplicate_type(type);
5694                 copy->function.unspecified_parameters = false;
5695                 type                                  = identify_new_type(copy);
5696
5697                 ndeclaration->declaration.type = type;
5698         }
5699
5700         entity_t *const entity = record_entity(ndeclaration, true);
5701         assert(entity->kind == ENTITY_FUNCTION);
5702         assert(ndeclaration->kind == ENTITY_FUNCTION);
5703
5704         function_t *function = &entity->function;
5705         if (ndeclaration != entity) {
5706                 function->parameters = ndeclaration->function.parameters;
5707         }
5708         assert(is_declaration(entity));
5709         type = skip_typeref(entity->declaration.type);
5710
5711         /* push function parameters and switch scope */
5712         size_t const  top       = environment_top();
5713         scope_t      *old_scope = scope_push(&function->parameters);
5714
5715         entity_t *parameter = function->parameters.entities;
5716         for (; parameter != NULL; parameter = parameter->base.next) {
5717                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5718                         parameter->base.parent_scope = current_scope;
5719                 }
5720                 assert(parameter->base.parent_scope == NULL
5721                                 || parameter->base.parent_scope == current_scope);
5722                 parameter->base.parent_scope = current_scope;
5723                 if (parameter->base.symbol == NULL) {
5724                         errorf(&parameter->base.source_position, "parameter name omitted");
5725                         continue;
5726                 }
5727                 environment_push(parameter);
5728         }
5729
5730         if (function->statement != NULL) {
5731                 parser_error_multiple_definition(entity, HERE);
5732                 eat_block();
5733         } else {
5734                 /* parse function body */
5735                 int         label_stack_top      = label_top();
5736                 function_t *old_current_function = current_function;
5737                 current_function                 = function;
5738                 current_parent                   = NULL;
5739
5740                 goto_first   = NULL;
5741                 goto_anchor  = &goto_first;
5742                 label_first  = NULL;
5743                 label_anchor = &label_first;
5744
5745                 statement_t *const body = parse_compound_statement(false);
5746                 function->statement = body;
5747                 first_err = true;
5748                 check_labels();
5749                 check_declarations();
5750                 if (warning.return_type      ||
5751                     warning.unreachable_code ||
5752                     (warning.missing_noreturn
5753                      && !(function->base.modifiers & DM_NORETURN))) {
5754                         noreturn_candidate = true;
5755                         check_reachable(body);
5756                         if (warning.unreachable_code)
5757                                 walk_statements(body, check_unreachable, NULL);
5758                         if (warning.missing_noreturn &&
5759                             noreturn_candidate       &&
5760                             !(function->base.modifiers & DM_NORETURN)) {
5761                                 warningf(&body->base.source_position,
5762                                          "function '%#T' is candidate for attribute 'noreturn'",
5763                                          type, entity->base.symbol);
5764                         }
5765                 }
5766
5767                 assert(current_parent   == NULL);
5768                 assert(current_function == function);
5769                 current_function = old_current_function;
5770                 label_pop_to(label_stack_top);
5771         }
5772
5773         assert(current_scope == &function->parameters);
5774         scope_pop(old_scope);
5775         environment_pop_to(top);
5776 }
5777
5778 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5779                                   source_position_t *source_position,
5780                                   const symbol_t *symbol)
5781 {
5782         type_t *type = allocate_type_zero(TYPE_BITFIELD);
5783
5784         type->bitfield.base_type       = base_type;
5785         type->bitfield.size_expression = size;
5786
5787         il_size_t bit_size;
5788         type_t *skipped_type = skip_typeref(base_type);
5789         if (!is_type_integer(skipped_type)) {
5790                 errorf(HERE, "bitfield base type '%T' is not an integer type",
5791                         base_type);
5792                 bit_size = 0;
5793         } else {
5794                 bit_size = get_type_size(base_type) * 8;
5795         }
5796
5797         if (is_constant_expression(size)) {
5798                 long v = fold_constant_to_int(size);
5799                 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5800
5801                 if (v < 0) {
5802                         errorf(source_position, "negative width in bit-field '%Y'",
5803                                user_symbol);
5804                 } else if (v == 0 && symbol != NULL) {
5805                         errorf(source_position, "zero width for bit-field '%Y'",
5806                                user_symbol);
5807                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5808                         errorf(source_position, "width of '%Y' exceeds its type",
5809                                user_symbol);
5810                 } else {
5811                         type->bitfield.bit_size = v;
5812                 }
5813         }
5814
5815         return type;
5816 }
5817
5818 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5819 {
5820         entity_t *iter = compound->members.entities;
5821         for (; iter != NULL; iter = iter->base.next) {
5822                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5823                         continue;
5824
5825                 if (iter->base.symbol == symbol) {
5826                         return iter;
5827                 } else if (iter->base.symbol == NULL) {
5828                         /* search in anonymous structs and unions */
5829                         type_t *type = skip_typeref(iter->declaration.type);
5830                         if (is_type_compound(type)) {
5831                                 if (find_compound_entry(type->compound.compound, symbol)
5832                                                 != NULL)
5833                                         return iter;
5834                         }
5835                         continue;
5836                 }
5837         }
5838
5839         return NULL;
5840 }
5841
5842 static void check_deprecated(const source_position_t *source_position,
5843                              const entity_t *entity)
5844 {
5845         if (!warning.deprecated_declarations)
5846                 return;
5847         if (!is_declaration(entity))
5848                 return;
5849         if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5850                 return;
5851
5852         char const *const prefix = get_entity_kind_name(entity->kind);
5853         const char *deprecated_string
5854                         = get_deprecated_string(entity->declaration.attributes);
5855         if (deprecated_string != NULL) {
5856                 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5857                                  prefix, entity->base.symbol, &entity->base.source_position,
5858                                  deprecated_string);
5859         } else {
5860                 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5861                                  entity->base.symbol, &entity->base.source_position);
5862         }
5863 }
5864
5865
5866 static expression_t *create_select(const source_position_t *pos,
5867                                    expression_t *addr,
5868                                    type_qualifiers_t qualifiers,
5869                                                                    entity_t *entry)
5870 {
5871         assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5872
5873         check_deprecated(pos, entry);
5874
5875         expression_t *select          = allocate_expression_zero(EXPR_SELECT);
5876         select->select.compound       = addr;
5877         select->select.compound_entry = entry;
5878
5879         type_t *entry_type = entry->declaration.type;
5880         type_t *res_type   = get_qualified_type(entry_type, qualifiers);
5881
5882         /* we always do the auto-type conversions; the & and sizeof parser contains
5883          * code to revert this! */
5884         select->base.type = automatic_type_conversion(res_type);
5885         if (res_type->kind == TYPE_BITFIELD) {
5886                 select->base.type = res_type->bitfield.base_type;
5887         }
5888
5889         return select;
5890 }
5891
5892 /**
5893  * Find entry with symbol in compound. Search anonymous structs and unions and
5894  * creates implicit select expressions for them.
5895  * Returns the adress for the innermost compound.
5896  */
5897 static expression_t *find_create_select(const source_position_t *pos,
5898                                         expression_t *addr,
5899                                         type_qualifiers_t qualifiers,
5900                                         compound_t *compound, symbol_t *symbol)
5901 {
5902         entity_t *iter = compound->members.entities;
5903         for (; iter != NULL; iter = iter->base.next) {
5904                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5905                         continue;
5906
5907                 symbol_t *iter_symbol = iter->base.symbol;
5908                 if (iter_symbol == NULL) {
5909                         type_t *type = iter->declaration.type;
5910                         if (type->kind != TYPE_COMPOUND_STRUCT
5911                                         && type->kind != TYPE_COMPOUND_UNION)
5912                                 continue;
5913
5914                         compound_t *sub_compound = type->compound.compound;
5915
5916                         if (find_compound_entry(sub_compound, symbol) == NULL)
5917                                 continue;
5918
5919                         expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5920                         sub_addr->base.source_position = *pos;
5921                         sub_addr->select.implicit      = true;
5922                         return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5923                                                   symbol);
5924                 }
5925
5926                 if (iter_symbol == symbol) {
5927                         return create_select(pos, addr, qualifiers, iter);
5928                 }
5929         }
5930
5931         return NULL;
5932 }
5933
5934 static void parse_compound_declarators(compound_t *compound,
5935                 const declaration_specifiers_t *specifiers)
5936 {
5937         do {
5938                 entity_t *entity;
5939
5940                 if (token.type == ':') {
5941                         source_position_t source_position = *HERE;
5942                         next_token();
5943
5944                         type_t *base_type = specifiers->type;
5945                         expression_t *size = parse_constant_expression();
5946
5947                         type_t *type = make_bitfield_type(base_type, size,
5948                                         &source_position, NULL);
5949
5950                         attribute_t *attributes = parse_attributes(NULL);
5951                         if (attributes != NULL) {
5952                                 attribute_t *last = attributes;
5953                                 while (last->next != NULL)
5954                                         last = last->next;
5955                                 last->next = specifiers->attributes;
5956                         } else {
5957                                 attributes = specifiers->attributes;
5958                         }
5959
5960                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5961                         entity->base.namespc                       = NAMESPACE_NORMAL;
5962                         entity->base.source_position               = source_position;
5963                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5964                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
5965                         entity->declaration.type                   = type;
5966                         entity->declaration.attributes             = attributes;
5967
5968                         if (attributes != NULL) {
5969                                 handle_entity_attributes(attributes, entity);
5970                         }
5971                         append_entity(&compound->members, entity);
5972                 } else {
5973                         entity = parse_declarator(specifiers,
5974                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5975                         if (entity->kind == ENTITY_TYPEDEF) {
5976                                 errorf(&entity->base.source_position,
5977                                                 "typedef not allowed as compound member");
5978                         } else {
5979                                 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5980
5981                                 /* make sure we don't define a symbol multiple times */
5982                                 symbol_t *symbol = entity->base.symbol;
5983                                 if (symbol != NULL) {
5984                                         entity_t *prev = find_compound_entry(compound, symbol);
5985                                         if (prev != NULL) {
5986                                                 errorf(&entity->base.source_position,
5987                                                                 "multiple declarations of symbol '%Y' (declared %P)",
5988                                                                 symbol, &prev->base.source_position);
5989                                         }
5990                                 }
5991
5992                                 if (token.type == ':') {
5993                                         source_position_t source_position = *HERE;
5994                                         next_token();
5995                                         expression_t *size = parse_constant_expression();
5996
5997                                         type_t *type          = entity->declaration.type;
5998                                         type_t *bitfield_type = make_bitfield_type(type, size,
5999                                                         &source_position, entity->base.symbol);
6000
6001                                         attribute_t *attributes = parse_attributes(NULL);
6002                                         entity->declaration.type = bitfield_type;
6003                                         handle_entity_attributes(attributes, entity);
6004                                 } else {
6005                                         type_t *orig_type = entity->declaration.type;
6006                                         type_t *type      = skip_typeref(orig_type);
6007                                         if (is_type_function(type)) {
6008                                                 errorf(&entity->base.source_position,
6009                                                                 "compound member '%Y' must not have function type '%T'",
6010                                                                 entity->base.symbol, orig_type);
6011                                         } else if (is_type_incomplete(type)) {
6012                                                 /* §6.7.2.1:16 flexible array member */
6013                                                 if (!is_type_array(type)       ||
6014                                                                 token.type          != ';' ||
6015                                                                 look_ahead(1)->type != '}') {
6016                                                         errorf(&entity->base.source_position,
6017                                                                         "compound member '%Y' has incomplete type '%T'",
6018                                                                         entity->base.symbol, orig_type);
6019                                                 }
6020                                         }
6021                                 }
6022
6023                                 append_entity(&compound->members, entity);
6024                         }
6025                 }
6026         } while (next_if(','));
6027         expect(';', end_error);
6028
6029 end_error:
6030         anonymous_entity = NULL;
6031 }
6032
6033 static void parse_compound_type_entries(compound_t *compound)
6034 {
6035         eat('{');
6036         add_anchor_token('}');
6037
6038         while (token.type != '}') {
6039                 if (token.type == T_EOF) {
6040                         errorf(HERE, "EOF while parsing struct");
6041                         break;
6042                 }
6043                 declaration_specifiers_t specifiers;
6044                 memset(&specifiers, 0, sizeof(specifiers));
6045                 parse_declaration_specifiers(&specifiers);
6046
6047                 parse_compound_declarators(compound, &specifiers);
6048         }
6049         rem_anchor_token('}');
6050         next_token();
6051
6052         /* §6.7.2.1:7 */
6053         compound->complete = true;
6054 }
6055
6056 static type_t *parse_typename(void)
6057 {
6058         declaration_specifiers_t specifiers;
6059         memset(&specifiers, 0, sizeof(specifiers));
6060         parse_declaration_specifiers(&specifiers);
6061         if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6062                         specifiers.thread_local) {
6063                 /* TODO: improve error message, user does probably not know what a
6064                  * storage class is...
6065                  */
6066                 errorf(HERE, "typename may not have a storage class");
6067         }
6068
6069         type_t *result = parse_abstract_declarator(specifiers.type);
6070
6071         return result;
6072 }
6073
6074
6075
6076
6077 typedef expression_t* (*parse_expression_function)(void);
6078 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6079
6080 typedef struct expression_parser_function_t expression_parser_function_t;
6081 struct expression_parser_function_t {
6082         parse_expression_function        parser;
6083         precedence_t                     infix_precedence;
6084         parse_expression_infix_function  infix_parser;
6085 };
6086
6087 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6088
6089 /**
6090  * Prints an error message if an expression was expected but not read
6091  */
6092 static expression_t *expected_expression_error(void)
6093 {
6094         /* skip the error message if the error token was read */
6095         if (token.type != T_ERROR) {
6096                 errorf(HERE, "expected expression, got token %K", &token);
6097         }
6098         next_token();
6099
6100         return create_invalid_expression();
6101 }
6102
6103 /**
6104  * Parse a string constant.
6105  */
6106 static expression_t *parse_string_const(void)
6107 {
6108         wide_string_t wres;
6109         if (token.type == T_STRING_LITERAL) {
6110                 string_t res = token.v.string;
6111                 next_token();
6112                 while (token.type == T_STRING_LITERAL) {
6113                         res = concat_strings(&res, &token.v.string);
6114                         next_token();
6115                 }
6116                 if (token.type != T_WIDE_STRING_LITERAL) {
6117                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6118                         /* note: that we use type_char_ptr here, which is already the
6119                          * automatic converted type. revert_automatic_type_conversion
6120                          * will construct the array type */
6121                         cnst->base.type    = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6122                         cnst->string.value = res;
6123                         return cnst;
6124                 }
6125
6126                 wres = concat_string_wide_string(&res, &token.v.wide_string);
6127         } else {
6128                 wres = token.v.wide_string;
6129         }
6130         next_token();
6131
6132         for (;;) {
6133                 switch (token.type) {
6134                         case T_WIDE_STRING_LITERAL:
6135                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
6136                                 break;
6137
6138                         case T_STRING_LITERAL:
6139                                 wres = concat_wide_string_string(&wres, &token.v.string);
6140                                 break;
6141
6142                         default: {
6143                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6144                                 cnst->base.type         = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6145                                 cnst->wide_string.value = wres;
6146                                 return cnst;
6147                         }
6148                 }
6149                 next_token();
6150         }
6151 }
6152
6153 /**
6154  * Parse a boolean constant.
6155  */
6156 static expression_t *parse_bool_const(bool value)
6157 {
6158         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6159         cnst->base.type          = type_bool;
6160         cnst->conste.v.int_value = value;
6161
6162         next_token();
6163
6164         return cnst;
6165 }
6166
6167 /**
6168  * Parse an integer constant.
6169  */
6170 static expression_t *parse_int_const(void)
6171 {
6172         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6173         cnst->base.type          = token.datatype;
6174         cnst->conste.v.int_value = token.v.intvalue;
6175
6176         next_token();
6177
6178         return cnst;
6179 }
6180
6181 /**
6182  * Parse a character constant.
6183  */
6184 static expression_t *parse_character_constant(void)
6185 {
6186         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6187         cnst->base.type          = token.datatype;
6188         cnst->conste.v.character = token.v.string;
6189
6190         if (cnst->conste.v.character.size != 1) {
6191                 if (!GNU_MODE) {
6192                         errorf(HERE, "more than 1 character in character constant");
6193                 } else if (warning.multichar) {
6194                         warningf(HERE, "multi-character character constant");
6195                 }
6196         }
6197         next_token();
6198
6199         return cnst;
6200 }
6201
6202 /**
6203  * Parse a wide character constant.
6204  */
6205 static expression_t *parse_wide_character_constant(void)
6206 {
6207         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6208         cnst->base.type               = token.datatype;
6209         cnst->conste.v.wide_character = token.v.wide_string;
6210
6211         if (cnst->conste.v.wide_character.size != 1) {
6212                 if (!GNU_MODE) {
6213                         errorf(HERE, "more than 1 character in character constant");
6214                 } else if (warning.multichar) {
6215                         warningf(HERE, "multi-character character constant");
6216                 }
6217         }
6218         next_token();
6219
6220         return cnst;
6221 }
6222
6223 /**
6224  * Parse a float constant.
6225  */
6226 static expression_t *parse_float_const(void)
6227 {
6228         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6229         cnst->base.type            = token.datatype;
6230         cnst->conste.v.float_value = token.v.floatvalue;
6231
6232         next_token();
6233
6234         return cnst;
6235 }
6236
6237 static entity_t *create_implicit_function(symbol_t *symbol,
6238                 const source_position_t *source_position)
6239 {
6240         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6241         ntype->function.return_type            = type_int;
6242         ntype->function.unspecified_parameters = true;
6243         ntype->function.linkage                = LINKAGE_C;
6244         type_t *type                           = identify_new_type(ntype);
6245
6246         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6247         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6248         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6249         entity->declaration.type                   = type;
6250         entity->declaration.implicit               = true;
6251         entity->base.symbol                        = symbol;
6252         entity->base.source_position               = *source_position;
6253
6254         if (current_scope != NULL) {
6255                 bool strict_prototypes_old = warning.strict_prototypes;
6256                 warning.strict_prototypes  = false;
6257                 record_entity(entity, false);
6258                 warning.strict_prototypes = strict_prototypes_old;
6259         }
6260
6261         return entity;
6262 }
6263
6264 /**
6265  * Creates a return_type (func)(argument_type) function type if not
6266  * already exists.
6267  */
6268 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6269                                     type_t *argument_type2)
6270 {
6271         function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6272         function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6273         parameter1->next = parameter2;
6274
6275         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6276         type->function.return_type = return_type;
6277         type->function.parameters  = parameter1;
6278
6279         return identify_new_type(type);
6280 }
6281
6282 /**
6283  * Creates a return_type (func)(argument_type) function type if not
6284  * already exists.
6285  *
6286  * @param return_type    the return type
6287  * @param argument_type  the argument type
6288  */
6289 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6290 {
6291         function_parameter_t *const parameter = allocate_parameter(argument_type);
6292
6293         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6294         type->function.return_type = return_type;
6295         type->function.parameters  = parameter;
6296
6297         return identify_new_type(type);
6298 }
6299
6300 /**
6301  * Creates a return_type (func)(argument_type, ...) function type if not
6302  * already exists.
6303  *
6304  * @param return_type    the return type
6305  * @param argument_type  the argument type
6306  */
6307 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6308 {
6309         function_parameter_t *const parameter = allocate_parameter(argument_type);
6310
6311         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6312         type->function.return_type = return_type;
6313         type->function.parameters  = parameter;
6314         type->function.variadic    = true;
6315
6316         return identify_new_type(type);
6317 }
6318
6319 /**
6320  * Creates a return_type (func)(void) function type if not
6321  * already exists.
6322  *
6323  * @param return_type    the return type
6324  */
6325 static type_t *make_function_0_type(type_t *return_type)
6326 {
6327         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6328         type->function.return_type = return_type;
6329         type->function.parameters  = NULL;
6330
6331         return identify_new_type(type);
6332 }
6333
6334 /**
6335  * Creates a NO_RETURN return_type (func)(void) function type if not
6336  * already exists.
6337  *
6338  * @param return_type    the return type
6339  */
6340 static type_t *make_function_0_type_noreturn(type_t *return_type)
6341 {
6342         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6343         type->function.return_type = return_type;
6344         type->function.parameters  = NULL;
6345         type->function.modifiers  |= DM_NORETURN;
6346         return identify_new_type(type);
6347 }
6348
6349 /**
6350  * Performs automatic type cast as described in §6.3.2.1.
6351  *
6352  * @param orig_type  the original type
6353  */
6354 static type_t *automatic_type_conversion(type_t *orig_type)
6355 {
6356         type_t *type = skip_typeref(orig_type);
6357         if (is_type_array(type)) {
6358                 array_type_t *array_type   = &type->array;
6359                 type_t       *element_type = array_type->element_type;
6360                 unsigned      qualifiers   = array_type->base.qualifiers;
6361
6362                 return make_pointer_type(element_type, qualifiers);
6363         }
6364
6365         if (is_type_function(type)) {
6366                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6367         }
6368
6369         return orig_type;
6370 }
6371
6372 /**
6373  * reverts the automatic casts of array to pointer types and function
6374  * to function-pointer types as defined §6.3.2.1
6375  */
6376 type_t *revert_automatic_type_conversion(const expression_t *expression)
6377 {
6378         switch (expression->kind) {
6379                 case EXPR_REFERENCE: {
6380                         entity_t *entity = expression->reference.entity;
6381                         if (is_declaration(entity)) {
6382                                 return entity->declaration.type;
6383                         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6384                                 return entity->enum_value.enum_type;
6385                         } else {
6386                                 panic("no declaration or enum in reference");
6387                         }
6388                 }
6389
6390                 case EXPR_SELECT: {
6391                         entity_t *entity = expression->select.compound_entry;
6392                         assert(is_declaration(entity));
6393                         type_t   *type   = entity->declaration.type;
6394                         return get_qualified_type(type,
6395                                         expression->base.type->base.qualifiers);
6396                 }
6397
6398                 case EXPR_UNARY_DEREFERENCE: {
6399                         const expression_t *const value = expression->unary.value;
6400                         type_t             *const type  = skip_typeref(value->base.type);
6401                         if (!is_type_pointer(type))
6402                                 return type_error_type;
6403                         return type->pointer.points_to;
6404                 }
6405
6406                 case EXPR_ARRAY_ACCESS: {
6407                         const expression_t *array_ref = expression->array_access.array_ref;
6408                         type_t             *type_left = skip_typeref(array_ref->base.type);
6409                         if (!is_type_pointer(type_left))
6410                                 return type_error_type;
6411                         return type_left->pointer.points_to;
6412                 }
6413
6414                 case EXPR_STRING_LITERAL: {
6415                         size_t size = expression->string.value.size;
6416                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6417                 }
6418
6419                 case EXPR_WIDE_STRING_LITERAL: {
6420                         size_t size = expression->wide_string.value.size;
6421                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6422                 }
6423
6424                 case EXPR_COMPOUND_LITERAL:
6425                         return expression->compound_literal.type;
6426
6427                 default:
6428                         return expression->base.type;
6429         }
6430 }
6431
6432 /**
6433  * Find an entity matching a symbol in a scope.
6434  * Uses current scope if scope is NULL
6435  */
6436 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6437                                namespace_tag_t namespc)
6438 {
6439         if (scope == NULL) {
6440                 return get_entity(symbol, namespc);
6441         }
6442
6443         /* we should optimize here, if scope grows above a certain size we should
6444            construct a hashmap here... */
6445         entity_t *entity = scope->entities;
6446         for ( ; entity != NULL; entity = entity->base.next) {
6447                 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6448                         break;
6449         }
6450
6451         return entity;
6452 }
6453
6454 static entity_t *parse_qualified_identifier(void)
6455 {
6456         /* namespace containing the symbol */
6457         symbol_t          *symbol;
6458         source_position_t  pos;
6459         const scope_t     *lookup_scope = NULL;
6460
6461         if (next_if(T_COLONCOLON))
6462                 lookup_scope = &unit->scope;
6463
6464         entity_t *entity;
6465         while (true) {
6466                 if (token.type != T_IDENTIFIER) {
6467                         parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6468                         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6469                 }
6470                 symbol = token.v.symbol;
6471                 pos    = *HERE;
6472                 next_token();
6473
6474                 /* lookup entity */
6475                 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6476
6477                 if (!next_if(T_COLONCOLON))
6478                         break;
6479
6480                 switch (entity->kind) {
6481                 case ENTITY_NAMESPACE:
6482                         lookup_scope = &entity->namespacee.members;
6483                         break;
6484                 case ENTITY_STRUCT:
6485                 case ENTITY_UNION:
6486                 case ENTITY_CLASS:
6487                         lookup_scope = &entity->compound.members;
6488                         break;
6489                 default:
6490                         errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6491                                symbol, get_entity_kind_name(entity->kind));
6492                         goto end_error;
6493                 }
6494         }
6495
6496         if (entity == NULL) {
6497                 if (!strict_mode && token.type == '(') {
6498                         /* an implicitly declared function */
6499                         if (warning.error_implicit_function_declaration) {
6500                                 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6501                         } else if (warning.implicit_function_declaration) {
6502                                 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6503                         }
6504
6505                         entity = create_implicit_function(symbol, &pos);
6506                 } else {
6507                         errorf(&pos, "unknown identifier '%Y' found.", symbol);
6508                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
6509                 }
6510         }
6511
6512         return entity;
6513
6514 end_error:
6515         /* skip further qualifications */
6516         while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6517
6518         return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6519 }
6520
6521 static expression_t *parse_reference(void)
6522 {
6523         entity_t *entity = parse_qualified_identifier();
6524
6525         type_t *orig_type;
6526         if (is_declaration(entity)) {
6527                 orig_type = entity->declaration.type;
6528         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6529                 orig_type = entity->enum_value.enum_type;
6530         } else {
6531                 panic("expected declaration or enum value in reference");
6532         }
6533
6534         /* we always do the auto-type conversions; the & and sizeof parser contains
6535          * code to revert this! */
6536         type_t *type = automatic_type_conversion(orig_type);
6537
6538         expression_kind_t kind = EXPR_REFERENCE;
6539         if (entity->kind == ENTITY_ENUM_VALUE)
6540                 kind = EXPR_REFERENCE_ENUM_VALUE;
6541
6542         expression_t *expression     = allocate_expression_zero(kind);
6543         expression->reference.entity = entity;
6544         expression->base.type        = type;
6545
6546         /* this declaration is used */
6547         if (is_declaration(entity)) {
6548                 entity->declaration.used = true;
6549         }
6550
6551         if (entity->base.parent_scope != file_scope
6552                 && (current_function != NULL
6553                         && entity->base.parent_scope->depth < current_function->parameters.depth)
6554                 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6555                 if (entity->kind == ENTITY_VARIABLE) {
6556                         /* access of a variable from an outer function */
6557                         entity->variable.address_taken = true;
6558                 } else if (entity->kind == ENTITY_PARAMETER) {
6559                         entity->parameter.address_taken = true;
6560                 }
6561                 current_function->need_closure = true;
6562         }
6563
6564         check_deprecated(HERE, entity);
6565
6566         if (warning.init_self && entity == current_init_decl && !in_type_prop
6567             && entity->kind == ENTITY_VARIABLE) {
6568                 current_init_decl = NULL;
6569                 warningf(HERE, "variable '%#T' is initialized by itself",
6570                          entity->declaration.type, entity->base.symbol);
6571         }
6572
6573         return expression;
6574 }
6575
6576 static bool semantic_cast(expression_t *cast)
6577 {
6578         expression_t            *expression      = cast->unary.value;
6579         type_t                  *orig_dest_type  = cast->base.type;
6580         type_t                  *orig_type_right = expression->base.type;
6581         type_t            const *dst_type        = skip_typeref(orig_dest_type);
6582         type_t            const *src_type        = skip_typeref(orig_type_right);
6583         source_position_t const *pos             = &cast->base.source_position;
6584
6585         /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6586         if (dst_type == type_void)
6587                 return true;
6588
6589         /* only integer and pointer can be casted to pointer */
6590         if (is_type_pointer(dst_type)  &&
6591             !is_type_pointer(src_type) &&
6592             !is_type_integer(src_type) &&
6593             is_type_valid(src_type)) {
6594                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6595                 return false;
6596         }
6597
6598         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6599                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6600                 return false;
6601         }
6602
6603         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6604                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6605                 return false;
6606         }
6607
6608         if (warning.cast_qual &&
6609             is_type_pointer(src_type) &&
6610             is_type_pointer(dst_type)) {
6611                 type_t *src = skip_typeref(src_type->pointer.points_to);
6612                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6613                 unsigned missing_qualifiers =
6614                         src->base.qualifiers & ~dst->base.qualifiers;
6615                 if (missing_qualifiers != 0) {
6616                         warningf(pos,
6617                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
6618                                  missing_qualifiers, orig_type_right);
6619                 }
6620         }
6621         return true;
6622 }
6623
6624 static expression_t *parse_compound_literal(type_t *type)
6625 {
6626         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6627
6628         parse_initializer_env_t env;
6629         env.type             = type;
6630         env.entity           = NULL;
6631         env.must_be_constant = false;
6632         initializer_t *initializer = parse_initializer(&env);
6633         type = env.type;
6634
6635         expression->compound_literal.initializer = initializer;
6636         expression->compound_literal.type        = type;
6637         expression->base.type                    = automatic_type_conversion(type);
6638
6639         return expression;
6640 }
6641
6642 /**
6643  * Parse a cast expression.
6644  */
6645 static expression_t *parse_cast(void)
6646 {
6647         add_anchor_token(')');
6648
6649         source_position_t source_position = token.source_position;
6650
6651         type_t *type = parse_typename();
6652
6653         rem_anchor_token(')');
6654         expect(')', end_error);
6655
6656         if (token.type == '{') {
6657                 return parse_compound_literal(type);
6658         }
6659
6660         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6661         cast->base.source_position = source_position;
6662
6663         expression_t *value = parse_sub_expression(PREC_CAST);
6664         cast->base.type   = type;
6665         cast->unary.value = value;
6666
6667         if (! semantic_cast(cast)) {
6668                 /* TODO: record the error in the AST. else it is impossible to detect it */
6669         }
6670
6671         return cast;
6672 end_error:
6673         return create_invalid_expression();
6674 }
6675
6676 /**
6677  * Parse a statement expression.
6678  */
6679 static expression_t *parse_statement_expression(void)
6680 {
6681         add_anchor_token(')');
6682
6683         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6684
6685         statement_t *statement          = parse_compound_statement(true);
6686         statement->compound.stmt_expr   = true;
6687         expression->statement.statement = statement;
6688
6689         /* find last statement and use its type */
6690         type_t *type = type_void;
6691         const statement_t *stmt = statement->compound.statements;
6692         if (stmt != NULL) {
6693                 while (stmt->base.next != NULL)
6694                         stmt = stmt->base.next;
6695
6696                 if (stmt->kind == STATEMENT_EXPRESSION) {
6697                         type = stmt->expression.expression->base.type;
6698                 }
6699         } else if (warning.other) {
6700                 warningf(&expression->base.source_position, "empty statement expression ({})");
6701         }
6702         expression->base.type = type;
6703
6704         rem_anchor_token(')');
6705         expect(')', end_error);
6706
6707 end_error:
6708         return expression;
6709 }
6710
6711 /**
6712  * Parse a parenthesized expression.
6713  */
6714 static expression_t *parse_parenthesized_expression(void)
6715 {
6716         eat('(');
6717
6718         switch (token.type) {
6719         case '{':
6720                 /* gcc extension: a statement expression */
6721                 return parse_statement_expression();
6722
6723         TYPE_QUALIFIERS
6724         TYPE_SPECIFIERS
6725                 return parse_cast();
6726         case T_IDENTIFIER:
6727                 if (is_typedef_symbol(token.v.symbol)) {
6728                         return parse_cast();
6729                 }
6730         }
6731
6732         add_anchor_token(')');
6733         expression_t *result = parse_expression();
6734         result->base.parenthesized = true;
6735         rem_anchor_token(')');
6736         expect(')', end_error);
6737
6738 end_error:
6739         return result;
6740 }
6741
6742 static expression_t *parse_function_keyword(void)
6743 {
6744         /* TODO */
6745
6746         if (current_function == NULL) {
6747                 errorf(HERE, "'__func__' used outside of a function");
6748         }
6749
6750         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6751         expression->base.type     = type_char_ptr;
6752         expression->funcname.kind = FUNCNAME_FUNCTION;
6753
6754         next_token();
6755
6756         return expression;
6757 }
6758
6759 static expression_t *parse_pretty_function_keyword(void)
6760 {
6761         if (current_function == NULL) {
6762                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6763         }
6764
6765         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6766         expression->base.type     = type_char_ptr;
6767         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6768
6769         eat(T___PRETTY_FUNCTION__);
6770
6771         return expression;
6772 }
6773
6774 static expression_t *parse_funcsig_keyword(void)
6775 {
6776         if (current_function == NULL) {
6777                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6778         }
6779
6780         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6781         expression->base.type     = type_char_ptr;
6782         expression->funcname.kind = FUNCNAME_FUNCSIG;
6783
6784         eat(T___FUNCSIG__);
6785
6786         return expression;
6787 }
6788
6789 static expression_t *parse_funcdname_keyword(void)
6790 {
6791         if (current_function == NULL) {
6792                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6793         }
6794
6795         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
6796         expression->base.type     = type_char_ptr;
6797         expression->funcname.kind = FUNCNAME_FUNCDNAME;
6798
6799         eat(T___FUNCDNAME__);
6800
6801         return expression;
6802 }
6803
6804 static designator_t *parse_designator(void)
6805 {
6806         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
6807         result->source_position = *HERE;
6808
6809         if (token.type != T_IDENTIFIER) {
6810                 parse_error_expected("while parsing member designator",
6811                                      T_IDENTIFIER, NULL);
6812                 return NULL;
6813         }
6814         result->symbol = token.v.symbol;
6815         next_token();
6816
6817         designator_t *last_designator = result;
6818         while (true) {
6819                 if (next_if('.')) {
6820                         if (token.type != T_IDENTIFIER) {
6821                                 parse_error_expected("while parsing member designator",
6822                                                      T_IDENTIFIER, NULL);
6823                                 return NULL;
6824                         }
6825                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6826                         designator->source_position = *HERE;
6827                         designator->symbol          = token.v.symbol;
6828                         next_token();
6829
6830                         last_designator->next = designator;
6831                         last_designator       = designator;
6832                         continue;
6833                 }
6834                 if (next_if('[')) {
6835                         add_anchor_token(']');
6836                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
6837                         designator->source_position = *HERE;
6838                         designator->array_index     = parse_expression();
6839                         rem_anchor_token(']');
6840                         expect(']', end_error);
6841                         if (designator->array_index == NULL) {
6842                                 return NULL;
6843                         }
6844
6845                         last_designator->next = designator;
6846                         last_designator       = designator;
6847                         continue;
6848                 }
6849                 break;
6850         }
6851
6852         return result;
6853 end_error:
6854         return NULL;
6855 }
6856
6857 /**
6858  * Parse the __builtin_offsetof() expression.
6859  */
6860 static expression_t *parse_offsetof(void)
6861 {
6862         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6863         expression->base.type    = type_size_t;
6864
6865         eat(T___builtin_offsetof);
6866
6867         expect('(', end_error);
6868         add_anchor_token(',');
6869         type_t *type = parse_typename();
6870         rem_anchor_token(',');
6871         expect(',', end_error);
6872         add_anchor_token(')');
6873         designator_t *designator = parse_designator();
6874         rem_anchor_token(')');
6875         expect(')', end_error);
6876
6877         expression->offsetofe.type       = type;
6878         expression->offsetofe.designator = designator;
6879
6880         type_path_t path;
6881         memset(&path, 0, sizeof(path));
6882         path.top_type = type;
6883         path.path     = NEW_ARR_F(type_path_entry_t, 0);
6884
6885         descend_into_subtype(&path);
6886
6887         if (!walk_designator(&path, designator, true)) {
6888                 return create_invalid_expression();
6889         }
6890
6891         DEL_ARR_F(path.path);
6892
6893         return expression;
6894 end_error:
6895         return create_invalid_expression();
6896 }
6897
6898 /**
6899  * Parses a _builtin_va_start() expression.
6900  */
6901 static expression_t *parse_va_start(void)
6902 {
6903         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6904
6905         eat(T___builtin_va_start);
6906
6907         expect('(', end_error);
6908         add_anchor_token(',');
6909         expression->va_starte.ap = parse_assignment_expression();
6910         rem_anchor_token(',');
6911         expect(',', end_error);
6912         expression_t *const expr = parse_assignment_expression();
6913         if (expr->kind == EXPR_REFERENCE) {
6914                 entity_t *const entity = expr->reference.entity;
6915                 if (!current_function->base.type->function.variadic) {
6916                         errorf(&expr->base.source_position,
6917                                         "'va_start' used in non-variadic function");
6918                 } else if (entity->base.parent_scope != &current_function->parameters ||
6919                                 entity->base.next != NULL ||
6920                                 entity->kind != ENTITY_PARAMETER) {
6921                         errorf(&expr->base.source_position,
6922                                "second argument of 'va_start' must be last parameter of the current function");
6923                 } else {
6924                         expression->va_starte.parameter = &entity->variable;
6925                 }
6926                 expect(')', end_error);
6927                 return expression;
6928         }
6929         expect(')', end_error);
6930 end_error:
6931         return create_invalid_expression();
6932 }
6933
6934 /**
6935  * Parses a __builtin_va_arg() expression.
6936  */
6937 static expression_t *parse_va_arg(void)
6938 {
6939         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6940
6941         eat(T___builtin_va_arg);
6942
6943         expect('(', end_error);
6944         call_argument_t ap;
6945         ap.expression = parse_assignment_expression();
6946         expression->va_arge.ap = ap.expression;
6947         check_call_argument(type_valist, &ap, 1);
6948
6949         expect(',', end_error);
6950         expression->base.type = parse_typename();
6951         expect(')', end_error);
6952
6953         return expression;
6954 end_error:
6955         return create_invalid_expression();
6956 }
6957
6958 /**
6959  * Parses a __builtin_va_copy() expression.
6960  */
6961 static expression_t *parse_va_copy(void)
6962 {
6963         expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6964
6965         eat(T___builtin_va_copy);
6966
6967         expect('(', end_error);
6968         expression_t *dst = parse_assignment_expression();
6969         assign_error_t error = semantic_assign(type_valist, dst);
6970         report_assign_error(error, type_valist, dst, "call argument 1",
6971                             &dst->base.source_position);
6972         expression->va_copye.dst = dst;
6973
6974         expect(',', end_error);
6975
6976         call_argument_t src;
6977         src.expression = parse_assignment_expression();
6978         check_call_argument(type_valist, &src, 2);
6979         expression->va_copye.src = src.expression;
6980         expect(')', end_error);
6981
6982         return expression;
6983 end_error:
6984         return create_invalid_expression();
6985 }
6986
6987 /**
6988  * Parses a __builtin_constant_p() expression.
6989  */
6990 static expression_t *parse_builtin_constant(void)
6991 {
6992         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6993
6994         eat(T___builtin_constant_p);
6995
6996         expect('(', end_error);
6997         add_anchor_token(')');
6998         expression->builtin_constant.value = parse_assignment_expression();
6999         rem_anchor_token(')');
7000         expect(')', end_error);
7001         expression->base.type = type_int;
7002
7003         return expression;
7004 end_error:
7005         return create_invalid_expression();
7006 }
7007
7008 /**
7009  * Parses a __builtin_types_compatible_p() expression.
7010  */
7011 static expression_t *parse_builtin_types_compatible(void)
7012 {
7013         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7014
7015         eat(T___builtin_types_compatible_p);
7016
7017         expect('(', end_error);
7018         add_anchor_token(')');
7019         add_anchor_token(',');
7020         expression->builtin_types_compatible.left = parse_typename();
7021         rem_anchor_token(',');
7022         expect(',', end_error);
7023         expression->builtin_types_compatible.right = parse_typename();
7024         rem_anchor_token(')');
7025         expect(')', end_error);
7026         expression->base.type = type_int;
7027
7028         return expression;
7029 end_error:
7030         return create_invalid_expression();
7031 }
7032
7033 /**
7034  * Parses a __builtin_is_*() compare expression.
7035  */
7036 static expression_t *parse_compare_builtin(void)
7037 {
7038         expression_t *expression;
7039
7040         switch (token.type) {
7041         case T___builtin_isgreater:
7042                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7043                 break;
7044         case T___builtin_isgreaterequal:
7045                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7046                 break;
7047         case T___builtin_isless:
7048                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7049                 break;
7050         case T___builtin_islessequal:
7051                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7052                 break;
7053         case T___builtin_islessgreater:
7054                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7055                 break;
7056         case T___builtin_isunordered:
7057                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7058                 break;
7059         default:
7060                 internal_errorf(HERE, "invalid compare builtin found");
7061         }
7062         expression->base.source_position = *HERE;
7063         next_token();
7064
7065         expect('(', end_error);
7066         expression->binary.left = parse_assignment_expression();
7067         expect(',', end_error);
7068         expression->binary.right = parse_assignment_expression();
7069         expect(')', end_error);
7070
7071         type_t *const orig_type_left  = expression->binary.left->base.type;
7072         type_t *const orig_type_right = expression->binary.right->base.type;
7073
7074         type_t *const type_left  = skip_typeref(orig_type_left);
7075         type_t *const type_right = skip_typeref(orig_type_right);
7076         if (!is_type_float(type_left) && !is_type_float(type_right)) {
7077                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7078                         type_error_incompatible("invalid operands in comparison",
7079                                 &expression->base.source_position, orig_type_left, orig_type_right);
7080                 }
7081         } else {
7082                 semantic_comparison(&expression->binary);
7083         }
7084
7085         return expression;
7086 end_error:
7087         return create_invalid_expression();
7088 }
7089
7090 /**
7091  * Parses a MS assume() expression.
7092  */
7093 static expression_t *parse_assume(void)
7094 {
7095         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7096
7097         eat(T__assume);
7098
7099         expect('(', end_error);
7100         add_anchor_token(')');
7101         expression->unary.value = parse_assignment_expression();
7102         rem_anchor_token(')');
7103         expect(')', end_error);
7104
7105         expression->base.type = type_void;
7106         return expression;
7107 end_error:
7108         return create_invalid_expression();
7109 }
7110
7111 /**
7112  * Return the declaration for a given label symbol or create a new one.
7113  *
7114  * @param symbol  the symbol of the label
7115  */
7116 static label_t *get_label(symbol_t *symbol)
7117 {
7118         entity_t *label;
7119         assert(current_function != NULL);
7120
7121         label = get_entity(symbol, NAMESPACE_LABEL);
7122         /* if we found a local label, we already created the declaration */
7123         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7124                 if (label->base.parent_scope != current_scope) {
7125                         assert(label->base.parent_scope->depth < current_scope->depth);
7126                         current_function->goto_to_outer = true;
7127                 }
7128                 return &label->label;
7129         }
7130
7131         label = get_entity(symbol, NAMESPACE_LABEL);
7132         /* if we found a label in the same function, then we already created the
7133          * declaration */
7134         if (label != NULL
7135                         && label->base.parent_scope == &current_function->parameters) {
7136                 return &label->label;
7137         }
7138
7139         /* otherwise we need to create a new one */
7140         label               = allocate_entity_zero(ENTITY_LABEL);
7141         label->base.namespc = NAMESPACE_LABEL;
7142         label->base.symbol  = symbol;
7143
7144         label_push(label);
7145
7146         return &label->label;
7147 }
7148
7149 /**
7150  * Parses a GNU && label address expression.
7151  */
7152 static expression_t *parse_label_address(void)
7153 {
7154         source_position_t source_position = token.source_position;
7155         eat(T_ANDAND);
7156         if (token.type != T_IDENTIFIER) {
7157                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7158                 goto end_error;
7159         }
7160         symbol_t *symbol = token.v.symbol;
7161         next_token();
7162
7163         label_t *label       = get_label(symbol);
7164         label->used          = true;
7165         label->address_taken = true;
7166
7167         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7168         expression->base.source_position = source_position;
7169
7170         /* label address is threaten as a void pointer */
7171         expression->base.type           = type_void_ptr;
7172         expression->label_address.label = label;
7173         return expression;
7174 end_error:
7175         return create_invalid_expression();
7176 }
7177
7178 /**
7179  * Parse a microsoft __noop expression.
7180  */
7181 static expression_t *parse_noop_expression(void)
7182 {
7183         /* the result is a (int)0 */
7184         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
7185         cnst->base.type            = type_int;
7186         cnst->conste.v.int_value   = 0;
7187         cnst->conste.is_ms_noop    = true;
7188
7189         eat(T___noop);
7190
7191         if (token.type == '(') {
7192                 /* parse arguments */
7193                 eat('(');
7194                 add_anchor_token(')');
7195                 add_anchor_token(',');
7196
7197                 if (token.type != ')') do {
7198                         (void)parse_assignment_expression();
7199                 } while (next_if(','));
7200         }
7201         rem_anchor_token(',');
7202         rem_anchor_token(')');
7203         expect(')', end_error);
7204
7205 end_error:
7206         return cnst;
7207 }
7208
7209 /**
7210  * Parses a primary expression.
7211  */
7212 static expression_t *parse_primary_expression(void)
7213 {
7214         switch (token.type) {
7215                 case T_false:                        return parse_bool_const(false);
7216                 case T_true:                         return parse_bool_const(true);
7217                 case T_INTEGER:                      return parse_int_const();
7218                 case T_CHARACTER_CONSTANT:           return parse_character_constant();
7219                 case T_WIDE_CHARACTER_CONSTANT:      return parse_wide_character_constant();
7220                 case T_FLOATINGPOINT:                return parse_float_const();
7221                 case T_STRING_LITERAL:
7222                 case T_WIDE_STRING_LITERAL:          return parse_string_const();
7223                 case T___FUNCTION__:
7224                 case T___func__:                     return parse_function_keyword();
7225                 case T___PRETTY_FUNCTION__:          return parse_pretty_function_keyword();
7226                 case T___FUNCSIG__:                  return parse_funcsig_keyword();
7227                 case T___FUNCDNAME__:                return parse_funcdname_keyword();
7228                 case T___builtin_offsetof:           return parse_offsetof();
7229                 case T___builtin_va_start:           return parse_va_start();
7230                 case T___builtin_va_arg:             return parse_va_arg();
7231                 case T___builtin_va_copy:            return parse_va_copy();
7232                 case T___builtin_isgreater:
7233                 case T___builtin_isgreaterequal:
7234                 case T___builtin_isless:
7235                 case T___builtin_islessequal:
7236                 case T___builtin_islessgreater:
7237                 case T___builtin_isunordered:        return parse_compare_builtin();
7238                 case T___builtin_constant_p:         return parse_builtin_constant();
7239                 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7240                 case T__assume:                      return parse_assume();
7241                 case T_ANDAND:
7242                         if (GNU_MODE)
7243                                 return parse_label_address();
7244                         break;
7245
7246                 case '(':                            return parse_parenthesized_expression();
7247                 case T___noop:                       return parse_noop_expression();
7248
7249                 /* Gracefully handle type names while parsing expressions. */
7250                 case T_COLONCOLON:
7251                         return parse_reference();
7252                 case T_IDENTIFIER:
7253                         if (!is_typedef_symbol(token.v.symbol)) {
7254                                 return parse_reference();
7255                         }
7256                         /* FALLTHROUGH */
7257                 TYPENAME_START {
7258                         source_position_t  const pos  = *HERE;
7259                         type_t const      *const type = parse_typename();
7260                         errorf(&pos, "encountered type '%T' while parsing expression", type);
7261                         return create_invalid_expression();
7262                 }
7263         }
7264
7265         errorf(HERE, "unexpected token %K, expected an expression", &token);
7266         return create_invalid_expression();
7267 }
7268
7269 /**
7270  * Check if the expression has the character type and issue a warning then.
7271  */
7272 static void check_for_char_index_type(const expression_t *expression)
7273 {
7274         type_t       *const type      = expression->base.type;
7275         const type_t *const base_type = skip_typeref(type);
7276
7277         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7278                         warning.char_subscripts) {
7279                 warningf(&expression->base.source_position,
7280                          "array subscript has type '%T'", type);
7281         }
7282 }
7283
7284 static expression_t *parse_array_expression(expression_t *left)
7285 {
7286         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7287
7288         eat('[');
7289         add_anchor_token(']');
7290
7291         expression_t *inside = parse_expression();
7292
7293         type_t *const orig_type_left   = left->base.type;
7294         type_t *const orig_type_inside = inside->base.type;
7295
7296         type_t *const type_left   = skip_typeref(orig_type_left);
7297         type_t *const type_inside = skip_typeref(orig_type_inside);
7298
7299         type_t                    *return_type;
7300         array_access_expression_t *array_access = &expression->array_access;
7301         if (is_type_pointer(type_left)) {
7302                 return_type             = type_left->pointer.points_to;
7303                 array_access->array_ref = left;
7304                 array_access->index     = inside;
7305                 check_for_char_index_type(inside);
7306         } else if (is_type_pointer(type_inside)) {
7307                 return_type             = type_inside->pointer.points_to;
7308                 array_access->array_ref = inside;
7309                 array_access->index     = left;
7310                 array_access->flipped   = true;
7311                 check_for_char_index_type(left);
7312         } else {
7313                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7314                         errorf(HERE,
7315                                 "array access on object with non-pointer types '%T', '%T'",
7316                                 orig_type_left, orig_type_inside);
7317                 }
7318                 return_type             = type_error_type;
7319                 array_access->array_ref = left;
7320                 array_access->index     = inside;
7321         }
7322
7323         expression->base.type = automatic_type_conversion(return_type);
7324
7325         rem_anchor_token(']');
7326         expect(']', end_error);
7327 end_error:
7328         return expression;
7329 }
7330
7331 static expression_t *parse_typeprop(expression_kind_t const kind)
7332 {
7333         expression_t  *tp_expression = allocate_expression_zero(kind);
7334         tp_expression->base.type     = type_size_t;
7335
7336         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7337
7338         /* we only refer to a type property, mark this case */
7339         bool old     = in_type_prop;
7340         in_type_prop = true;
7341
7342         type_t       *orig_type;
7343         expression_t *expression;
7344         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7345                 next_token();
7346                 add_anchor_token(')');
7347                 orig_type = parse_typename();
7348                 rem_anchor_token(')');
7349                 expect(')', end_error);
7350
7351                 if (token.type == '{') {
7352                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7353                          * starting with a compound literal */
7354                         expression = parse_compound_literal(orig_type);
7355                         goto typeprop_expression;
7356                 }
7357         } else {
7358                 expression = parse_sub_expression(PREC_UNARY);
7359
7360 typeprop_expression:
7361                 tp_expression->typeprop.tp_expression = expression;
7362
7363                 orig_type = revert_automatic_type_conversion(expression);
7364                 expression->base.type = orig_type;
7365         }
7366
7367         tp_expression->typeprop.type   = orig_type;
7368         type_t const* const type       = skip_typeref(orig_type);
7369         char   const* const wrong_type =
7370                 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL                  :
7371                 is_type_incomplete(type)                           ? "incomplete"          :
7372                 type->kind == TYPE_FUNCTION                        ? "function designator" :
7373                 type->kind == TYPE_BITFIELD                        ? "bitfield"            :
7374                 NULL;
7375         if (wrong_type != NULL) {
7376                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7377                 errorf(&tp_expression->base.source_position,
7378                                 "operand of %s expression must not be of %s type '%T'",
7379                                 what, wrong_type, orig_type);
7380         }
7381
7382 end_error:
7383         in_type_prop = old;
7384         return tp_expression;
7385 }
7386
7387 static expression_t *parse_sizeof(void)
7388 {
7389         return parse_typeprop(EXPR_SIZEOF);
7390 }
7391
7392 static expression_t *parse_alignof(void)
7393 {
7394         return parse_typeprop(EXPR_ALIGNOF);
7395 }
7396
7397 static expression_t *parse_select_expression(expression_t *addr)
7398 {
7399         assert(token.type == '.' || token.type == T_MINUSGREATER);
7400         bool select_left_arrow = (token.type == T_MINUSGREATER);
7401         next_token();
7402
7403         if (token.type != T_IDENTIFIER) {
7404                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7405                 return create_invalid_expression();
7406         }
7407         symbol_t *symbol = token.v.symbol;
7408         next_token();
7409
7410         type_t *const orig_type = addr->base.type;
7411         type_t *const type      = skip_typeref(orig_type);
7412
7413         type_t *type_left;
7414         bool    saw_error = false;
7415         if (is_type_pointer(type)) {
7416                 if (!select_left_arrow) {
7417                         errorf(HERE,
7418                                "request for member '%Y' in something not a struct or union, but '%T'",
7419                                symbol, orig_type);
7420                         saw_error = true;
7421                 }
7422                 type_left = skip_typeref(type->pointer.points_to);
7423         } else {
7424                 if (select_left_arrow && is_type_valid(type)) {
7425                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7426                         saw_error = true;
7427                 }
7428                 type_left = type;
7429         }
7430
7431         if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7432             type_left->kind != TYPE_COMPOUND_UNION) {
7433
7434                 if (is_type_valid(type_left) && !saw_error) {
7435                         errorf(HERE,
7436                                "request for member '%Y' in something not a struct or union, but '%T'",
7437                                symbol, type_left);
7438                 }
7439                 return create_invalid_expression();
7440         }
7441
7442         compound_t *compound = type_left->compound.compound;
7443         if (!compound->complete) {
7444                 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7445                        symbol, type_left);
7446                 return create_invalid_expression();
7447         }
7448
7449         type_qualifiers_t  qualifiers = type_left->base.qualifiers;
7450         expression_t      *result
7451                 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7452
7453         if (result == NULL) {
7454                 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7455                 return create_invalid_expression();
7456         }
7457
7458         return result;
7459 }
7460
7461 static void check_call_argument(type_t          *expected_type,
7462                                 call_argument_t *argument, unsigned pos)
7463 {
7464         type_t         *expected_type_skip = skip_typeref(expected_type);
7465         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7466         expression_t   *arg_expr           = argument->expression;
7467         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7468
7469         /* handle transparent union gnu extension */
7470         if (is_type_union(expected_type_skip)
7471                         && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7472                 compound_t *union_decl  = expected_type_skip->compound.compound;
7473                 type_t     *best_type   = NULL;
7474                 entity_t   *entry       = union_decl->members.entities;
7475                 for ( ; entry != NULL; entry = entry->base.next) {
7476                         assert(is_declaration(entry));
7477                         type_t *decl_type = entry->declaration.type;
7478                         error = semantic_assign(decl_type, arg_expr);
7479                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7480                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7481                                 continue;
7482
7483                         if (error == ASSIGN_SUCCESS) {
7484                                 best_type = decl_type;
7485                         } else if (best_type == NULL) {
7486                                 best_type = decl_type;
7487                         }
7488                 }
7489
7490                 if (best_type != NULL) {
7491                         expected_type = best_type;
7492                 }
7493         }
7494
7495         error                = semantic_assign(expected_type, arg_expr);
7496         argument->expression = create_implicit_cast(arg_expr, expected_type);
7497
7498         if (error != ASSIGN_SUCCESS) {
7499                 /* report exact scope in error messages (like "in argument 3") */
7500                 char buf[64];
7501                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7502                 report_assign_error(error, expected_type, arg_expr,     buf,
7503                                                         &arg_expr->base.source_position);
7504         } else if (warning.traditional || warning.conversion) {
7505                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7506                 if (!types_compatible(expected_type_skip, promoted_type) &&
7507                     !types_compatible(expected_type_skip, type_void_ptr) &&
7508                     !types_compatible(type_void_ptr,      promoted_type)) {
7509                         /* Deliberately show the skipped types in this warning */
7510                         warningf(&arg_expr->base.source_position,
7511                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
7512                                 pos, expected_type_skip, promoted_type);
7513                 }
7514         }
7515 }
7516
7517 /**
7518  * Handle the semantic restrictions of builtin calls
7519  */
7520 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7521         switch (call->function->reference.entity->function.btk) {
7522                 case bk_gnu_builtin_return_address:
7523                 case bk_gnu_builtin_frame_address: {
7524                         /* argument must be constant */
7525                         call_argument_t *argument = call->arguments;
7526
7527                         if (! is_constant_expression(argument->expression)) {
7528                                 errorf(&call->base.source_position,
7529                                        "argument of '%Y' must be a constant expression",
7530                                        call->function->reference.entity->base.symbol);
7531                         }
7532                         break;
7533                 }
7534                 case bk_gnu_builtin_prefetch: {
7535                         /* second and third argument must be constant if existent */
7536                         call_argument_t *rw = call->arguments->next;
7537                         call_argument_t *locality = NULL;
7538
7539                         if (rw != NULL) {
7540                                 if (! is_constant_expression(rw->expression)) {
7541                                         errorf(&call->base.source_position,
7542                                                "second argument of '%Y' must be a constant expression",
7543                                                call->function->reference.entity->base.symbol);
7544                                 }
7545                                 locality = rw->next;
7546                         }
7547                         if (locality != NULL) {
7548                                 if (! is_constant_expression(locality->expression)) {
7549                                         errorf(&call->base.source_position,
7550                                                "third argument of '%Y' must be a constant expression",
7551                                                call->function->reference.entity->base.symbol);
7552                                 }
7553                                 locality = rw->next;
7554                         }
7555                         break;
7556                 }
7557                 default:
7558                         break;
7559         }
7560 }
7561
7562 /**
7563  * Parse a call expression, ie. expression '( ... )'.
7564  *
7565  * @param expression  the function address
7566  */
7567 static expression_t *parse_call_expression(expression_t *expression)
7568 {
7569         expression_t      *result = allocate_expression_zero(EXPR_CALL);
7570         call_expression_t *call   = &result->call;
7571         call->function            = expression;
7572
7573         type_t *const orig_type = expression->base.type;
7574         type_t *const type      = skip_typeref(orig_type);
7575
7576         function_type_t *function_type = NULL;
7577         if (is_type_pointer(type)) {
7578                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7579
7580                 if (is_type_function(to_type)) {
7581                         function_type   = &to_type->function;
7582                         call->base.type = function_type->return_type;
7583                 }
7584         }
7585
7586         if (function_type == NULL && is_type_valid(type)) {
7587                 errorf(HERE,
7588                        "called object '%E' (type '%T') is not a pointer to a function",
7589                        expression, orig_type);
7590         }
7591
7592         /* parse arguments */
7593         eat('(');
7594         add_anchor_token(')');
7595         add_anchor_token(',');
7596
7597         if (token.type != ')') {
7598                 call_argument_t **anchor = &call->arguments;
7599                 do {
7600                         call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7601                         argument->expression = parse_assignment_expression();
7602
7603                         *anchor = argument;
7604                         anchor  = &argument->next;
7605                 } while (next_if(','));
7606         }
7607         rem_anchor_token(',');
7608         rem_anchor_token(')');
7609         expect(')', end_error);
7610
7611         if (function_type == NULL)
7612                 return result;
7613
7614         /* check type and count of call arguments */
7615         function_parameter_t *parameter = function_type->parameters;
7616         call_argument_t      *argument  = call->arguments;
7617         if (!function_type->unspecified_parameters) {
7618                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7619                                 parameter = parameter->next, argument = argument->next) {
7620                         check_call_argument(parameter->type, argument, ++pos);
7621                 }
7622
7623                 if (parameter != NULL) {
7624                         errorf(HERE, "too few arguments to function '%E'", expression);
7625                 } else if (argument != NULL && !function_type->variadic) {
7626                         errorf(HERE, "too many arguments to function '%E'", expression);
7627                 }
7628         }
7629
7630         /* do default promotion for other arguments */
7631         for (; argument != NULL; argument = argument->next) {
7632                 type_t *type = argument->expression->base.type;
7633
7634                 type = get_default_promoted_type(type);
7635
7636                 argument->expression
7637                         = create_implicit_cast(argument->expression, type);
7638         }
7639
7640         check_format(&result->call);
7641
7642         if (warning.aggregate_return &&
7643             is_type_compound(skip_typeref(function_type->return_type))) {
7644                 warningf(&result->base.source_position,
7645                          "function call has aggregate value");
7646         }
7647
7648         if (call->function->kind == EXPR_REFERENCE) {
7649                 reference_expression_t *reference = &call->function->reference;
7650                 if (reference->entity->kind == ENTITY_FUNCTION &&
7651                     reference->entity->function.btk != bk_none)
7652                         handle_builtin_argument_restrictions(call);
7653         }
7654
7655 end_error:
7656         return result;
7657 }
7658
7659 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7660
7661 static bool same_compound_type(const type_t *type1, const type_t *type2)
7662 {
7663         return
7664                 is_type_compound(type1) &&
7665                 type1->kind == type2->kind &&
7666                 type1->compound.compound == type2->compound.compound;
7667 }
7668
7669 static expression_t const *get_reference_address(expression_t const *expr)
7670 {
7671         bool regular_take_address = true;
7672         for (;;) {
7673                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7674                         expr = expr->unary.value;
7675                 } else {
7676                         regular_take_address = false;
7677                 }
7678
7679                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7680                         break;
7681
7682                 expr = expr->unary.value;
7683         }
7684
7685         if (expr->kind != EXPR_REFERENCE)
7686                 return NULL;
7687
7688         /* special case for functions which are automatically converted to a
7689          * pointer to function without an extra TAKE_ADDRESS operation */
7690         if (!regular_take_address &&
7691                         expr->reference.entity->kind != ENTITY_FUNCTION) {
7692                 return NULL;
7693         }
7694
7695         return expr;
7696 }
7697
7698 static void warn_reference_address_as_bool(expression_t const* expr)
7699 {
7700         if (!warning.address)
7701                 return;
7702
7703         expr = get_reference_address(expr);
7704         if (expr != NULL) {
7705                 warningf(&expr->base.source_position,
7706                          "the address of '%Y' will always evaluate as 'true'",
7707                          expr->reference.entity->base.symbol);
7708         }
7709 }
7710
7711 static void warn_assignment_in_condition(const expression_t *const expr)
7712 {
7713         if (!warning.parentheses)
7714                 return;
7715         if (expr->base.kind != EXPR_BINARY_ASSIGN)
7716                 return;
7717         if (expr->base.parenthesized)
7718                 return;
7719         warningf(&expr->base.source_position,
7720                         "suggest parentheses around assignment used as truth value");
7721 }
7722
7723 static void semantic_condition(expression_t const *const expr,
7724                                char const *const context)
7725 {
7726         type_t *const type = skip_typeref(expr->base.type);
7727         if (is_type_scalar(type)) {
7728                 warn_reference_address_as_bool(expr);
7729                 warn_assignment_in_condition(expr);
7730         } else if (is_type_valid(type)) {
7731                 errorf(&expr->base.source_position,
7732                                 "%s must have scalar type", context);
7733         }
7734 }
7735
7736 /**
7737  * Parse a conditional expression, ie. 'expression ? ... : ...'.
7738  *
7739  * @param expression  the conditional expression
7740  */
7741 static expression_t *parse_conditional_expression(expression_t *expression)
7742 {
7743         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7744
7745         conditional_expression_t *conditional = &result->conditional;
7746         conditional->condition                = expression;
7747
7748         eat('?');
7749         add_anchor_token(':');
7750
7751         /* §6.5.15:2  The first operand shall have scalar type. */
7752         semantic_condition(expression, "condition of conditional operator");
7753
7754         expression_t *true_expression = expression;
7755         bool          gnu_cond = false;
7756         if (GNU_MODE && token.type == ':') {
7757                 gnu_cond = true;
7758         } else {
7759                 true_expression = parse_expression();
7760         }
7761         rem_anchor_token(':');
7762         expect(':', end_error);
7763 end_error:;
7764         expression_t *false_expression =
7765                 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7766
7767         type_t *const orig_true_type  = true_expression->base.type;
7768         type_t *const orig_false_type = false_expression->base.type;
7769         type_t *const true_type       = skip_typeref(orig_true_type);
7770         type_t *const false_type      = skip_typeref(orig_false_type);
7771
7772         /* 6.5.15.3 */
7773         type_t *result_type;
7774         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
7775                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7776                 /* ISO/IEC 14882:1998(E) §5.16:2 */
7777                 if (true_expression->kind == EXPR_UNARY_THROW) {
7778                         result_type = false_type;
7779                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7780                         result_type = true_type;
7781                 } else {
7782                         if (warning.other && (
7783                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
7784                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7785                                         )) {
7786                                 warningf(&conditional->base.source_position,
7787                                                 "ISO C forbids conditional expression with only one void side");
7788                         }
7789                         result_type = type_void;
7790                 }
7791         } else if (is_type_arithmetic(true_type)
7792                    && is_type_arithmetic(false_type)) {
7793                 result_type = semantic_arithmetic(true_type, false_type);
7794
7795                 true_expression  = create_implicit_cast(true_expression, result_type);
7796                 false_expression = create_implicit_cast(false_expression, result_type);
7797
7798                 conditional->true_expression  = true_expression;
7799                 conditional->false_expression = false_expression;
7800                 conditional->base.type        = result_type;
7801         } else if (same_compound_type(true_type, false_type)) {
7802                 /* just take 1 of the 2 types */
7803                 result_type = true_type;
7804         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7805                 type_t *pointer_type;
7806                 type_t *other_type;
7807                 expression_t *other_expression;
7808                 if (is_type_pointer(true_type) &&
7809                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7810                         pointer_type     = true_type;
7811                         other_type       = false_type;
7812                         other_expression = false_expression;
7813                 } else {
7814                         pointer_type     = false_type;
7815                         other_type       = true_type;
7816                         other_expression = true_expression;
7817                 }
7818
7819                 if (is_null_pointer_constant(other_expression)) {
7820                         result_type = pointer_type;
7821                 } else if (is_type_pointer(other_type)) {
7822                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7823                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
7824
7825                         type_t *to;
7826                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7827                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7828                                 to = type_void;
7829                         } else if (types_compatible(get_unqualified_type(to1),
7830                                                     get_unqualified_type(to2))) {
7831                                 to = to1;
7832                         } else {
7833                                 if (warning.other) {
7834                                         warningf(&conditional->base.source_position,
7835                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
7836                                                         true_type, false_type);
7837                                 }
7838                                 to = type_void;
7839                         }
7840
7841                         type_t *const type =
7842                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7843                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7844                 } else if (is_type_integer(other_type)) {
7845                         if (warning.other) {
7846                                 warningf(&conditional->base.source_position,
7847                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7848                         }
7849                         result_type = pointer_type;
7850                 } else {
7851                         if (is_type_valid(other_type)) {
7852                                 type_error_incompatible("while parsing conditional",
7853                                                 &expression->base.source_position, true_type, false_type);
7854                         }
7855                         result_type = type_error_type;
7856                 }
7857         } else {
7858                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7859                         type_error_incompatible("while parsing conditional",
7860                                                 &conditional->base.source_position, true_type,
7861                                                 false_type);
7862                 }
7863                 result_type = type_error_type;
7864         }
7865
7866         conditional->true_expression
7867                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7868         conditional->false_expression
7869                 = create_implicit_cast(false_expression, result_type);
7870         conditional->base.type = result_type;
7871         return result;
7872 }
7873
7874 /**
7875  * Parse an extension expression.
7876  */
7877 static expression_t *parse_extension(void)
7878 {
7879         eat(T___extension__);
7880
7881         bool old_gcc_extension   = in_gcc_extension;
7882         in_gcc_extension         = true;
7883         expression_t *expression = parse_sub_expression(PREC_UNARY);
7884         in_gcc_extension         = old_gcc_extension;
7885         return expression;
7886 }
7887
7888 /**
7889  * Parse a __builtin_classify_type() expression.
7890  */
7891 static expression_t *parse_builtin_classify_type(void)
7892 {
7893         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7894         result->base.type    = type_int;
7895
7896         eat(T___builtin_classify_type);
7897
7898         expect('(', end_error);
7899         add_anchor_token(')');
7900         expression_t *expression = parse_expression();
7901         rem_anchor_token(')');
7902         expect(')', end_error);
7903         result->classify_type.type_expression = expression;
7904
7905         return result;
7906 end_error:
7907         return create_invalid_expression();
7908 }
7909
7910 /**
7911  * Parse a delete expression
7912  * ISO/IEC 14882:1998(E) §5.3.5
7913  */
7914 static expression_t *parse_delete(void)
7915 {
7916         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7917         result->base.type          = type_void;
7918
7919         eat(T_delete);
7920
7921         if (next_if('[')) {
7922                 result->kind = EXPR_UNARY_DELETE_ARRAY;
7923                 expect(']', end_error);
7924 end_error:;
7925         }
7926
7927         expression_t *const value = parse_sub_expression(PREC_CAST);
7928         result->unary.value = value;
7929
7930         type_t *const type = skip_typeref(value->base.type);
7931         if (!is_type_pointer(type)) {
7932                 if (is_type_valid(type)) {
7933                         errorf(&value->base.source_position,
7934                                         "operand of delete must have pointer type");
7935                 }
7936         } else if (warning.other &&
7937                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7938                 warningf(&value->base.source_position,
7939                                 "deleting 'void*' is undefined");
7940         }
7941
7942         return result;
7943 }
7944
7945 /**
7946  * Parse a throw expression
7947  * ISO/IEC 14882:1998(E) §15:1
7948  */
7949 static expression_t *parse_throw(void)
7950 {
7951         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7952         result->base.type          = type_void;
7953
7954         eat(T_throw);
7955
7956         expression_t *value = NULL;
7957         switch (token.type) {
7958                 EXPRESSION_START {
7959                         value = parse_assignment_expression();
7960                         /* ISO/IEC 14882:1998(E) §15.1:3 */
7961                         type_t *const orig_type = value->base.type;
7962                         type_t *const type      = skip_typeref(orig_type);
7963                         if (is_type_incomplete(type)) {
7964                                 errorf(&value->base.source_position,
7965                                                 "cannot throw object of incomplete type '%T'", orig_type);
7966                         } else if (is_type_pointer(type)) {
7967                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
7968                                 if (is_type_incomplete(points_to) &&
7969                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7970                                         errorf(&value->base.source_position,
7971                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
7972                                 }
7973                         }
7974                 }
7975
7976                 default:
7977                         break;
7978         }
7979         result->unary.value = value;
7980
7981         return result;
7982 }
7983
7984 static bool check_pointer_arithmetic(const source_position_t *source_position,
7985                                      type_t *pointer_type,
7986                                      type_t *orig_pointer_type)
7987 {
7988         type_t *points_to = pointer_type->pointer.points_to;
7989         points_to = skip_typeref(points_to);
7990
7991         if (is_type_incomplete(points_to)) {
7992                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7993                         errorf(source_position,
7994                                "arithmetic with pointer to incomplete type '%T' not allowed",
7995                                orig_pointer_type);
7996                         return false;
7997                 } else if (warning.pointer_arith) {
7998                         warningf(source_position,
7999                                  "pointer of type '%T' used in arithmetic",
8000                                  orig_pointer_type);
8001                 }
8002         } else if (is_type_function(points_to)) {
8003                 if (!GNU_MODE) {
8004                         errorf(source_position,
8005                                "arithmetic with pointer to function type '%T' not allowed",
8006                                orig_pointer_type);
8007                         return false;
8008                 } else if (warning.pointer_arith) {
8009                         warningf(source_position,
8010                                  "pointer to a function '%T' used in arithmetic",
8011                                  orig_pointer_type);
8012                 }
8013         }
8014         return true;
8015 }
8016
8017 static bool is_lvalue(const expression_t *expression)
8018 {
8019         /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8020         switch (expression->kind) {
8021         case EXPR_ARRAY_ACCESS:
8022         case EXPR_COMPOUND_LITERAL:
8023         case EXPR_REFERENCE:
8024         case EXPR_SELECT:
8025         case EXPR_UNARY_DEREFERENCE:
8026                 return true;
8027
8028         default: {
8029                 type_t *type = skip_typeref(expression->base.type);
8030                 return
8031                         /* ISO/IEC 14882:1998(E) §3.10:3 */
8032                         is_type_reference(type) ||
8033                         /* Claim it is an lvalue, if the type is invalid.  There was a parse
8034                          * error before, which maybe prevented properly recognizing it as
8035                          * lvalue. */
8036                         !is_type_valid(type);
8037         }
8038         }
8039 }
8040
8041 static void semantic_incdec(unary_expression_t *expression)
8042 {
8043         type_t *const orig_type = expression->value->base.type;
8044         type_t *const type      = skip_typeref(orig_type);
8045         if (is_type_pointer(type)) {
8046                 if (!check_pointer_arithmetic(&expression->base.source_position,
8047                                               type, orig_type)) {
8048                         return;
8049                 }
8050         } else if (!is_type_real(type) && is_type_valid(type)) {
8051                 /* TODO: improve error message */
8052                 errorf(&expression->base.source_position,
8053                        "operation needs an arithmetic or pointer type");
8054                 return;
8055         }
8056         if (!is_lvalue(expression->value)) {
8057                 /* TODO: improve error message */
8058                 errorf(&expression->base.source_position, "lvalue required as operand");
8059         }
8060         expression->base.type = orig_type;
8061 }
8062
8063 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8064 {
8065         type_t *const orig_type = expression->value->base.type;
8066         type_t *const type      = skip_typeref(orig_type);
8067         if (!is_type_arithmetic(type)) {
8068                 if (is_type_valid(type)) {
8069                         /* TODO: improve error message */
8070                         errorf(&expression->base.source_position,
8071                                 "operation needs an arithmetic type");
8072                 }
8073                 return;
8074         }
8075
8076         expression->base.type = orig_type;
8077 }
8078
8079 static void semantic_unexpr_plus(unary_expression_t *expression)
8080 {
8081         semantic_unexpr_arithmetic(expression);
8082         if (warning.traditional)
8083                 warningf(&expression->base.source_position,
8084                         "traditional C rejects the unary plus operator");
8085 }
8086
8087 static void semantic_not(unary_expression_t *expression)
8088 {
8089         /* §6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8090         semantic_condition(expression->value, "operand of !");
8091         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8092 }
8093
8094 static void semantic_unexpr_integer(unary_expression_t *expression)
8095 {
8096         type_t *const orig_type = expression->value->base.type;
8097         type_t *const type      = skip_typeref(orig_type);
8098         if (!is_type_integer(type)) {
8099                 if (is_type_valid(type)) {
8100                         errorf(&expression->base.source_position,
8101                                "operand of ~ must be of integer type");
8102                 }
8103                 return;
8104         }
8105
8106         expression->base.type = orig_type;
8107 }
8108
8109 static void semantic_dereference(unary_expression_t *expression)
8110 {
8111         type_t *const orig_type = expression->value->base.type;
8112         type_t *const type      = skip_typeref(orig_type);
8113         if (!is_type_pointer(type)) {
8114                 if (is_type_valid(type)) {
8115                         errorf(&expression->base.source_position,
8116                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8117                 }
8118                 return;
8119         }
8120
8121         type_t *result_type   = type->pointer.points_to;
8122         result_type           = automatic_type_conversion(result_type);
8123         expression->base.type = result_type;
8124 }
8125
8126 /**
8127  * Record that an address is taken (expression represents an lvalue).
8128  *
8129  * @param expression       the expression
8130  * @param may_be_register  if true, the expression might be an register
8131  */
8132 static void set_address_taken(expression_t *expression, bool may_be_register)
8133 {
8134         if (expression->kind != EXPR_REFERENCE)
8135                 return;
8136
8137         entity_t *const entity = expression->reference.entity;
8138
8139         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8140                 return;
8141
8142         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8143                         && !may_be_register) {
8144                 errorf(&expression->base.source_position,
8145                                 "address of register %s '%Y' requested",
8146                                 get_entity_kind_name(entity->kind),     entity->base.symbol);
8147         }
8148
8149         if (entity->kind == ENTITY_VARIABLE) {
8150                 entity->variable.address_taken = true;
8151         } else {
8152                 assert(entity->kind == ENTITY_PARAMETER);
8153                 entity->parameter.address_taken = true;
8154         }
8155 }
8156
8157 /**
8158  * Check the semantic of the address taken expression.
8159  */
8160 static void semantic_take_addr(unary_expression_t *expression)
8161 {
8162         expression_t *value = expression->value;
8163         value->base.type    = revert_automatic_type_conversion(value);
8164
8165         type_t *orig_type = value->base.type;
8166         type_t *type      = skip_typeref(orig_type);
8167         if (!is_type_valid(type))
8168                 return;
8169
8170         /* §6.5.3.2 */
8171         if (!is_lvalue(value)) {
8172                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8173         }
8174         if (type->kind == TYPE_BITFIELD) {
8175                 errorf(&expression->base.source_position,
8176                        "'&' not allowed on object with bitfield type '%T'",
8177                        type);
8178         }
8179
8180         set_address_taken(value, false);
8181
8182         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8183 }
8184
8185 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8186 static expression_t *parse_##unexpression_type(void)                         \
8187 {                                                                            \
8188         expression_t *unary_expression                                           \
8189                 = allocate_expression_zero(unexpression_type);                       \
8190         eat(token_type);                                                         \
8191         unary_expression->unary.value = parse_sub_expression(PREC_UNARY);        \
8192                                                                                  \
8193         sfunc(&unary_expression->unary);                                         \
8194                                                                                  \
8195         return unary_expression;                                                 \
8196 }
8197
8198 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8199                                semantic_unexpr_arithmetic)
8200 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8201                                semantic_unexpr_plus)
8202 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8203                                semantic_not)
8204 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8205                                semantic_dereference)
8206 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8207                                semantic_take_addr)
8208 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8209                                semantic_unexpr_integer)
8210 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8211                                semantic_incdec)
8212 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8213                                semantic_incdec)
8214
8215 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8216                                                sfunc)                         \
8217 static expression_t *parse_##unexpression_type(expression_t *left)            \
8218 {                                                                             \
8219         expression_t *unary_expression                                            \
8220                 = allocate_expression_zero(unexpression_type);                        \
8221         eat(token_type);                                                          \
8222         unary_expression->unary.value = left;                                     \
8223                                                                                   \
8224         sfunc(&unary_expression->unary);                                          \
8225                                                                               \
8226         return unary_expression;                                                  \
8227 }
8228
8229 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8230                                        EXPR_UNARY_POSTFIX_INCREMENT,
8231                                        semantic_incdec)
8232 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8233                                        EXPR_UNARY_POSTFIX_DECREMENT,
8234                                        semantic_incdec)
8235
8236 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8237 {
8238         /* TODO: handle complex + imaginary types */
8239
8240         type_left  = get_unqualified_type(type_left);
8241         type_right = get_unqualified_type(type_right);
8242
8243         /* §6.3.1.8 Usual arithmetic conversions */
8244         if (type_left == type_long_double || type_right == type_long_double) {
8245                 return type_long_double;
8246         } else if (type_left == type_double || type_right == type_double) {
8247                 return type_double;
8248         } else if (type_left == type_float || type_right == type_float) {
8249                 return type_float;
8250         }
8251
8252         type_left  = promote_integer(type_left);
8253         type_right = promote_integer(type_right);
8254
8255         if (type_left == type_right)
8256                 return type_left;
8257
8258         bool const signed_left  = is_type_signed(type_left);
8259         bool const signed_right = is_type_signed(type_right);
8260         int const  rank_left    = get_rank(type_left);
8261         int const  rank_right   = get_rank(type_right);
8262
8263         if (signed_left == signed_right)
8264                 return rank_left >= rank_right ? type_left : type_right;
8265
8266         int     s_rank;
8267         int     u_rank;
8268         type_t *s_type;
8269         type_t *u_type;
8270         if (signed_left) {
8271                 s_rank = rank_left;
8272                 s_type = type_left;
8273                 u_rank = rank_right;
8274                 u_type = type_right;
8275         } else {
8276                 s_rank = rank_right;
8277                 s_type = type_right;
8278                 u_rank = rank_left;
8279                 u_type = type_left;
8280         }
8281
8282         if (u_rank >= s_rank)
8283                 return u_type;
8284
8285         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8286          * easier here... */
8287         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8288                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8289                 return s_type;
8290
8291         switch (s_rank) {
8292                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8293                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8294                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8295
8296                 default: panic("invalid atomic type");
8297         }
8298 }
8299
8300 /**
8301  * Check the semantic restrictions for a binary expression.
8302  */
8303 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8304 {
8305         expression_t *const left            = expression->left;
8306         expression_t *const right           = expression->right;
8307         type_t       *const orig_type_left  = left->base.type;
8308         type_t       *const orig_type_right = right->base.type;
8309         type_t       *const type_left       = skip_typeref(orig_type_left);
8310         type_t       *const type_right      = skip_typeref(orig_type_right);
8311
8312         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8313                 /* TODO: improve error message */
8314                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8315                         errorf(&expression->base.source_position,
8316                                "operation needs arithmetic types");
8317                 }
8318                 return;
8319         }
8320
8321         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8322         expression->left      = create_implicit_cast(left, arithmetic_type);
8323         expression->right     = create_implicit_cast(right, arithmetic_type);
8324         expression->base.type = arithmetic_type;
8325 }
8326
8327 static void warn_div_by_zero(binary_expression_t const *const expression)
8328 {
8329         if (!warning.div_by_zero ||
8330             !is_type_integer(expression->base.type))
8331                 return;
8332
8333         expression_t const *const right = expression->right;
8334         /* The type of the right operand can be different for /= */
8335         if (is_type_integer(right->base.type) &&
8336             is_constant_expression(right)     &&
8337             !fold_constant_to_bool(right)) {
8338                 warningf(&expression->base.source_position, "division by zero");
8339         }
8340 }
8341
8342 /**
8343  * Check the semantic restrictions for a div/mod expression.
8344  */
8345 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8346 {
8347         semantic_binexpr_arithmetic(expression);
8348         warn_div_by_zero(expression);
8349 }
8350
8351 static void warn_addsub_in_shift(const expression_t *const expr)
8352 {
8353         if (expr->base.parenthesized)
8354                 return;
8355
8356         char op;
8357         switch (expr->kind) {
8358                 case EXPR_BINARY_ADD: op = '+'; break;
8359                 case EXPR_BINARY_SUB: op = '-'; break;
8360                 default:              return;
8361         }
8362
8363         warningf(&expr->base.source_position,
8364                         "suggest parentheses around '%c' inside shift", op);
8365 }
8366
8367 static bool semantic_shift(binary_expression_t *expression)
8368 {
8369         expression_t *const left            = expression->left;
8370         expression_t *const right           = expression->right;
8371         type_t       *const orig_type_left  = left->base.type;
8372         type_t       *const orig_type_right = right->base.type;
8373         type_t       *      type_left       = skip_typeref(orig_type_left);
8374         type_t       *      type_right      = skip_typeref(orig_type_right);
8375
8376         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8377                 /* TODO: improve error message */
8378                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8379                         errorf(&expression->base.source_position,
8380                                "operands of shift operation must have integer types");
8381                 }
8382                 return false;
8383         }
8384
8385         type_left = promote_integer(type_left);
8386
8387         if (is_constant_expression(right)) {
8388                 long count = fold_constant_to_int(right);
8389                 if (count < 0) {
8390                         warningf(&right->base.source_position,
8391                                         "shift count must be non-negative");
8392                 } else if ((unsigned long)count >=
8393                                 get_atomic_type_size(type_left->atomic.akind) * 8) {
8394                         warningf(&right->base.source_position,
8395                                         "shift count must be less than type width");
8396                 }
8397         }
8398
8399         type_right        = promote_integer(type_right);
8400         expression->right = create_implicit_cast(right, type_right);
8401
8402         return true;
8403 }
8404
8405 static void semantic_shift_op(binary_expression_t *expression)
8406 {
8407         expression_t *const left  = expression->left;
8408         expression_t *const right = expression->right;
8409
8410         if (!semantic_shift(expression))
8411                 return;
8412
8413         if (warning.parentheses) {
8414                 warn_addsub_in_shift(left);
8415                 warn_addsub_in_shift(right);
8416         }
8417
8418         type_t *const orig_type_left = left->base.type;
8419         type_t *      type_left      = skip_typeref(orig_type_left);
8420
8421         type_left             = promote_integer(type_left);
8422         expression->left      = create_implicit_cast(left, type_left);
8423         expression->base.type = type_left;
8424 }
8425
8426 static void semantic_add(binary_expression_t *expression)
8427 {
8428         expression_t *const left            = expression->left;
8429         expression_t *const right           = expression->right;
8430         type_t       *const orig_type_left  = left->base.type;
8431         type_t       *const orig_type_right = right->base.type;
8432         type_t       *const type_left       = skip_typeref(orig_type_left);
8433         type_t       *const type_right      = skip_typeref(orig_type_right);
8434
8435         /* §6.5.6 */
8436         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8437                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8438                 expression->left  = create_implicit_cast(left, arithmetic_type);
8439                 expression->right = create_implicit_cast(right, arithmetic_type);
8440                 expression->base.type = arithmetic_type;
8441         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8442                 check_pointer_arithmetic(&expression->base.source_position,
8443                                          type_left, orig_type_left);
8444                 expression->base.type = type_left;
8445         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8446                 check_pointer_arithmetic(&expression->base.source_position,
8447                                          type_right, orig_type_right);
8448                 expression->base.type = type_right;
8449         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8450                 errorf(&expression->base.source_position,
8451                        "invalid operands to binary + ('%T', '%T')",
8452                        orig_type_left, orig_type_right);
8453         }
8454 }
8455
8456 static void semantic_sub(binary_expression_t *expression)
8457 {
8458         expression_t            *const left            = expression->left;
8459         expression_t            *const right           = expression->right;
8460         type_t                  *const orig_type_left  = left->base.type;
8461         type_t                  *const orig_type_right = right->base.type;
8462         type_t                  *const type_left       = skip_typeref(orig_type_left);
8463         type_t                  *const type_right      = skip_typeref(orig_type_right);
8464         source_position_t const *const pos             = &expression->base.source_position;
8465
8466         /* §5.6.5 */
8467         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8468                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8469                 expression->left        = create_implicit_cast(left, arithmetic_type);
8470                 expression->right       = create_implicit_cast(right, arithmetic_type);
8471                 expression->base.type =  arithmetic_type;
8472         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8473                 check_pointer_arithmetic(&expression->base.source_position,
8474                                          type_left, orig_type_left);
8475                 expression->base.type = type_left;
8476         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8477                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8478                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8479                 if (!types_compatible(unqual_left, unqual_right)) {
8480                         errorf(pos,
8481                                "subtracting pointers to incompatible types '%T' and '%T'",
8482                                orig_type_left, orig_type_right);
8483                 } else if (!is_type_object(unqual_left)) {
8484                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8485                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8486                                        orig_type_left);
8487                         } else if (warning.other) {
8488                                 warningf(pos, "subtracting pointers to void");
8489                         }
8490                 }
8491                 expression->base.type = type_ptrdiff_t;
8492         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8493                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8494                        orig_type_left, orig_type_right);
8495         }
8496 }
8497
8498 static void warn_string_literal_address(expression_t const* expr)
8499 {
8500         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8501                 expr = expr->unary.value;
8502                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8503                         return;
8504                 expr = expr->unary.value;
8505         }
8506
8507         if (expr->kind == EXPR_STRING_LITERAL ||
8508             expr->kind == EXPR_WIDE_STRING_LITERAL) {
8509                 warningf(&expr->base.source_position,
8510                         "comparison with string literal results in unspecified behaviour");
8511         }
8512 }
8513
8514 static void warn_comparison_in_comparison(const expression_t *const expr)
8515 {
8516         if (expr->base.parenthesized)
8517                 return;
8518         switch (expr->base.kind) {
8519                 case EXPR_BINARY_LESS:
8520                 case EXPR_BINARY_GREATER:
8521                 case EXPR_BINARY_LESSEQUAL:
8522                 case EXPR_BINARY_GREATEREQUAL:
8523                 case EXPR_BINARY_NOTEQUAL:
8524                 case EXPR_BINARY_EQUAL:
8525                         warningf(&expr->base.source_position,
8526                                         "comparisons like 'x <= y < z' do not have their mathematical meaning");
8527                         break;
8528                 default:
8529                         break;
8530         }
8531 }
8532
8533 static bool maybe_negative(expression_t const *const expr)
8534 {
8535         return
8536                 !is_constant_expression(expr) ||
8537                 fold_constant_to_int(expr) < 0;
8538 }
8539
8540 /**
8541  * Check the semantics of comparison expressions.
8542  *
8543  * @param expression   The expression to check.
8544  */
8545 static void semantic_comparison(binary_expression_t *expression)
8546 {
8547         expression_t *left  = expression->left;
8548         expression_t *right = expression->right;
8549
8550         if (warning.address) {
8551                 warn_string_literal_address(left);
8552                 warn_string_literal_address(right);
8553
8554                 expression_t const* const func_left = get_reference_address(left);
8555                 if (func_left != NULL && is_null_pointer_constant(right)) {
8556                         warningf(&expression->base.source_position,
8557                                  "the address of '%Y' will never be NULL",
8558                                  func_left->reference.entity->base.symbol);
8559                 }
8560
8561                 expression_t const* const func_right = get_reference_address(right);
8562                 if (func_right != NULL && is_null_pointer_constant(right)) {
8563                         warningf(&expression->base.source_position,
8564                                  "the address of '%Y' will never be NULL",
8565                                  func_right->reference.entity->base.symbol);
8566                 }
8567         }
8568
8569         if (warning.parentheses) {
8570                 warn_comparison_in_comparison(left);
8571                 warn_comparison_in_comparison(right);
8572         }
8573
8574         type_t *orig_type_left  = left->base.type;
8575         type_t *orig_type_right = right->base.type;
8576         type_t *type_left       = skip_typeref(orig_type_left);
8577         type_t *type_right      = skip_typeref(orig_type_right);
8578
8579         /* TODO non-arithmetic types */
8580         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8581                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8582
8583                 /* test for signed vs unsigned compares */
8584                 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8585                         bool const signed_left  = is_type_signed(type_left);
8586                         bool const signed_right = is_type_signed(type_right);
8587                         if (signed_left != signed_right) {
8588                                 /* FIXME long long needs better const folding magic */
8589                                 /* TODO check whether constant value can be represented by other type */
8590                                 if ((signed_left  && maybe_negative(left)) ||
8591                                                 (signed_right && maybe_negative(right))) {
8592                                         warningf(&expression->base.source_position,
8593                                                         "comparison between signed and unsigned");
8594                                 }
8595                         }
8596                 }
8597
8598                 expression->left        = create_implicit_cast(left, arithmetic_type);
8599                 expression->right       = create_implicit_cast(right, arithmetic_type);
8600                 expression->base.type   = arithmetic_type;
8601                 if (warning.float_equal &&
8602                     (expression->base.kind == EXPR_BINARY_EQUAL ||
8603                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8604                     is_type_float(arithmetic_type)) {
8605                         warningf(&expression->base.source_position,
8606                                  "comparing floating point with == or != is unsafe");
8607                 }
8608         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8609                 /* TODO check compatibility */
8610         } else if (is_type_pointer(type_left)) {
8611                 expression->right = create_implicit_cast(right, type_left);
8612         } else if (is_type_pointer(type_right)) {
8613                 expression->left = create_implicit_cast(left, type_right);
8614         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8615                 type_error_incompatible("invalid operands in comparison",
8616                                         &expression->base.source_position,
8617                                         type_left, type_right);
8618         }
8619         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8620 }
8621
8622 /**
8623  * Checks if a compound type has constant fields.
8624  */
8625 static bool has_const_fields(const compound_type_t *type)
8626 {
8627         compound_t *compound = type->compound;
8628         entity_t   *entry    = compound->members.entities;
8629
8630         for (; entry != NULL; entry = entry->base.next) {
8631                 if (!is_declaration(entry))
8632                         continue;
8633
8634                 const type_t *decl_type = skip_typeref(entry->declaration.type);
8635                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8636                         return true;
8637         }
8638
8639         return false;
8640 }
8641
8642 static bool is_valid_assignment_lhs(expression_t const* const left)
8643 {
8644         type_t *const orig_type_left = revert_automatic_type_conversion(left);
8645         type_t *const type_left      = skip_typeref(orig_type_left);
8646
8647         if (!is_lvalue(left)) {
8648                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8649                        left);
8650                 return false;
8651         }
8652
8653         if (left->kind == EXPR_REFERENCE
8654                         && left->reference.entity->kind == ENTITY_FUNCTION) {
8655                 errorf(HERE, "cannot assign to function '%E'", left);
8656                 return false;
8657         }
8658
8659         if (is_type_array(type_left)) {
8660                 errorf(HERE, "cannot assign to array '%E'", left);
8661                 return false;
8662         }
8663         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8664                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8665                        orig_type_left);
8666                 return false;
8667         }
8668         if (is_type_incomplete(type_left)) {
8669                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8670                        left, orig_type_left);
8671                 return false;
8672         }
8673         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8674                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8675                        left, orig_type_left);
8676                 return false;
8677         }
8678
8679         return true;
8680 }
8681
8682 static void semantic_arithmetic_assign(binary_expression_t *expression)
8683 {
8684         expression_t *left            = expression->left;
8685         expression_t *right           = expression->right;
8686         type_t       *orig_type_left  = left->base.type;
8687         type_t       *orig_type_right = right->base.type;
8688
8689         if (!is_valid_assignment_lhs(left))
8690                 return;
8691
8692         type_t *type_left  = skip_typeref(orig_type_left);
8693         type_t *type_right = skip_typeref(orig_type_right);
8694
8695         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8696                 /* TODO: improve error message */
8697                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8698                         errorf(&expression->base.source_position,
8699                                "operation needs arithmetic types");
8700                 }
8701                 return;
8702         }
8703
8704         /* combined instructions are tricky. We can't create an implicit cast on
8705          * the left side, because we need the uncasted form for the store.
8706          * The ast2firm pass has to know that left_type must be right_type
8707          * for the arithmetic operation and create a cast by itself */
8708         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8709         expression->right       = create_implicit_cast(right, arithmetic_type);
8710         expression->base.type   = type_left;
8711 }
8712
8713 static void semantic_divmod_assign(binary_expression_t *expression)
8714 {
8715         semantic_arithmetic_assign(expression);
8716         warn_div_by_zero(expression);
8717 }
8718
8719 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8720 {
8721         expression_t *const left            = expression->left;
8722         expression_t *const right           = expression->right;
8723         type_t       *const orig_type_left  = left->base.type;
8724         type_t       *const orig_type_right = right->base.type;
8725         type_t       *const type_left       = skip_typeref(orig_type_left);
8726         type_t       *const type_right      = skip_typeref(orig_type_right);
8727
8728         if (!is_valid_assignment_lhs(left))
8729                 return;
8730
8731         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8732                 /* combined instructions are tricky. We can't create an implicit cast on
8733                  * the left side, because we need the uncasted form for the store.
8734                  * The ast2firm pass has to know that left_type must be right_type
8735                  * for the arithmetic operation and create a cast by itself */
8736                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8737                 expression->right     = create_implicit_cast(right, arithmetic_type);
8738                 expression->base.type = type_left;
8739         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8740                 check_pointer_arithmetic(&expression->base.source_position,
8741                                          type_left, orig_type_left);
8742                 expression->base.type = type_left;
8743         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8744                 errorf(&expression->base.source_position,
8745                        "incompatible types '%T' and '%T' in assignment",
8746                        orig_type_left, orig_type_right);
8747         }
8748 }
8749
8750 static void semantic_integer_assign(binary_expression_t *expression)
8751 {
8752         expression_t *left            = expression->left;
8753         expression_t *right           = expression->right;
8754         type_t       *orig_type_left  = left->base.type;
8755         type_t       *orig_type_right = right->base.type;
8756
8757         if (!is_valid_assignment_lhs(left))
8758                 return;
8759
8760         type_t *type_left  = skip_typeref(orig_type_left);
8761         type_t *type_right = skip_typeref(orig_type_right);
8762
8763         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8764                 /* TODO: improve error message */
8765                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8766                         errorf(&expression->base.source_position,
8767                                "operation needs integer types");
8768                 }
8769                 return;
8770         }
8771
8772         /* combined instructions are tricky. We can't create an implicit cast on
8773          * the left side, because we need the uncasted form for the store.
8774          * The ast2firm pass has to know that left_type must be right_type
8775          * for the arithmetic operation and create a cast by itself */
8776         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8777         expression->right       = create_implicit_cast(right, arithmetic_type);
8778         expression->base.type   = type_left;
8779 }
8780
8781 static void semantic_shift_assign(binary_expression_t *expression)
8782 {
8783         expression_t *left           = expression->left;
8784
8785         if (!is_valid_assignment_lhs(left))
8786                 return;
8787
8788         if (!semantic_shift(expression))
8789                 return;
8790
8791         expression->base.type = skip_typeref(left->base.type);
8792 }
8793
8794 static void warn_logical_and_within_or(const expression_t *const expr)
8795 {
8796         if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8797                 return;
8798         if (expr->base.parenthesized)
8799                 return;
8800         warningf(&expr->base.source_position,
8801                         "suggest parentheses around && within ||");
8802 }
8803
8804 /**
8805  * Check the semantic restrictions of a logical expression.
8806  */
8807 static void semantic_logical_op(binary_expression_t *expression)
8808 {
8809         /* §6.5.13:2  Each of the operands shall have scalar type.
8810          * §6.5.14:2  Each of the operands shall have scalar type. */
8811         semantic_condition(expression->left,   "left operand of logical operator");
8812         semantic_condition(expression->right, "right operand of logical operator");
8813         if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8814                         warning.parentheses) {
8815                 warn_logical_and_within_or(expression->left);
8816                 warn_logical_and_within_or(expression->right);
8817         }
8818         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8819 }
8820
8821 /**
8822  * Check the semantic restrictions of a binary assign expression.
8823  */
8824 static void semantic_binexpr_assign(binary_expression_t *expression)
8825 {
8826         expression_t *left           = expression->left;
8827         type_t       *orig_type_left = left->base.type;
8828
8829         if (!is_valid_assignment_lhs(left))
8830                 return;
8831
8832         assign_error_t error = semantic_assign(orig_type_left, expression->right);
8833         report_assign_error(error, orig_type_left, expression->right,
8834                         "assignment", &left->base.source_position);
8835         expression->right = create_implicit_cast(expression->right, orig_type_left);
8836         expression->base.type = orig_type_left;
8837 }
8838
8839 /**
8840  * Determine if the outermost operation (or parts thereof) of the given
8841  * expression has no effect in order to generate a warning about this fact.
8842  * Therefore in some cases this only examines some of the operands of the
8843  * expression (see comments in the function and examples below).
8844  * Examples:
8845  *   f() + 23;    // warning, because + has no effect
8846  *   x || f();    // no warning, because x controls execution of f()
8847  *   x ? y : f(); // warning, because y has no effect
8848  *   (void)x;     // no warning to be able to suppress the warning
8849  * This function can NOT be used for an "expression has definitely no effect"-
8850  * analysis. */
8851 static bool expression_has_effect(const expression_t *const expr)
8852 {
8853         switch (expr->kind) {
8854                 case EXPR_UNKNOWN:                    break;
8855                 case EXPR_INVALID:                    return true; /* do NOT warn */
8856                 case EXPR_REFERENCE:                  return false;
8857                 case EXPR_REFERENCE_ENUM_VALUE:       return false;
8858                 /* suppress the warning for microsoft __noop operations */
8859                 case EXPR_CONST:                      return expr->conste.is_ms_noop;
8860                 case EXPR_CHARACTER_CONSTANT:         return false;
8861                 case EXPR_WIDE_CHARACTER_CONSTANT:    return false;
8862                 case EXPR_STRING_LITERAL:             return false;
8863                 case EXPR_WIDE_STRING_LITERAL:        return false;
8864                 case EXPR_LABEL_ADDRESS:              return false;
8865
8866                 case EXPR_CALL: {
8867                         const call_expression_t *const call = &expr->call;
8868                         if (call->function->kind != EXPR_REFERENCE)
8869                                 return true;
8870
8871                         switch (call->function->reference.entity->function.btk) {
8872                                 /* FIXME: which builtins have no effect? */
8873                                 default:                      return true;
8874                         }
8875                 }
8876
8877                 /* Generate the warning if either the left or right hand side of a
8878                  * conditional expression has no effect */
8879                 case EXPR_CONDITIONAL: {
8880                         conditional_expression_t const *const cond = &expr->conditional;
8881                         expression_t             const *const t    = cond->true_expression;
8882                         return
8883                                 (t == NULL || expression_has_effect(t)) &&
8884                                 expression_has_effect(cond->false_expression);
8885                 }
8886
8887                 case EXPR_SELECT:                     return false;
8888                 case EXPR_ARRAY_ACCESS:               return false;
8889                 case EXPR_SIZEOF:                     return false;
8890                 case EXPR_CLASSIFY_TYPE:              return false;
8891                 case EXPR_ALIGNOF:                    return false;
8892
8893                 case EXPR_FUNCNAME:                   return false;
8894                 case EXPR_BUILTIN_CONSTANT_P:         return false;
8895                 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8896                 case EXPR_OFFSETOF:                   return false;
8897                 case EXPR_VA_START:                   return true;
8898                 case EXPR_VA_ARG:                     return true;
8899                 case EXPR_VA_COPY:                    return true;
8900                 case EXPR_STATEMENT:                  return true; // TODO
8901                 case EXPR_COMPOUND_LITERAL:           return false;
8902
8903                 case EXPR_UNARY_NEGATE:               return false;
8904                 case EXPR_UNARY_PLUS:                 return false;
8905                 case EXPR_UNARY_BITWISE_NEGATE:       return false;
8906                 case EXPR_UNARY_NOT:                  return false;
8907                 case EXPR_UNARY_DEREFERENCE:          return false;
8908                 case EXPR_UNARY_TAKE_ADDRESS:         return false;
8909                 case EXPR_UNARY_POSTFIX_INCREMENT:    return true;
8910                 case EXPR_UNARY_POSTFIX_DECREMENT:    return true;
8911                 case EXPR_UNARY_PREFIX_INCREMENT:     return true;
8912                 case EXPR_UNARY_PREFIX_DECREMENT:     return true;
8913
8914                 /* Treat void casts as if they have an effect in order to being able to
8915                  * suppress the warning */
8916                 case EXPR_UNARY_CAST: {
8917                         type_t *const type = skip_typeref(expr->base.type);
8918                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
8919                 }
8920
8921                 case EXPR_UNARY_CAST_IMPLICIT:        return true;
8922                 case EXPR_UNARY_ASSUME:               return true;
8923                 case EXPR_UNARY_DELETE:               return true;
8924                 case EXPR_UNARY_DELETE_ARRAY:         return true;
8925                 case EXPR_UNARY_THROW:                return true;
8926
8927                 case EXPR_BINARY_ADD:                 return false;
8928                 case EXPR_BINARY_SUB:                 return false;
8929                 case EXPR_BINARY_MUL:                 return false;
8930                 case EXPR_BINARY_DIV:                 return false;
8931                 case EXPR_BINARY_MOD:                 return false;
8932                 case EXPR_BINARY_EQUAL:               return false;
8933                 case EXPR_BINARY_NOTEQUAL:            return false;
8934                 case EXPR_BINARY_LESS:                return false;
8935                 case EXPR_BINARY_LESSEQUAL:           return false;
8936                 case EXPR_BINARY_GREATER:             return false;
8937                 case EXPR_BINARY_GREATEREQUAL:        return false;
8938                 case EXPR_BINARY_BITWISE_AND:         return false;
8939                 case EXPR_BINARY_BITWISE_OR:          return false;
8940                 case EXPR_BINARY_BITWISE_XOR:         return false;
8941                 case EXPR_BINARY_SHIFTLEFT:           return false;
8942                 case EXPR_BINARY_SHIFTRIGHT:          return false;
8943                 case EXPR_BINARY_ASSIGN:              return true;
8944                 case EXPR_BINARY_MUL_ASSIGN:          return true;
8945                 case EXPR_BINARY_DIV_ASSIGN:          return true;
8946                 case EXPR_BINARY_MOD_ASSIGN:          return true;
8947                 case EXPR_BINARY_ADD_ASSIGN:          return true;
8948                 case EXPR_BINARY_SUB_ASSIGN:          return true;
8949                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:    return true;
8950                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:   return true;
8951                 case EXPR_BINARY_BITWISE_AND_ASSIGN:  return true;
8952                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:  return true;
8953                 case EXPR_BINARY_BITWISE_OR_ASSIGN:   return true;
8954
8955                 /* Only examine the right hand side of && and ||, because the left hand
8956                  * side already has the effect of controlling the execution of the right
8957                  * hand side */
8958                 case EXPR_BINARY_LOGICAL_AND:
8959                 case EXPR_BINARY_LOGICAL_OR:
8960                 /* Only examine the right hand side of a comma expression, because the left
8961                  * hand side has a separate warning */
8962                 case EXPR_BINARY_COMMA:
8963                         return expression_has_effect(expr->binary.right);
8964
8965                 case EXPR_BINARY_ISGREATER:           return false;
8966                 case EXPR_BINARY_ISGREATEREQUAL:      return false;
8967                 case EXPR_BINARY_ISLESS:              return false;
8968                 case EXPR_BINARY_ISLESSEQUAL:         return false;
8969                 case EXPR_BINARY_ISLESSGREATER:       return false;
8970                 case EXPR_BINARY_ISUNORDERED:         return false;
8971         }
8972
8973         internal_errorf(HERE, "unexpected expression");
8974 }
8975
8976 static void semantic_comma(binary_expression_t *expression)
8977 {
8978         if (warning.unused_value) {
8979                 const expression_t *const left = expression->left;
8980                 if (!expression_has_effect(left)) {
8981                         warningf(&left->base.source_position,
8982                                  "left-hand operand of comma expression has no effect");
8983                 }
8984         }
8985         expression->base.type = expression->right->base.type;
8986 }
8987
8988 /**
8989  * @param prec_r precedence of the right operand
8990  */
8991 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8992 static expression_t *parse_##binexpression_type(expression_t *left)          \
8993 {                                                                            \
8994         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
8995         binexpr->binary.left  = left;                                            \
8996         eat(token_type);                                                         \
8997                                                                              \
8998         expression_t *right = parse_sub_expression(prec_r);                      \
8999                                                                              \
9000         binexpr->binary.right = right;                                           \
9001         sfunc(&binexpr->binary);                                                 \
9002                                                                              \
9003         return binexpr;                                                          \
9004 }
9005
9006 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
9007 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
9008 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
9009 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
9010 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
9011 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
9012 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
9013 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
9014 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
9015 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
9016 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
9017 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
9018 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
9019 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_arithmetic)
9020 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_arithmetic)
9021 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_arithmetic)
9022 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
9023 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
9024 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
9025 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9026 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9027 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9028 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9029 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9030 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_shift_assign)
9031 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_shift_assign)
9032 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
9033 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_integer_assign)
9034 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_integer_assign)
9035 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9036
9037
9038 static expression_t *parse_sub_expression(precedence_t precedence)
9039 {
9040         if (token.type < 0) {
9041                 return expected_expression_error();
9042         }
9043
9044         expression_parser_function_t *parser
9045                 = &expression_parsers[token.type];
9046         source_position_t             source_position = token.source_position;
9047         expression_t                 *left;
9048
9049         if (parser->parser != NULL) {
9050                 left = parser->parser();
9051         } else {
9052                 left = parse_primary_expression();
9053         }
9054         assert(left != NULL);
9055         left->base.source_position = source_position;
9056
9057         while (true) {
9058                 if (token.type < 0) {
9059                         return expected_expression_error();
9060                 }
9061
9062                 parser = &expression_parsers[token.type];
9063                 if (parser->infix_parser == NULL)
9064                         break;
9065                 if (parser->infix_precedence < precedence)
9066                         break;
9067
9068                 left = parser->infix_parser(left);
9069
9070                 assert(left != NULL);
9071                 assert(left->kind != EXPR_UNKNOWN);
9072                 left->base.source_position = source_position;
9073         }
9074
9075         return left;
9076 }
9077
9078 /**
9079  * Parse an expression.
9080  */
9081 static expression_t *parse_expression(void)
9082 {
9083         return parse_sub_expression(PREC_EXPRESSION);
9084 }
9085
9086 /**
9087  * Register a parser for a prefix-like operator.
9088  *
9089  * @param parser      the parser function
9090  * @param token_type  the token type of the prefix token
9091  */
9092 static void register_expression_parser(parse_expression_function parser,
9093                                        int token_type)
9094 {
9095         expression_parser_function_t *entry = &expression_parsers[token_type];
9096
9097         if (entry->parser != NULL) {
9098                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9099                 panic("trying to register multiple expression parsers for a token");
9100         }
9101         entry->parser = parser;
9102 }
9103
9104 /**
9105  * Register a parser for an infix operator with given precedence.
9106  *
9107  * @param parser      the parser function
9108  * @param token_type  the token type of the infix operator
9109  * @param precedence  the precedence of the operator
9110  */
9111 static void register_infix_parser(parse_expression_infix_function parser,
9112                 int token_type, precedence_t precedence)
9113 {
9114         expression_parser_function_t *entry = &expression_parsers[token_type];
9115
9116         if (entry->infix_parser != NULL) {
9117                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9118                 panic("trying to register multiple infix expression parsers for a "
9119                       "token");
9120         }
9121         entry->infix_parser     = parser;
9122         entry->infix_precedence = precedence;
9123 }
9124
9125 /**
9126  * Initialize the expression parsers.
9127  */
9128 static void init_expression_parsers(void)
9129 {
9130         memset(&expression_parsers, 0, sizeof(expression_parsers));
9131
9132         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9133         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9134         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9135         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9136         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9137         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9138         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9139         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9140         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9141         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9142         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9143         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9144         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9145         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9146         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9147         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9148         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9149         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9150         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9151         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9152         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9153         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9154         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9155         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9156         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9157         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9158         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9159         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9160         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9161         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9162         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9163         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9164         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9165         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9166         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9167         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9168         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9169
9170         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9171         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9172         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9173         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9174         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9175         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9176         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9177         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9178         register_expression_parser(parse_sizeof,                      T_sizeof);
9179         register_expression_parser(parse_alignof,                     T___alignof__);
9180         register_expression_parser(parse_extension,                   T___extension__);
9181         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9182         register_expression_parser(parse_delete,                      T_delete);
9183         register_expression_parser(parse_throw,                       T_throw);
9184 }
9185
9186 /**
9187  * Parse a asm statement arguments specification.
9188  */
9189 static asm_argument_t *parse_asm_arguments(bool is_out)
9190 {
9191         asm_argument_t  *result = NULL;
9192         asm_argument_t **anchor = &result;
9193
9194         while (token.type == T_STRING_LITERAL || token.type == '[') {
9195                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9196                 memset(argument, 0, sizeof(argument[0]));
9197
9198                 if (next_if('[')) {
9199                         if (token.type != T_IDENTIFIER) {
9200                                 parse_error_expected("while parsing asm argument",
9201                                                      T_IDENTIFIER, NULL);
9202                                 return NULL;
9203                         }
9204                         argument->symbol = token.v.symbol;
9205
9206                         expect(']', end_error);
9207                 }
9208
9209                 argument->constraints = parse_string_literals();
9210                 expect('(', end_error);
9211                 add_anchor_token(')');
9212                 expression_t *expression = parse_expression();
9213                 rem_anchor_token(')');
9214                 if (is_out) {
9215                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9216                          * change size or type representation (e.g. int -> long is ok, but
9217                          * int -> float is not) */
9218                         if (expression->kind == EXPR_UNARY_CAST) {
9219                                 type_t      *const type = expression->base.type;
9220                                 type_kind_t  const kind = type->kind;
9221                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9222                                         unsigned flags;
9223                                         unsigned size;
9224                                         if (kind == TYPE_ATOMIC) {
9225                                                 atomic_type_kind_t const akind = type->atomic.akind;
9226                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9227                                                 size  = get_atomic_type_size(akind);
9228                                         } else {
9229                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9230                                                 size  = get_atomic_type_size(get_intptr_kind());
9231                                         }
9232
9233                                         do {
9234                                                 expression_t *const value      = expression->unary.value;
9235                                                 type_t       *const value_type = value->base.type;
9236                                                 type_kind_t   const value_kind = value_type->kind;
9237
9238                                                 unsigned value_flags;
9239                                                 unsigned value_size;
9240                                                 if (value_kind == TYPE_ATOMIC) {
9241                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9242                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9243                                                         value_size  = get_atomic_type_size(value_akind);
9244                                                 } else if (value_kind == TYPE_POINTER) {
9245                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9246                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9247                                                 } else {
9248                                                         break;
9249                                                 }
9250
9251                                                 if (value_flags != flags || value_size != size)
9252                                                         break;
9253
9254                                                 expression = value;
9255                                         } while (expression->kind == EXPR_UNARY_CAST);
9256                                 }
9257                         }
9258
9259                         if (!is_lvalue(expression)) {
9260                                 errorf(&expression->base.source_position,
9261                                        "asm output argument is not an lvalue");
9262                         }
9263
9264                         if (argument->constraints.begin[0] == '+')
9265                                 mark_vars_read(expression, NULL);
9266                 } else {
9267                         mark_vars_read(expression, NULL);
9268                 }
9269                 argument->expression = expression;
9270                 expect(')', end_error);
9271
9272                 set_address_taken(expression, true);
9273
9274                 *anchor = argument;
9275                 anchor  = &argument->next;
9276
9277                 if (!next_if(','))
9278                         break;
9279         }
9280
9281         return result;
9282 end_error:
9283         return NULL;
9284 }
9285
9286 /**
9287  * Parse a asm statement clobber specification.
9288  */
9289 static asm_clobber_t *parse_asm_clobbers(void)
9290 {
9291         asm_clobber_t *result = NULL;
9292         asm_clobber_t *last   = NULL;
9293
9294         while (token.type == T_STRING_LITERAL) {
9295                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9296                 clobber->clobber       = parse_string_literals();
9297
9298                 if (last != NULL) {
9299                         last->next = clobber;
9300                 } else {
9301                         result = clobber;
9302                 }
9303                 last = clobber;
9304
9305                 if (!next_if(','))
9306                         break;
9307         }
9308
9309         return result;
9310 }
9311
9312 /**
9313  * Parse an asm statement.
9314  */
9315 static statement_t *parse_asm_statement(void)
9316 {
9317         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9318         asm_statement_t *asm_statement = &statement->asms;
9319
9320         eat(T_asm);
9321
9322         if (next_if(T_volatile))
9323                 asm_statement->is_volatile = true;
9324
9325         expect('(', end_error);
9326         add_anchor_token(')');
9327         add_anchor_token(':');
9328         asm_statement->asm_text = parse_string_literals();
9329
9330         if (!next_if(':')) {
9331                 rem_anchor_token(':');
9332                 goto end_of_asm;
9333         }
9334
9335         asm_statement->outputs = parse_asm_arguments(true);
9336         if (!next_if(':')) {
9337                 rem_anchor_token(':');
9338                 goto end_of_asm;
9339         }
9340
9341         asm_statement->inputs = parse_asm_arguments(false);
9342         if (!next_if(':')) {
9343                 rem_anchor_token(':');
9344                 goto end_of_asm;
9345         }
9346         rem_anchor_token(':');
9347
9348         asm_statement->clobbers = parse_asm_clobbers();
9349
9350 end_of_asm:
9351         rem_anchor_token(')');
9352         expect(')', end_error);
9353         expect(';', end_error);
9354
9355         if (asm_statement->outputs == NULL) {
9356                 /* GCC: An 'asm' instruction without any output operands will be treated
9357                  * identically to a volatile 'asm' instruction. */
9358                 asm_statement->is_volatile = true;
9359         }
9360
9361         return statement;
9362 end_error:
9363         return create_invalid_statement();
9364 }
9365
9366 /**
9367  * Parse a case statement.
9368  */
9369 static statement_t *parse_case_statement(void)
9370 {
9371         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9372         source_position_t *const pos       = &statement->base.source_position;
9373
9374         eat(T_case);
9375
9376         expression_t *const expression   = parse_expression();
9377         statement->case_label.expression = expression;
9378         if (!is_constant_expression(expression)) {
9379                 /* This check does not prevent the error message in all cases of an
9380                  * prior error while parsing the expression.  At least it catches the
9381                  * common case of a mistyped enum entry. */
9382                 if (is_type_valid(skip_typeref(expression->base.type))) {
9383                         errorf(pos, "case label does not reduce to an integer constant");
9384                 }
9385                 statement->case_label.is_bad = true;
9386         } else {
9387                 long const val = fold_constant_to_int(expression);
9388                 statement->case_label.first_case = val;
9389                 statement->case_label.last_case  = val;
9390         }
9391
9392         if (GNU_MODE) {
9393                 if (next_if(T_DOTDOTDOT)) {
9394                         expression_t *const end_range   = parse_expression();
9395                         statement->case_label.end_range = end_range;
9396                         if (!is_constant_expression(end_range)) {
9397                                 /* This check does not prevent the error message in all cases of an
9398                                  * prior error while parsing the expression.  At least it catches the
9399                                  * common case of a mistyped enum entry. */
9400                                 if (is_type_valid(skip_typeref(end_range->base.type))) {
9401                                         errorf(pos, "case range does not reduce to an integer constant");
9402                                 }
9403                                 statement->case_label.is_bad = true;
9404                         } else {
9405                                 long const val = fold_constant_to_int(end_range);
9406                                 statement->case_label.last_case = val;
9407
9408                                 if (warning.other && val < statement->case_label.first_case) {
9409                                         statement->case_label.is_empty_range = true;
9410                                         warningf(pos, "empty range specified");
9411                                 }
9412                         }
9413                 }
9414         }
9415
9416         PUSH_PARENT(statement);
9417
9418         expect(':', end_error);
9419 end_error:
9420
9421         if (current_switch != NULL) {
9422                 if (! statement->case_label.is_bad) {
9423                         /* Check for duplicate case values */
9424                         case_label_statement_t *c = &statement->case_label;
9425                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9426                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9427                                         continue;
9428
9429                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9430                                         continue;
9431
9432                                 errorf(pos, "duplicate case value (previously used %P)",
9433                                        &l->base.source_position);
9434                                 break;
9435                         }
9436                 }
9437                 /* link all cases into the switch statement */
9438                 if (current_switch->last_case == NULL) {
9439                         current_switch->first_case      = &statement->case_label;
9440                 } else {
9441                         current_switch->last_case->next = &statement->case_label;
9442                 }
9443                 current_switch->last_case = &statement->case_label;
9444         } else {
9445                 errorf(pos, "case label not within a switch statement");
9446         }
9447
9448         statement_t *const inner_stmt = parse_statement();
9449         statement->case_label.statement = inner_stmt;
9450         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9451                 errorf(&inner_stmt->base.source_position, "declaration after case label");
9452         }
9453
9454         POP_PARENT;
9455         return statement;
9456 }
9457
9458 /**
9459  * Parse a default statement.
9460  */
9461 static statement_t *parse_default_statement(void)
9462 {
9463         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9464
9465         eat(T_default);
9466
9467         PUSH_PARENT(statement);
9468
9469         expect(':', end_error);
9470         if (current_switch != NULL) {
9471                 const case_label_statement_t *def_label = current_switch->default_label;
9472                 if (def_label != NULL) {
9473                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9474                                &def_label->base.source_position);
9475                 } else {
9476                         current_switch->default_label = &statement->case_label;
9477
9478                         /* link all cases into the switch statement */
9479                         if (current_switch->last_case == NULL) {
9480                                 current_switch->first_case      = &statement->case_label;
9481                         } else {
9482                                 current_switch->last_case->next = &statement->case_label;
9483                         }
9484                         current_switch->last_case = &statement->case_label;
9485                 }
9486         } else {
9487                 errorf(&statement->base.source_position,
9488                         "'default' label not within a switch statement");
9489         }
9490
9491         statement_t *const inner_stmt = parse_statement();
9492         statement->case_label.statement = inner_stmt;
9493         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9494                 errorf(&inner_stmt->base.source_position, "declaration after default label");
9495         }
9496
9497         POP_PARENT;
9498         return statement;
9499 end_error:
9500         POP_PARENT;
9501         return create_invalid_statement();
9502 }
9503
9504 /**
9505  * Parse a label statement.
9506  */
9507 static statement_t *parse_label_statement(void)
9508 {
9509         assert(token.type == T_IDENTIFIER);
9510         symbol_t *symbol = token.v.symbol;
9511         label_t  *label  = get_label(symbol);
9512
9513         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9514         statement->label.label       = label;
9515
9516         next_token();
9517
9518         PUSH_PARENT(statement);
9519
9520         /* if statement is already set then the label is defined twice,
9521          * otherwise it was just mentioned in a goto/local label declaration so far
9522          */
9523         if (label->statement != NULL) {
9524                 errorf(HERE, "duplicate label '%Y' (declared %P)",
9525                        symbol, &label->base.source_position);
9526         } else {
9527                 label->base.source_position = token.source_position;
9528                 label->statement            = statement;
9529         }
9530
9531         eat(':');
9532
9533         if (token.type == '}') {
9534                 /* TODO only warn? */
9535                 if (warning.other && false) {
9536                         warningf(HERE, "label at end of compound statement");
9537                         statement->label.statement = create_empty_statement();
9538                 } else {
9539                         errorf(HERE, "label at end of compound statement");
9540                         statement->label.statement = create_invalid_statement();
9541                 }
9542         } else if (token.type == ';') {
9543                 /* Eat an empty statement here, to avoid the warning about an empty
9544                  * statement after a label.  label:; is commonly used to have a label
9545                  * before a closing brace. */
9546                 statement->label.statement = create_empty_statement();
9547                 next_token();
9548         } else {
9549                 statement_t *const inner_stmt = parse_statement();
9550                 statement->label.statement = inner_stmt;
9551                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9552                         errorf(&inner_stmt->base.source_position, "declaration after label");
9553                 }
9554         }
9555
9556         /* remember the labels in a list for later checking */
9557         *label_anchor = &statement->label;
9558         label_anchor  = &statement->label.next;
9559
9560         POP_PARENT;
9561         return statement;
9562 }
9563
9564 /**
9565  * Parse an if statement.
9566  */
9567 static statement_t *parse_if(void)
9568 {
9569         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9570
9571         eat(T_if);
9572
9573         PUSH_PARENT(statement);
9574
9575         add_anchor_token('{');
9576
9577         expect('(', end_error);
9578         add_anchor_token(')');
9579         expression_t *const expr = parse_expression();
9580         statement->ifs.condition = expr;
9581         /* §6.8.4.1:1  The controlling expression of an if statement shall have
9582          *             scalar type. */
9583         semantic_condition(expr, "condition of 'if'-statment");
9584         mark_vars_read(expr, NULL);
9585         rem_anchor_token(')');
9586         expect(')', end_error);
9587
9588 end_error:
9589         rem_anchor_token('{');
9590
9591         add_anchor_token(T_else);
9592         statement_t *const true_stmt = parse_statement();
9593         statement->ifs.true_statement = true_stmt;
9594         rem_anchor_token(T_else);
9595
9596         if (next_if(T_else)) {
9597                 statement->ifs.false_statement = parse_statement();
9598         } else if (warning.parentheses &&
9599                         true_stmt->kind == STATEMENT_IF &&
9600                         true_stmt->ifs.false_statement != NULL) {
9601                 warningf(&true_stmt->base.source_position,
9602                                 "suggest explicit braces to avoid ambiguous 'else'");
9603         }
9604
9605         POP_PARENT;
9606         return statement;
9607 }
9608
9609 /**
9610  * Check that all enums are handled in a switch.
9611  *
9612  * @param statement  the switch statement to check
9613  */
9614 static void check_enum_cases(const switch_statement_t *statement)
9615 {
9616         const type_t *type = skip_typeref(statement->expression->base.type);
9617         if (! is_type_enum(type))
9618                 return;
9619         const enum_type_t *enumt = &type->enumt;
9620
9621         /* if we have a default, no warnings */
9622         if (statement->default_label != NULL)
9623                 return;
9624
9625         /* FIXME: calculation of value should be done while parsing */
9626         /* TODO: quadratic algorithm here. Change to an n log n one */
9627         long            last_value = -1;
9628         const entity_t *entry      = enumt->enume->base.next;
9629         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9630              entry = entry->base.next) {
9631                 const expression_t *expression = entry->enum_value.value;
9632                 long                value      = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9633                 bool                found      = false;
9634                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9635                         if (l->expression == NULL)
9636                                 continue;
9637                         if (l->first_case <= value && value <= l->last_case) {
9638                                 found = true;
9639                                 break;
9640                         }
9641                 }
9642                 if (! found) {
9643                         warningf(&statement->base.source_position,
9644                                  "enumeration value '%Y' not handled in switch",
9645                                  entry->base.symbol);
9646                 }
9647                 last_value = value;
9648         }
9649 }
9650
9651 /**
9652  * Parse a switch statement.
9653  */
9654 static statement_t *parse_switch(void)
9655 {
9656         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9657
9658         eat(T_switch);
9659
9660         PUSH_PARENT(statement);
9661
9662         expect('(', end_error);
9663         add_anchor_token(')');
9664         expression_t *const expr = parse_expression();
9665         mark_vars_read(expr, NULL);
9666         type_t       *      type = skip_typeref(expr->base.type);
9667         if (is_type_integer(type)) {
9668                 type = promote_integer(type);
9669                 if (warning.traditional) {
9670                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9671                                 warningf(&expr->base.source_position,
9672                                         "'%T' switch expression not converted to '%T' in ISO C",
9673                                         type, type_int);
9674                         }
9675                 }
9676         } else if (is_type_valid(type)) {
9677                 errorf(&expr->base.source_position,
9678                        "switch quantity is not an integer, but '%T'", type);
9679                 type = type_error_type;
9680         }
9681         statement->switchs.expression = create_implicit_cast(expr, type);
9682         expect(')', end_error);
9683         rem_anchor_token(')');
9684
9685         switch_statement_t *rem = current_switch;
9686         current_switch          = &statement->switchs;
9687         statement->switchs.body = parse_statement();
9688         current_switch          = rem;
9689
9690         if (warning.switch_default &&
9691             statement->switchs.default_label == NULL) {
9692                 warningf(&statement->base.source_position, "switch has no default case");
9693         }
9694         if (warning.switch_enum)
9695                 check_enum_cases(&statement->switchs);
9696
9697         POP_PARENT;
9698         return statement;
9699 end_error:
9700         POP_PARENT;
9701         return create_invalid_statement();
9702 }
9703
9704 static statement_t *parse_loop_body(statement_t *const loop)
9705 {
9706         statement_t *const rem = current_loop;
9707         current_loop = loop;
9708
9709         statement_t *const body = parse_statement();
9710
9711         current_loop = rem;
9712         return body;
9713 }
9714
9715 /**
9716  * Parse a while statement.
9717  */
9718 static statement_t *parse_while(void)
9719 {
9720         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9721
9722         eat(T_while);
9723
9724         PUSH_PARENT(statement);
9725
9726         expect('(', end_error);
9727         add_anchor_token(')');
9728         expression_t *const cond = parse_expression();
9729         statement->whiles.condition = cond;
9730         /* §6.8.5:2    The controlling expression of an iteration statement shall
9731          *             have scalar type. */
9732         semantic_condition(cond, "condition of 'while'-statement");
9733         mark_vars_read(cond, NULL);
9734         rem_anchor_token(')');
9735         expect(')', end_error);
9736
9737         statement->whiles.body = parse_loop_body(statement);
9738
9739         POP_PARENT;
9740         return statement;
9741 end_error:
9742         POP_PARENT;
9743         return create_invalid_statement();
9744 }
9745
9746 /**
9747  * Parse a do statement.
9748  */
9749 static statement_t *parse_do(void)
9750 {
9751         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9752
9753         eat(T_do);
9754
9755         PUSH_PARENT(statement);
9756
9757         add_anchor_token(T_while);
9758         statement->do_while.body = parse_loop_body(statement);
9759         rem_anchor_token(T_while);
9760
9761         expect(T_while, end_error);
9762         expect('(', end_error);
9763         add_anchor_token(')');
9764         expression_t *const cond = parse_expression();
9765         statement->do_while.condition = cond;
9766         /* §6.8.5:2    The controlling expression of an iteration statement shall
9767          *             have scalar type. */
9768         semantic_condition(cond, "condition of 'do-while'-statement");
9769         mark_vars_read(cond, NULL);
9770         rem_anchor_token(')');
9771         expect(')', end_error);
9772         expect(';', end_error);
9773
9774         POP_PARENT;
9775         return statement;
9776 end_error:
9777         POP_PARENT;
9778         return create_invalid_statement();
9779 }
9780
9781 /**
9782  * Parse a for statement.
9783  */
9784 static statement_t *parse_for(void)
9785 {
9786         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9787
9788         eat(T_for);
9789
9790         expect('(', end_error1);
9791         add_anchor_token(')');
9792
9793         PUSH_PARENT(statement);
9794
9795         size_t const  top       = environment_top();
9796         scope_t      *old_scope = scope_push(&statement->fors.scope);
9797
9798         bool old_gcc_extension = in_gcc_extension;
9799         while (next_if(T___extension__)) {
9800                 in_gcc_extension = true;
9801         }
9802
9803         if (next_if(';')) {
9804         } else if (is_declaration_specifier(&token, false)) {
9805                 parse_declaration(record_entity, DECL_FLAGS_NONE);
9806         } else {
9807                 add_anchor_token(';');
9808                 expression_t *const init = parse_expression();
9809                 statement->fors.initialisation = init;
9810                 mark_vars_read(init, ENT_ANY);
9811                 if (warning.unused_value && !expression_has_effect(init)) {
9812                         warningf(&init->base.source_position,
9813                                         "initialisation of 'for'-statement has no effect");
9814                 }
9815                 rem_anchor_token(';');
9816                 expect(';', end_error2);
9817         }
9818         in_gcc_extension = old_gcc_extension;
9819
9820         if (token.type != ';') {
9821                 add_anchor_token(';');
9822                 expression_t *const cond = parse_expression();
9823                 statement->fors.condition = cond;
9824                 /* §6.8.5:2    The controlling expression of an iteration statement
9825                  *             shall have scalar type. */
9826                 semantic_condition(cond, "condition of 'for'-statement");
9827                 mark_vars_read(cond, NULL);
9828                 rem_anchor_token(';');
9829         }
9830         expect(';', end_error2);
9831         if (token.type != ')') {
9832                 expression_t *const step = parse_expression();
9833                 statement->fors.step = step;
9834                 mark_vars_read(step, ENT_ANY);
9835                 if (warning.unused_value && !expression_has_effect(step)) {
9836                         warningf(&step->base.source_position,
9837                                  "step of 'for'-statement has no effect");
9838                 }
9839         }
9840         expect(')', end_error2);
9841         rem_anchor_token(')');
9842         statement->fors.body = parse_loop_body(statement);
9843
9844         assert(current_scope == &statement->fors.scope);
9845         scope_pop(old_scope);
9846         environment_pop_to(top);
9847
9848         POP_PARENT;
9849         return statement;
9850
9851 end_error2:
9852         POP_PARENT;
9853         rem_anchor_token(')');
9854         assert(current_scope == &statement->fors.scope);
9855         scope_pop(old_scope);
9856         environment_pop_to(top);
9857         /* fallthrough */
9858
9859 end_error1:
9860         return create_invalid_statement();
9861 }
9862
9863 /**
9864  * Parse a goto statement.
9865  */
9866 static statement_t *parse_goto(void)
9867 {
9868         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9869         eat(T_goto);
9870
9871         if (GNU_MODE && next_if('*')) {
9872                 expression_t *expression = parse_expression();
9873                 mark_vars_read(expression, NULL);
9874
9875                 /* Argh: although documentation says the expression must be of type void*,
9876                  * gcc accepts anything that can be casted into void* without error */
9877                 type_t *type = expression->base.type;
9878
9879                 if (type != type_error_type) {
9880                         if (!is_type_pointer(type) && !is_type_integer(type)) {
9881                                 errorf(&expression->base.source_position,
9882                                         "cannot convert to a pointer type");
9883                         } else if (warning.other && type != type_void_ptr) {
9884                                 warningf(&expression->base.source_position,
9885                                         "type of computed goto expression should be 'void*' not '%T'", type);
9886                         }
9887                         expression = create_implicit_cast(expression, type_void_ptr);
9888                 }
9889
9890                 statement->gotos.expression = expression;
9891         } else if (token.type == T_IDENTIFIER) {
9892                 symbol_t *symbol = token.v.symbol;
9893                 next_token();
9894                 statement->gotos.label = get_label(symbol);
9895         } else {
9896                 if (GNU_MODE)
9897                         parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9898                 else
9899                         parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9900                 eat_until_anchor();
9901                 goto end_error;
9902         }
9903
9904         /* remember the goto's in a list for later checking */
9905         *goto_anchor = &statement->gotos;
9906         goto_anchor  = &statement->gotos.next;
9907
9908         expect(';', end_error);
9909
9910         return statement;
9911 end_error:
9912         return create_invalid_statement();
9913 }
9914
9915 /**
9916  * Parse a continue statement.
9917  */
9918 static statement_t *parse_continue(void)
9919 {
9920         if (current_loop == NULL) {
9921                 errorf(HERE, "continue statement not within loop");
9922         }
9923
9924         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9925
9926         eat(T_continue);
9927         expect(';', end_error);
9928
9929 end_error:
9930         return statement;
9931 }
9932
9933 /**
9934  * Parse a break statement.
9935  */
9936 static statement_t *parse_break(void)
9937 {
9938         if (current_switch == NULL && current_loop == NULL) {
9939                 errorf(HERE, "break statement not within loop or switch");
9940         }
9941
9942         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9943
9944         eat(T_break);
9945         expect(';', end_error);
9946
9947 end_error:
9948         return statement;
9949 }
9950
9951 /**
9952  * Parse a __leave statement.
9953  */
9954 static statement_t *parse_leave_statement(void)
9955 {
9956         if (current_try == NULL) {
9957                 errorf(HERE, "__leave statement not within __try");
9958         }
9959
9960         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9961
9962         eat(T___leave);
9963         expect(';', end_error);
9964
9965 end_error:
9966         return statement;
9967 }
9968
9969 /**
9970  * Check if a given entity represents a local variable.
9971  */
9972 static bool is_local_variable(const entity_t *entity)
9973 {
9974         if (entity->kind != ENTITY_VARIABLE)
9975                 return false;
9976
9977         switch ((storage_class_tag_t) entity->declaration.storage_class) {
9978         case STORAGE_CLASS_AUTO:
9979         case STORAGE_CLASS_REGISTER: {
9980                 const type_t *type = skip_typeref(entity->declaration.type);
9981                 if (is_type_function(type)) {
9982                         return false;
9983                 } else {
9984                         return true;
9985                 }
9986         }
9987         default:
9988                 return false;
9989         }
9990 }
9991
9992 /**
9993  * Check if a given expression represents a local variable.
9994  */
9995 static bool expression_is_local_variable(const expression_t *expression)
9996 {
9997         if (expression->base.kind != EXPR_REFERENCE) {
9998                 return false;
9999         }
10000         const entity_t *entity = expression->reference.entity;
10001         return is_local_variable(entity);
10002 }
10003
10004 /**
10005  * Check if a given expression represents a local variable and
10006  * return its declaration then, else return NULL.
10007  */
10008 entity_t *expression_is_variable(const expression_t *expression)
10009 {
10010         if (expression->base.kind != EXPR_REFERENCE) {
10011                 return NULL;
10012         }
10013         entity_t *entity = expression->reference.entity;
10014         if (entity->kind != ENTITY_VARIABLE)
10015                 return NULL;
10016
10017         return entity;
10018 }
10019
10020 /**
10021  * Parse a return statement.
10022  */
10023 static statement_t *parse_return(void)
10024 {
10025         eat(T_return);
10026
10027         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10028
10029         expression_t *return_value = NULL;
10030         if (token.type != ';') {
10031                 return_value = parse_expression();
10032                 mark_vars_read(return_value, NULL);
10033         }
10034
10035         const type_t *const func_type = skip_typeref(current_function->base.type);
10036         assert(is_type_function(func_type));
10037         type_t *const return_type = skip_typeref(func_type->function.return_type);
10038
10039         source_position_t const *const pos = &statement->base.source_position;
10040         if (return_value != NULL) {
10041                 type_t *return_value_type = skip_typeref(return_value->base.type);
10042
10043                 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10044                         if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10045                                 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10046                                 /* Only warn in C mode, because GCC does the same */
10047                                 if (c_mode & _CXX || strict_mode) {
10048                                         errorf(pos,
10049                                                         "'return' with a value, in function returning 'void'");
10050                                 } else if (warning.other) {
10051                                         warningf(pos,
10052                                                         "'return' with a value, in function returning 'void'");
10053                                 }
10054                         } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10055                                 /* Only warn in C mode, because GCC does the same */
10056                                 if (strict_mode) {
10057                                         errorf(pos,
10058                                                         "'return' with expression in function returning 'void'");
10059                                 } else if (warning.other) {
10060                                         warningf(pos,
10061                                                         "'return' with expression in function returning 'void'");
10062                                 }
10063                         }
10064                 } else {
10065                         assign_error_t error = semantic_assign(return_type, return_value);
10066                         report_assign_error(error, return_type, return_value, "'return'",
10067                                         pos);
10068                 }
10069                 return_value = create_implicit_cast(return_value, return_type);
10070                 /* check for returning address of a local var */
10071                 if (warning.other && return_value != NULL
10072                                 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10073                         const expression_t *expression = return_value->unary.value;
10074                         if (expression_is_local_variable(expression)) {
10075                                 warningf(pos, "function returns address of local variable");
10076                         }
10077                 }
10078         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10079                 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10080                 if (c_mode & _CXX || strict_mode) {
10081                         errorf(pos,
10082                                         "'return' without value, in function returning non-void");
10083                 } else {
10084                         warningf(pos,
10085                                         "'return' without value, in function returning non-void");
10086                 }
10087         }
10088         statement->returns.value = return_value;
10089
10090         expect(';', end_error);
10091
10092 end_error:
10093         return statement;
10094 }
10095
10096 /**
10097  * Parse a declaration statement.
10098  */
10099 static statement_t *parse_declaration_statement(void)
10100 {
10101         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10102
10103         entity_t *before = current_scope->last_entity;
10104         if (GNU_MODE) {
10105                 parse_external_declaration();
10106         } else {
10107                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10108         }
10109
10110         declaration_statement_t *const decl  = &statement->declaration;
10111         entity_t                *const begin =
10112                 before != NULL ? before->base.next : current_scope->entities;
10113         decl->declarations_begin = begin;
10114         decl->declarations_end   = begin != NULL ? current_scope->last_entity : NULL;
10115
10116         return statement;
10117 }
10118
10119 /**
10120  * Parse an expression statement, ie. expr ';'.
10121  */
10122 static statement_t *parse_expression_statement(void)
10123 {
10124         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10125
10126         expression_t *const expr         = parse_expression();
10127         statement->expression.expression = expr;
10128         mark_vars_read(expr, ENT_ANY);
10129
10130         expect(';', end_error);
10131
10132 end_error:
10133         return statement;
10134 }
10135
10136 /**
10137  * Parse a microsoft __try { } __finally { } or
10138  * __try{ } __except() { }
10139  */
10140 static statement_t *parse_ms_try_statment(void)
10141 {
10142         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10143         eat(T___try);
10144
10145         PUSH_PARENT(statement);
10146
10147         ms_try_statement_t *rem = current_try;
10148         current_try = &statement->ms_try;
10149         statement->ms_try.try_statement = parse_compound_statement(false);
10150         current_try = rem;
10151
10152         POP_PARENT;
10153
10154         if (next_if(T___except)) {
10155                 expect('(', end_error);
10156                 add_anchor_token(')');
10157                 expression_t *const expr = parse_expression();
10158                 mark_vars_read(expr, NULL);
10159                 type_t       *      type = skip_typeref(expr->base.type);
10160                 if (is_type_integer(type)) {
10161                         type = promote_integer(type);
10162                 } else if (is_type_valid(type)) {
10163                         errorf(&expr->base.source_position,
10164                                "__expect expression is not an integer, but '%T'", type);
10165                         type = type_error_type;
10166                 }
10167                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10168                 rem_anchor_token(')');
10169                 expect(')', end_error);
10170                 statement->ms_try.final_statement = parse_compound_statement(false);
10171         } else if (next_if(T__finally)) {
10172                 statement->ms_try.final_statement = parse_compound_statement(false);
10173         } else {
10174                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10175                 return create_invalid_statement();
10176         }
10177         return statement;
10178 end_error:
10179         return create_invalid_statement();
10180 }
10181
10182 static statement_t *parse_empty_statement(void)
10183 {
10184         if (warning.empty_statement) {
10185                 warningf(HERE, "statement is empty");
10186         }
10187         statement_t *const statement = create_empty_statement();
10188         eat(';');
10189         return statement;
10190 }
10191
10192 static statement_t *parse_local_label_declaration(void)
10193 {
10194         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10195
10196         eat(T___label__);
10197
10198         entity_t *begin = NULL, *end = NULL;
10199
10200         do {
10201                 if (token.type != T_IDENTIFIER) {
10202                         parse_error_expected("while parsing local label declaration",
10203                                 T_IDENTIFIER, NULL);
10204                         goto end_error;
10205                 }
10206                 symbol_t *symbol = token.v.symbol;
10207                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10208                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10209                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10210                                symbol, &entity->base.source_position);
10211                 } else {
10212                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10213
10214                         entity->base.parent_scope    = current_scope;
10215                         entity->base.namespc         = NAMESPACE_LABEL;
10216                         entity->base.source_position = token.source_position;
10217                         entity->base.symbol          = symbol;
10218
10219                         if (end != NULL)
10220                                 end->base.next = entity;
10221                         end = entity;
10222                         if (begin == NULL)
10223                                 begin = entity;
10224
10225                         environment_push(entity);
10226                 }
10227                 next_token();
10228         } while (next_if(','));
10229         eat(';');
10230 end_error:
10231         statement->declaration.declarations_begin = begin;
10232         statement->declaration.declarations_end   = end;
10233         return statement;
10234 }
10235
10236 static void parse_namespace_definition(void)
10237 {
10238         eat(T_namespace);
10239
10240         entity_t *entity = NULL;
10241         symbol_t *symbol = NULL;
10242
10243         if (token.type == T_IDENTIFIER) {
10244                 symbol = token.v.symbol;
10245                 next_token();
10246
10247                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10248                 if (entity       != NULL             &&
10249                                 entity->kind != ENTITY_NAMESPACE &&
10250                                 entity->base.parent_scope == current_scope) {
10251                         if (!is_error_entity(entity)) {
10252                                 error_redefined_as_different_kind(&token.source_position,
10253                                                 entity, ENTITY_NAMESPACE);
10254                         }
10255                         entity = NULL;
10256                 }
10257         }
10258
10259         if (entity == NULL) {
10260                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10261                 entity->base.symbol          = symbol;
10262                 entity->base.source_position = token.source_position;
10263                 entity->base.namespc         = NAMESPACE_NORMAL;
10264                 entity->base.parent_scope    = current_scope;
10265         }
10266
10267         if (token.type == '=') {
10268                 /* TODO: parse namespace alias */
10269                 panic("namespace alias definition not supported yet");
10270         }
10271
10272         environment_push(entity);
10273         append_entity(current_scope, entity);
10274
10275         size_t const  top       = environment_top();
10276         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10277
10278         expect('{', end_error);
10279         parse_externals();
10280         expect('}', end_error);
10281
10282 end_error:
10283         assert(current_scope == &entity->namespacee.members);
10284         scope_pop(old_scope);
10285         environment_pop_to(top);
10286 }
10287
10288 /**
10289  * Parse a statement.
10290  * There's also parse_statement() which additionally checks for
10291  * "statement has no effect" warnings
10292  */
10293 static statement_t *intern_parse_statement(void)
10294 {
10295         statement_t *statement = NULL;
10296
10297         /* declaration or statement */
10298         add_anchor_token(';');
10299         switch (token.type) {
10300         case T_IDENTIFIER: {
10301                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10302                 if (la1_type == ':') {
10303                         statement = parse_label_statement();
10304                 } else if (is_typedef_symbol(token.v.symbol)) {
10305                         statement = parse_declaration_statement();
10306                 } else {
10307                         /* it's an identifier, the grammar says this must be an
10308                          * expression statement. However it is common that users mistype
10309                          * declaration types, so we guess a bit here to improve robustness
10310                          * for incorrect programs */
10311                         switch (la1_type) {
10312                         case '&':
10313                         case '*':
10314                                 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10315                                         goto expression_statment;
10316                                 /* FALLTHROUGH */
10317
10318                         DECLARATION_START
10319                         case T_IDENTIFIER:
10320                                 statement = parse_declaration_statement();
10321                                 break;
10322
10323                         default:
10324 expression_statment:
10325                                 statement = parse_expression_statement();
10326                                 break;
10327                         }
10328                 }
10329                 break;
10330         }
10331
10332         case T___extension__:
10333                 /* This can be a prefix to a declaration or an expression statement.
10334                  * We simply eat it now and parse the rest with tail recursion. */
10335                 while (next_if(T___extension__)) {}
10336                 bool old_gcc_extension = in_gcc_extension;
10337                 in_gcc_extension       = true;
10338                 statement = intern_parse_statement();
10339                 in_gcc_extension = old_gcc_extension;
10340                 break;
10341
10342         DECLARATION_START
10343                 statement = parse_declaration_statement();
10344                 break;
10345
10346         case T___label__:
10347                 statement = parse_local_label_declaration();
10348                 break;
10349
10350         case ';':         statement = parse_empty_statement();         break;
10351         case '{':         statement = parse_compound_statement(false); break;
10352         case T___leave:   statement = parse_leave_statement();         break;
10353         case T___try:     statement = parse_ms_try_statment();         break;
10354         case T_asm:       statement = parse_asm_statement();           break;
10355         case T_break:     statement = parse_break();                   break;
10356         case T_case:      statement = parse_case_statement();          break;
10357         case T_continue:  statement = parse_continue();                break;
10358         case T_default:   statement = parse_default_statement();       break;
10359         case T_do:        statement = parse_do();                      break;
10360         case T_for:       statement = parse_for();                     break;
10361         case T_goto:      statement = parse_goto();                    break;
10362         case T_if:        statement = parse_if();                      break;
10363         case T_return:    statement = parse_return();                  break;
10364         case T_switch:    statement = parse_switch();                  break;
10365         case T_while:     statement = parse_while();                   break;
10366
10367         EXPRESSION_START
10368                 statement = parse_expression_statement();
10369                 break;
10370
10371         default:
10372                 errorf(HERE, "unexpected token %K while parsing statement", &token);
10373                 statement = create_invalid_statement();
10374                 if (!at_anchor())
10375                         next_token();
10376                 break;
10377         }
10378         rem_anchor_token(';');
10379
10380         assert(statement != NULL
10381                         && statement->base.source_position.input_name != NULL);
10382
10383         return statement;
10384 }
10385
10386 /**
10387  * parse a statement and emits "statement has no effect" warning if needed
10388  * (This is really a wrapper around intern_parse_statement with check for 1
10389  *  single warning. It is needed, because for statement expressions we have
10390  *  to avoid the warning on the last statement)
10391  */
10392 static statement_t *parse_statement(void)
10393 {
10394         statement_t *statement = intern_parse_statement();
10395
10396         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10397                 expression_t *expression = statement->expression.expression;
10398                 if (!expression_has_effect(expression)) {
10399                         warningf(&expression->base.source_position,
10400                                         "statement has no effect");
10401                 }
10402         }
10403
10404         return statement;
10405 }
10406
10407 /**
10408  * Parse a compound statement.
10409  */
10410 static statement_t *parse_compound_statement(bool inside_expression_statement)
10411 {
10412         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10413
10414         PUSH_PARENT(statement);
10415
10416         eat('{');
10417         add_anchor_token('}');
10418         /* tokens, which can start a statement */
10419         /* TODO MS, __builtin_FOO */
10420         add_anchor_token('!');
10421         add_anchor_token('&');
10422         add_anchor_token('(');
10423         add_anchor_token('*');
10424         add_anchor_token('+');
10425         add_anchor_token('-');
10426         add_anchor_token('{');
10427         add_anchor_token('~');
10428         add_anchor_token(T_CHARACTER_CONSTANT);
10429         add_anchor_token(T_COLONCOLON);
10430         add_anchor_token(T_FLOATINGPOINT);
10431         add_anchor_token(T_IDENTIFIER);
10432         add_anchor_token(T_INTEGER);
10433         add_anchor_token(T_MINUSMINUS);
10434         add_anchor_token(T_PLUSPLUS);
10435         add_anchor_token(T_STRING_LITERAL);
10436         add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10437         add_anchor_token(T_WIDE_STRING_LITERAL);
10438         add_anchor_token(T__Bool);
10439         add_anchor_token(T__Complex);
10440         add_anchor_token(T__Imaginary);
10441         add_anchor_token(T___FUNCTION__);
10442         add_anchor_token(T___PRETTY_FUNCTION__);
10443         add_anchor_token(T___alignof__);
10444         add_anchor_token(T___attribute__);
10445         add_anchor_token(T___builtin_va_start);
10446         add_anchor_token(T___extension__);
10447         add_anchor_token(T___func__);
10448         add_anchor_token(T___imag__);
10449         add_anchor_token(T___label__);
10450         add_anchor_token(T___real__);
10451         add_anchor_token(T___thread);
10452         add_anchor_token(T_asm);
10453         add_anchor_token(T_auto);
10454         add_anchor_token(T_bool);
10455         add_anchor_token(T_break);
10456         add_anchor_token(T_case);
10457         add_anchor_token(T_char);
10458         add_anchor_token(T_class);
10459         add_anchor_token(T_const);
10460         add_anchor_token(T_const_cast);
10461         add_anchor_token(T_continue);
10462         add_anchor_token(T_default);
10463         add_anchor_token(T_delete);
10464         add_anchor_token(T_double);
10465         add_anchor_token(T_do);
10466         add_anchor_token(T_dynamic_cast);
10467         add_anchor_token(T_enum);
10468         add_anchor_token(T_extern);
10469         add_anchor_token(T_false);
10470         add_anchor_token(T_float);
10471         add_anchor_token(T_for);
10472         add_anchor_token(T_goto);
10473         add_anchor_token(T_if);
10474         add_anchor_token(T_inline);
10475         add_anchor_token(T_int);
10476         add_anchor_token(T_long);
10477         add_anchor_token(T_new);
10478         add_anchor_token(T_operator);
10479         add_anchor_token(T_register);
10480         add_anchor_token(T_reinterpret_cast);
10481         add_anchor_token(T_restrict);
10482         add_anchor_token(T_return);
10483         add_anchor_token(T_short);
10484         add_anchor_token(T_signed);
10485         add_anchor_token(T_sizeof);
10486         add_anchor_token(T_static);
10487         add_anchor_token(T_static_cast);
10488         add_anchor_token(T_struct);
10489         add_anchor_token(T_switch);
10490         add_anchor_token(T_template);
10491         add_anchor_token(T_this);
10492         add_anchor_token(T_throw);
10493         add_anchor_token(T_true);
10494         add_anchor_token(T_try);
10495         add_anchor_token(T_typedef);
10496         add_anchor_token(T_typeid);
10497         add_anchor_token(T_typename);
10498         add_anchor_token(T_typeof);
10499         add_anchor_token(T_union);
10500         add_anchor_token(T_unsigned);
10501         add_anchor_token(T_using);
10502         add_anchor_token(T_void);
10503         add_anchor_token(T_volatile);
10504         add_anchor_token(T_wchar_t);
10505         add_anchor_token(T_while);
10506
10507         size_t const  top       = environment_top();
10508         scope_t      *old_scope = scope_push(&statement->compound.scope);
10509
10510         statement_t **anchor            = &statement->compound.statements;
10511         bool          only_decls_so_far = true;
10512         while (token.type != '}') {
10513                 if (token.type == T_EOF) {
10514                         errorf(&statement->base.source_position,
10515                                "EOF while parsing compound statement");
10516                         break;
10517                 }
10518                 statement_t *sub_statement = intern_parse_statement();
10519                 if (is_invalid_statement(sub_statement)) {
10520                         /* an error occurred. if we are at an anchor, return */
10521                         if (at_anchor())
10522                                 goto end_error;
10523                         continue;
10524                 }
10525
10526                 if (warning.declaration_after_statement) {
10527                         if (sub_statement->kind != STATEMENT_DECLARATION) {
10528                                 only_decls_so_far = false;
10529                         } else if (!only_decls_so_far) {
10530                                 warningf(&sub_statement->base.source_position,
10531                                          "ISO C90 forbids mixed declarations and code");
10532                         }
10533                 }
10534
10535                 *anchor = sub_statement;
10536
10537                 while (sub_statement->base.next != NULL)
10538                         sub_statement = sub_statement->base.next;
10539
10540                 anchor = &sub_statement->base.next;
10541         }
10542         next_token();
10543
10544         /* look over all statements again to produce no effect warnings */
10545         if (warning.unused_value) {
10546                 statement_t *sub_statement = statement->compound.statements;
10547                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10548                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10549                                 continue;
10550                         /* don't emit a warning for the last expression in an expression
10551                          * statement as it has always an effect */
10552                         if (inside_expression_statement && sub_statement->base.next == NULL)
10553                                 continue;
10554
10555                         expression_t *expression = sub_statement->expression.expression;
10556                         if (!expression_has_effect(expression)) {
10557                                 warningf(&expression->base.source_position,
10558                                          "statement has no effect");
10559                         }
10560                 }
10561         }
10562
10563 end_error:
10564         rem_anchor_token(T_while);
10565         rem_anchor_token(T_wchar_t);
10566         rem_anchor_token(T_volatile);
10567         rem_anchor_token(T_void);
10568         rem_anchor_token(T_using);
10569         rem_anchor_token(T_unsigned);
10570         rem_anchor_token(T_union);
10571         rem_anchor_token(T_typeof);
10572         rem_anchor_token(T_typename);
10573         rem_anchor_token(T_typeid);
10574         rem_anchor_token(T_typedef);
10575         rem_anchor_token(T_try);
10576         rem_anchor_token(T_true);
10577         rem_anchor_token(T_throw);
10578         rem_anchor_token(T_this);
10579         rem_anchor_token(T_template);
10580         rem_anchor_token(T_switch);
10581         rem_anchor_token(T_struct);
10582         rem_anchor_token(T_static_cast);
10583         rem_anchor_token(T_static);
10584         rem_anchor_token(T_sizeof);
10585         rem_anchor_token(T_signed);
10586         rem_anchor_token(T_short);
10587         rem_anchor_token(T_return);
10588         rem_anchor_token(T_restrict);
10589         rem_anchor_token(T_reinterpret_cast);
10590         rem_anchor_token(T_register);
10591         rem_anchor_token(T_operator);
10592         rem_anchor_token(T_new);
10593         rem_anchor_token(T_long);
10594         rem_anchor_token(T_int);
10595         rem_anchor_token(T_inline);
10596         rem_anchor_token(T_if);
10597         rem_anchor_token(T_goto);
10598         rem_anchor_token(T_for);
10599         rem_anchor_token(T_float);
10600         rem_anchor_token(T_false);
10601         rem_anchor_token(T_extern);
10602         rem_anchor_token(T_enum);
10603         rem_anchor_token(T_dynamic_cast);
10604         rem_anchor_token(T_do);
10605         rem_anchor_token(T_double);
10606         rem_anchor_token(T_delete);
10607         rem_anchor_token(T_default);
10608         rem_anchor_token(T_continue);
10609         rem_anchor_token(T_const_cast);
10610         rem_anchor_token(T_const);
10611         rem_anchor_token(T_class);
10612         rem_anchor_token(T_char);
10613         rem_anchor_token(T_case);
10614         rem_anchor_token(T_break);
10615         rem_anchor_token(T_bool);
10616         rem_anchor_token(T_auto);
10617         rem_anchor_token(T_asm);
10618         rem_anchor_token(T___thread);
10619         rem_anchor_token(T___real__);
10620         rem_anchor_token(T___label__);
10621         rem_anchor_token(T___imag__);
10622         rem_anchor_token(T___func__);
10623         rem_anchor_token(T___extension__);
10624         rem_anchor_token(T___builtin_va_start);
10625         rem_anchor_token(T___attribute__);
10626         rem_anchor_token(T___alignof__);
10627         rem_anchor_token(T___PRETTY_FUNCTION__);
10628         rem_anchor_token(T___FUNCTION__);
10629         rem_anchor_token(T__Imaginary);
10630         rem_anchor_token(T__Complex);
10631         rem_anchor_token(T__Bool);
10632         rem_anchor_token(T_WIDE_STRING_LITERAL);
10633         rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10634         rem_anchor_token(T_STRING_LITERAL);
10635         rem_anchor_token(T_PLUSPLUS);
10636         rem_anchor_token(T_MINUSMINUS);
10637         rem_anchor_token(T_INTEGER);
10638         rem_anchor_token(T_IDENTIFIER);
10639         rem_anchor_token(T_FLOATINGPOINT);
10640         rem_anchor_token(T_COLONCOLON);
10641         rem_anchor_token(T_CHARACTER_CONSTANT);
10642         rem_anchor_token('~');
10643         rem_anchor_token('{');
10644         rem_anchor_token('-');
10645         rem_anchor_token('+');
10646         rem_anchor_token('*');
10647         rem_anchor_token('(');
10648         rem_anchor_token('&');
10649         rem_anchor_token('!');
10650         rem_anchor_token('}');
10651         assert(current_scope == &statement->compound.scope);
10652         scope_pop(old_scope);
10653         environment_pop_to(top);
10654
10655         POP_PARENT;
10656         return statement;
10657 }
10658
10659 /**
10660  * Check for unused global static functions and variables
10661  */
10662 static void check_unused_globals(void)
10663 {
10664         if (!warning.unused_function && !warning.unused_variable)
10665                 return;
10666
10667         for (const entity_t *entity = file_scope->entities; entity != NULL;
10668              entity = entity->base.next) {
10669                 if (!is_declaration(entity))
10670                         continue;
10671
10672                 const declaration_t *declaration = &entity->declaration;
10673                 if (declaration->used                  ||
10674                     declaration->modifiers & DM_UNUSED ||
10675                     declaration->modifiers & DM_USED   ||
10676                     declaration->storage_class != STORAGE_CLASS_STATIC)
10677                         continue;
10678
10679                 type_t *const type = declaration->type;
10680                 const char *s;
10681                 if (entity->kind == ENTITY_FUNCTION) {
10682                         /* inhibit warning for static inline functions */
10683                         if (entity->function.is_inline)
10684                                 continue;
10685
10686                         s = entity->function.statement != NULL ? "defined" : "declared";
10687                 } else {
10688                         s = "defined";
10689                 }
10690
10691                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10692                         type, declaration->base.symbol, s);
10693         }
10694 }
10695
10696 static void parse_global_asm(void)
10697 {
10698         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10699
10700         eat(T_asm);
10701         expect('(', end_error);
10702
10703         statement->asms.asm_text = parse_string_literals();
10704         statement->base.next     = unit->global_asm;
10705         unit->global_asm         = statement;
10706
10707         expect(')', end_error);
10708         expect(';', end_error);
10709
10710 end_error:;
10711 }
10712
10713 static void parse_linkage_specification(void)
10714 {
10715         eat(T_extern);
10716         assert(token.type == T_STRING_LITERAL);
10717
10718         const char *linkage = parse_string_literals().begin;
10719
10720         linkage_kind_t old_linkage = current_linkage;
10721         linkage_kind_t new_linkage;
10722         if (strcmp(linkage, "C") == 0) {
10723                 new_linkage = LINKAGE_C;
10724         } else if (strcmp(linkage, "C++") == 0) {
10725                 new_linkage = LINKAGE_CXX;
10726         } else {
10727                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10728                 new_linkage = LINKAGE_INVALID;
10729         }
10730         current_linkage = new_linkage;
10731
10732         if (next_if('{')) {
10733                 parse_externals();
10734                 expect('}', end_error);
10735         } else {
10736                 parse_external();
10737         }
10738
10739 end_error:
10740         assert(current_linkage == new_linkage);
10741         current_linkage = old_linkage;
10742 }
10743
10744 static void parse_external(void)
10745 {
10746         switch (token.type) {
10747                 DECLARATION_START_NO_EXTERN
10748                 case T_IDENTIFIER:
10749                 case T___extension__:
10750                 /* tokens below are for implicit int */
10751                 case '&': /* & x; -> int& x; (and error later, because C++ has no
10752                              implicit int) */
10753                 case '*': /* * x; -> int* x; */
10754                 case '(': /* (x); -> int (x); */
10755                         parse_external_declaration();
10756                         return;
10757
10758                 case T_extern:
10759                         if (look_ahead(1)->type == T_STRING_LITERAL) {
10760                                 parse_linkage_specification();
10761                         } else {
10762                                 parse_external_declaration();
10763                         }
10764                         return;
10765
10766                 case T_asm:
10767                         parse_global_asm();
10768                         return;
10769
10770                 case T_namespace:
10771                         parse_namespace_definition();
10772                         return;
10773
10774                 case ';':
10775                         if (!strict_mode) {
10776                                 if (warning.other)
10777                                         warningf(HERE, "stray ';' outside of function");
10778                                 next_token();
10779                                 return;
10780                         }
10781                         /* FALLTHROUGH */
10782
10783                 default:
10784                         errorf(HERE, "stray %K outside of function", &token);
10785                         if (token.type == '(' || token.type == '{' || token.type == '[')
10786                                 eat_until_matching_token(token.type);
10787                         next_token();
10788                         return;
10789         }
10790 }
10791
10792 static void parse_externals(void)
10793 {
10794         add_anchor_token('}');
10795         add_anchor_token(T_EOF);
10796
10797 #ifndef NDEBUG
10798         unsigned char token_anchor_copy[T_LAST_TOKEN];
10799         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10800 #endif
10801
10802         while (token.type != T_EOF && token.type != '}') {
10803 #ifndef NDEBUG
10804                 bool anchor_leak = false;
10805                 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10806                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10807                         if (count != 0) {
10808                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10809                                 anchor_leak = true;
10810                         }
10811                 }
10812                 if (in_gcc_extension) {
10813                         errorf(HERE, "Leaked __extension__");
10814                         anchor_leak = true;
10815                 }
10816
10817                 if (anchor_leak)
10818                         abort();
10819 #endif
10820
10821                 parse_external();
10822         }
10823
10824         rem_anchor_token(T_EOF);
10825         rem_anchor_token('}');
10826 }
10827
10828 /**
10829  * Parse a translation unit.
10830  */
10831 static void parse_translation_unit(void)
10832 {
10833         add_anchor_token(T_EOF);
10834
10835         while (true) {
10836                 parse_externals();
10837
10838                 if (token.type == T_EOF)
10839                         break;
10840
10841                 errorf(HERE, "stray %K outside of function", &token);
10842                 if (token.type == '(' || token.type == '{' || token.type == '[')
10843                         eat_until_matching_token(token.type);
10844                 next_token();
10845         }
10846 }
10847
10848 /**
10849  * Parse the input.
10850  *
10851  * @return  the translation unit or NULL if errors occurred.
10852  */
10853 void start_parsing(void)
10854 {
10855         environment_stack = NEW_ARR_F(stack_entry_t, 0);
10856         label_stack       = NEW_ARR_F(stack_entry_t, 0);
10857         diagnostic_count  = 0;
10858         error_count       = 0;
10859         warning_count     = 0;
10860
10861         type_set_output(stderr);
10862         ast_set_output(stderr);
10863
10864         assert(unit == NULL);
10865         unit = allocate_ast_zero(sizeof(unit[0]));
10866
10867         assert(file_scope == NULL);
10868         file_scope = &unit->scope;
10869
10870         assert(current_scope == NULL);
10871         scope_push(&unit->scope);
10872
10873         create_gnu_builtins();
10874         if (c_mode & _MS)
10875                 create_microsoft_intrinsics();
10876 }
10877
10878 translation_unit_t *finish_parsing(void)
10879 {
10880         assert(current_scope == &unit->scope);
10881         scope_pop(NULL);
10882
10883         assert(file_scope == &unit->scope);
10884         check_unused_globals();
10885         file_scope = NULL;
10886
10887         DEL_ARR_F(environment_stack);
10888         DEL_ARR_F(label_stack);
10889
10890         translation_unit_t *result = unit;
10891         unit = NULL;
10892         return result;
10893 }
10894
10895 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10896  * are given length one. */
10897 static void complete_incomplete_arrays(void)
10898 {
10899         size_t n = ARR_LEN(incomplete_arrays);
10900         for (size_t i = 0; i != n; ++i) {
10901                 declaration_t *const decl      = incomplete_arrays[i];
10902                 type_t        *const orig_type = decl->type;
10903                 type_t        *const type      = skip_typeref(orig_type);
10904
10905                 if (!is_type_incomplete(type))
10906                         continue;
10907
10908                 if (warning.other) {
10909                         warningf(&decl->base.source_position,
10910                                         "array '%#T' assumed to have one element",
10911                                         orig_type, decl->base.symbol);
10912                 }
10913
10914                 type_t *const new_type = duplicate_type(type);
10915                 new_type->array.size_constant     = true;
10916                 new_type->array.has_implicit_size = true;
10917                 new_type->array.size              = 1;
10918
10919                 type_t *const result = identify_new_type(new_type);
10920
10921                 decl->type = result;
10922         }
10923 }
10924
10925 void prepare_main_collect2(entity_t *entity)
10926 {
10927         // create call to __main
10928         symbol_t *symbol         = symbol_table_insert("__main");
10929         entity_t *subsubmain_ent
10930                 = create_implicit_function(symbol, &builtin_source_position);
10931
10932         expression_t *ref         = allocate_expression_zero(EXPR_REFERENCE);
10933         type_t       *ftype       = subsubmain_ent->declaration.type;
10934         ref->base.source_position = builtin_source_position;
10935         ref->base.type            = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10936         ref->reference.entity     = subsubmain_ent;
10937
10938         expression_t *call = allocate_expression_zero(EXPR_CALL);
10939         call->base.source_position = builtin_source_position;
10940         call->base.type            = type_void;
10941         call->call.function        = ref;
10942
10943         statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10944         expr_statement->base.source_position  = builtin_source_position;
10945         expr_statement->expression.expression = call;
10946
10947         statement_t *statement = entity->function.statement;
10948         assert(statement->kind == STATEMENT_COMPOUND);
10949         compound_statement_t *compounds = &statement->compound;
10950
10951         expr_statement->base.next = compounds->statements;
10952         compounds->statements     = expr_statement;
10953 }
10954
10955 void parse(void)
10956 {
10957         lookahead_bufpos = 0;
10958         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10959                 next_token();
10960         }
10961         current_linkage   = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10962         incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10963         parse_translation_unit();
10964         complete_incomplete_arrays();
10965         DEL_ARR_F(incomplete_arrays);
10966         incomplete_arrays = NULL;
10967 }
10968
10969 /**
10970  * create a builtin function.
10971  */
10972 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10973 {
10974         symbol_t *symbol = symbol_table_insert(name);
10975         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10976         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
10977         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10978         entity->declaration.type                   = function_type;
10979         entity->declaration.implicit               = true;
10980         entity->base.symbol                        = symbol;
10981         entity->base.source_position               = builtin_source_position;
10982
10983         entity->function.btk                       = kind;
10984
10985         record_entity(entity, /*is_definition=*/false);
10986         return entity;
10987 }
10988
10989
10990 /**
10991  * Create predefined gnu builtins.
10992  */
10993 static void create_gnu_builtins(void)
10994 {
10995 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10996
10997         GNU_BUILTIN(alloca,         make_function_1_type(type_void_ptr, type_size_t));
10998         GNU_BUILTIN(huge_val,       make_function_0_type(type_double));
10999         GNU_BUILTIN(inf,            make_function_0_type(type_double));
11000         GNU_BUILTIN(inff,           make_function_0_type(type_float));
11001         GNU_BUILTIN(infl,           make_function_0_type(type_long_double));
11002         GNU_BUILTIN(nan,            make_function_1_type(type_double, type_char_ptr));
11003         GNU_BUILTIN(nanf,           make_function_1_type(type_float, type_char_ptr));
11004         GNU_BUILTIN(nanl,           make_function_1_type(type_long_double, type_char_ptr));
11005         GNU_BUILTIN(va_end,         make_function_1_type(type_void, type_valist));
11006         GNU_BUILTIN(expect,         make_function_2_type(type_long, type_long, type_long));
11007         GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11008         GNU_BUILTIN(frame_address,  make_function_1_type(type_void_ptr, type_unsigned_int));
11009         GNU_BUILTIN(ffs,            make_function_1_type(type_int, type_unsigned_int));
11010         GNU_BUILTIN(clz,            make_function_1_type(type_int, type_unsigned_int));
11011         GNU_BUILTIN(ctz,            make_function_1_type(type_int, type_unsigned_int));
11012         GNU_BUILTIN(popcount,       make_function_1_type(type_int, type_unsigned_int));
11013         GNU_BUILTIN(parity,         make_function_1_type(type_int, type_unsigned_int));
11014         GNU_BUILTIN(prefetch,       make_function_1_type_variadic(type_float, type_void_ptr));
11015         GNU_BUILTIN(trap,           make_function_0_type_noreturn(type_void));
11016
11017 #undef GNU_BUILTIN
11018 }
11019
11020 /**
11021  * Create predefined MS intrinsics.
11022  */
11023 static void create_microsoft_intrinsics(void)
11024 {
11025 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11026
11027         /* intrinsics for all architectures */
11028         MS_BUILTIN(_rotl,                  make_function_2_type(type_unsigned_int,   type_unsigned_int, type_int));
11029         MS_BUILTIN(_rotr,                  make_function_2_type(type_unsigned_int,   type_unsigned_int, type_int));
11030         MS_BUILTIN(_rotl64,                make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11031         MS_BUILTIN(_rotr64,                make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11032         MS_BUILTIN(_byteswap_ushort,       make_function_1_type(type_unsigned_short, type_unsigned_short));
11033         MS_BUILTIN(_byteswap_ulong,        make_function_1_type(type_unsigned_long,  type_unsigned_long));
11034         MS_BUILTIN(_byteswap_uint64,       make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11035
11036         MS_BUILTIN(__debugbreak,            make_function_0_type(type_void));
11037         MS_BUILTIN(_ReturnAddress,          make_function_0_type(type_void_ptr));
11038         MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11039         MS_BUILTIN(__popcount,              make_function_1_type(type_unsigned_int, type_unsigned_int));
11040
11041         /* x86/x64 only */
11042         MS_BUILTIN(_enable,                make_function_0_type(type_void));
11043         MS_BUILTIN(_disable,               make_function_0_type(type_void));
11044         MS_BUILTIN(__inbyte,               make_function_1_type(type_unsigned_char, type_unsigned_short));
11045         MS_BUILTIN(__inword,               make_function_1_type(type_unsigned_short, type_unsigned_short));
11046         MS_BUILTIN(__indword,              make_function_1_type(type_unsigned_long, type_unsigned_short));
11047         MS_BUILTIN(__outbyte,              make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11048         MS_BUILTIN(__outword,              make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11049         MS_BUILTIN(__outdword,             make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11050         MS_BUILTIN(__ud2,                  make_function_0_type_noreturn(type_void));
11051         MS_BUILTIN(_BitScanForward,        make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11052         MS_BUILTIN(_BitScanReverse,        make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11053         MS_BUILTIN(_InterlockedExchange,   make_function_2_type(type_long, type_long_ptr, type_long));
11054         MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11055
11056         if (machine_size <= 32) {
11057                 MS_BUILTIN(__readeflags,           make_function_0_type(type_unsigned_int));
11058                 MS_BUILTIN(__writeeflags,          make_function_1_type(type_void, type_unsigned_int));
11059         } else {
11060                 MS_BUILTIN(__readeflags,           make_function_0_type(type_unsigned_int64));
11061                 MS_BUILTIN(__writeeflags,          make_function_1_type(type_void, type_unsigned_int64));
11062         }
11063
11064 #undef MS_BUILTIN
11065 }
11066
11067 /**
11068  * Initialize the parser.
11069  */
11070 void init_parser(void)
11071 {
11072         sym_anonymous = symbol_table_insert("<anonymous>");
11073
11074         memset(token_anchor_set, 0, sizeof(token_anchor_set));
11075
11076         init_expression_parsers();
11077         obstack_init(&temp_obst);
11078
11079         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11080         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11081 }
11082
11083 /**
11084  * Terminate the parser.
11085  */
11086 void exit_parser(void)
11087 {
11088         obstack_free(&temp_obst, NULL);
11089 }