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