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