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