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