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