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