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