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