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