c35ae06172647fe019cdab5ef021a19be6c6f574
[cparser] / parser.c
1 /*
2  * This file is part of cparser.
3  * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18  * 02111-1307, USA.
19  */
20 #include <config.h>
21
22 #include <assert.h>
23 #include <stdarg.h>
24 #include <stdbool.h>
25
26 #include "parser.h"
27 #include "diagnostic.h"
28 #include "format_check.h"
29 #include "lexer.h"
30 #include "symbol_t.h"
31 #include "token_t.h"
32 #include "types.h"
33 #include "type_t.h"
34 #include "type_hash.h"
35 #include "ast_t.h"
36 #include "entity_t.h"
37 #include "lang_features.h"
38 #include "walk_statements.h"
39 #include "warning.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
43
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 2
46
47 typedef struct {
48         entity_t           *old_entity;
49         symbol_t           *symbol;
50         entity_namespace_t  namespc;
51 } stack_entry_t;
52
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
55         long              argument;
56         argument_list_t  *next;
57 };
58
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61         gnu_attribute_kind_t kind;           /**< The kind of the GNU attribute. */
62         gnu_attribute_t     *next;
63         bool                 invalid;        /**< Set if this attribute had argument errors, */
64         bool                 have_arguments; /**< True, if this attribute has arguments. */
65         union {
66                 size_t              value;
67                 string_t            string;
68                 atomic_type_kind_t  akind;
69                 long                argument;  /**< Single argument. */
70                 argument_list_t    *arguments; /**< List of argument expressions. */
71         } u;
72 };
73
74 typedef struct declaration_specifiers_t  declaration_specifiers_t;
75 struct declaration_specifiers_t {
76         source_position_t  source_position;
77         storage_class_t    storage_class;
78         unsigned char      alignment;         /**< Alignment, 0 if not set. */
79         bool               is_inline    : 1;
80         bool               thread_local : 1;  /**< GCC __thread */
81         bool               deprecated   : 1;
82         decl_modifiers_t   modifiers;         /**< declaration modifiers */
83         gnu_attribute_t   *gnu_attributes;    /**< list of GNU attributes */
84         const char        *deprecated_string; /**< can be set if declaration was marked deprecated. */
85         symbol_t          *get_property_sym;  /**< the name of the get property if set. */
86         symbol_t          *put_property_sym;  /**< the name of the put property if set. */
87         type_t            *type;
88 };
89
90 /**
91  * An environment for parsing initializers (and compound literals).
92  */
93 typedef struct parse_initializer_env_t {
94         type_t     *type;   /**< the type of the initializer. In case of an
95                                  array type with unspecified size this gets
96                                  adjusted to the actual size. */
97         entity_t   *entity; /**< the variable that is initialized if any */
98         bool        must_be_constant;
99 } parse_initializer_env_t;
100
101 /**
102  * Capture a MS __base extension.
103  */
104 typedef struct based_spec_t {
105         source_position_t  source_position;
106         variable_t        *base_variable;
107 } based_spec_t;
108
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110
111 /** The current token. */
112 static token_t              token;
113 /** The lookahead ring-buffer. */
114 static token_t              lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static int                  lookahead_bufpos;
117 static stack_entry_t       *environment_stack = NULL;
118 static stack_entry_t       *label_stack       = NULL;
119 static scope_t             *file_scope        = NULL;
120 static scope_t             *current_scope     = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t          *current_function  = NULL;
123 static entity_t            *current_init_decl = NULL;
124 static switch_statement_t  *current_switch    = NULL;
125 static statement_t         *current_loop      = NULL;
126 static statement_t         *current_parent    = NULL;
127 static ms_try_statement_t  *current_try       = NULL;
128 static linkage_kind_t       current_linkage   = LINKAGE_INVALID;
129 static goto_statement_t    *goto_first        = NULL;
130 static goto_statement_t   **goto_anchor       = NULL;
131 static label_statement_t   *label_first       = NULL;
132 static label_statement_t  **label_anchor      = NULL;
133 /** current translation unit. */
134 static translation_unit_t  *unit              = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool                 in_type_prop      = false;
137 /** true in we are in a __extension__ context. */
138 static bool                 in_gcc_extension  = false;
139 static struct obstack       temp_obst;
140 static entity_t            *anonymous_entity;
141
142
143 #define PUSH_PARENT(stmt)                          \
144         statement_t *const prev_parent = current_parent; \
145         ((void)(current_parent = (stmt)))
146 #define POP_PARENT ((void)(current_parent = prev_parent))
147
148 /** special symbol used for anonymous entities. */
149 static const symbol_t *sym_anonymous = NULL;
150
151 /* symbols for Microsoft extended-decl-modifier */
152 static const symbol_t *sym_align      = NULL;
153 static const symbol_t *sym_allocate   = NULL;
154 static const symbol_t *sym_dllimport  = NULL;
155 static const symbol_t *sym_dllexport  = NULL;
156 static const symbol_t *sym_naked      = NULL;
157 static const symbol_t *sym_noinline   = NULL;
158 static const symbol_t *sym_noreturn   = NULL;
159 static const symbol_t *sym_nothrow    = NULL;
160 static const symbol_t *sym_novtable   = NULL;
161 static const symbol_t *sym_property   = NULL;
162 static const symbol_t *sym_get        = NULL;
163 static const symbol_t *sym_put        = NULL;
164 static const symbol_t *sym_selectany  = NULL;
165 static const symbol_t *sym_thread     = NULL;
166 static const symbol_t *sym_uuid       = NULL;
167 static const symbol_t *sym_deprecated = NULL;
168 static const symbol_t *sym_restrict   = NULL;
169 static const symbol_t *sym_noalias    = NULL;
170
171 /** The token anchor set */
172 static unsigned char token_anchor_set[T_LAST_TOKEN];
173
174 /** The current source position. */
175 #define HERE (&token.source_position)
176
177 /** true if we are in GCC mode. */
178 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
179
180 static type_t *type_valist;
181
182 static statement_t *parse_compound_statement(bool inside_expression_statement);
183 static statement_t *parse_statement(void);
184
185 static expression_t *parse_sub_expression(precedence_t);
186 static expression_t *parse_expression(void);
187 static type_t       *parse_typename(void);
188 static void          parse_externals(void);
189 static void          parse_external(void);
190
191 static void parse_compound_type_entries(compound_t *compound_declaration);
192
193 typedef enum declarator_flags_t {
194         DECL_FLAGS_NONE             = 0,
195         DECL_MAY_BE_ABSTRACT        = 1U << 0,
196         DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
197         DECL_IS_PARAMETER           = 1U << 2
198 } declarator_flags_t;
199
200 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
201                                   declarator_flags_t flags);
202
203 static entity_t *record_entity(entity_t *entity, bool is_definition);
204
205 static void semantic_comparison(binary_expression_t *expression);
206
207 #define STORAGE_CLASSES       \
208         STORAGE_CLASSES_NO_EXTERN \
209         case T_extern:
210
211 #define STORAGE_CLASSES_NO_EXTERN \
212         case T_typedef:         \
213         case T_static:          \
214         case T_auto:            \
215         case T_register:        \
216         case T___thread:
217
218 #define TYPE_QUALIFIERS     \
219         case T_const:           \
220         case T_restrict:        \
221         case T_volatile:        \
222         case T_inline:          \
223         case T__forceinline:    \
224         case T___attribute__:
225
226 #define COMPLEX_SPECIFIERS  \
227         case T__Complex:
228 #define IMAGINARY_SPECIFIERS \
229         case T__Imaginary:
230
231 #define TYPE_SPECIFIERS       \
232         case T__Bool:             \
233         case T___builtin_va_list: \
234         case T___typeof__:        \
235         case T__declspec:         \
236         case T_bool:              \
237         case T_char:              \
238         case T_double:            \
239         case T_enum:              \
240         case T_float:             \
241         case T_int:               \
242         case T_long:              \
243         case T_short:             \
244         case T_signed:            \
245         case T_struct:            \
246         case T_union:             \
247         case T_unsigned:          \
248         case T_void:              \
249         COMPLEX_SPECIFIERS        \
250         IMAGINARY_SPECIFIERS
251
252 #define DECLARATION_START   \
253         STORAGE_CLASSES         \
254         TYPE_QUALIFIERS         \
255         TYPE_SPECIFIERS
256
257 #define DECLARATION_START_NO_EXTERN \
258         STORAGE_CLASSES_NO_EXTERN       \
259         TYPE_QUALIFIERS                 \
260         TYPE_SPECIFIERS
261
262 #define TYPENAME_START      \
263         TYPE_QUALIFIERS         \
264         TYPE_SPECIFIERS
265
266 #define EXPRESSION_START           \
267         case '!':                        \
268         case '&':                        \
269         case '(':                        \
270         case '*':                        \
271         case '+':                        \
272         case '-':                        \
273         case '~':                        \
274         case T_ANDAND:                   \
275         case T_CHARACTER_CONSTANT:       \
276         case T_FLOATINGPOINT:            \
277         case T_INTEGER:                  \
278         case T_MINUSMINUS:               \
279         case T_PLUSPLUS:                 \
280         case T_STRING_LITERAL:           \
281         case T_WIDE_CHARACTER_CONSTANT:  \
282         case T_WIDE_STRING_LITERAL:      \
283         case T___FUNCDNAME__:            \
284         case T___FUNCSIG__:              \
285         case T___FUNCTION__:             \
286         case T___PRETTY_FUNCTION__:      \
287         case T___alignof__:              \
288         case T___builtin_alloca:         \
289         case T___builtin_classify_type:  \
290         case T___builtin_constant_p:     \
291         case T___builtin_expect:         \
292         case T___builtin_huge_val:       \
293         case T___builtin_inf:            \
294         case T___builtin_inff:           \
295         case T___builtin_infl:           \
296         case T___builtin_isgreater:      \
297         case T___builtin_isgreaterequal: \
298         case T___builtin_isless:         \
299         case T___builtin_islessequal:    \
300         case T___builtin_islessgreater:  \
301         case T___builtin_isunordered:    \
302         case T___builtin_nan:            \
303         case T___builtin_nanf:           \
304         case T___builtin_nanl:           \
305         case T___builtin_offsetof:       \
306         case T___builtin_prefetch:       \
307         case T___builtin_va_arg:         \
308         case T___builtin_va_end:         \
309         case T___builtin_va_start:       \
310         case T___func__:                 \
311         case T___noop:                   \
312         case T__assume:                  \
313         case T_delete:                   \
314         case T_false:                    \
315         case T_sizeof:                   \
316         case T_throw:                    \
317         case T_true:
318
319 /**
320  * Allocate an AST node with given size and
321  * initialize all fields with zero.
322  */
323 static void *allocate_ast_zero(size_t size)
324 {
325         void *res = allocate_ast(size);
326         memset(res, 0, size);
327         return res;
328 }
329
330 static size_t get_entity_struct_size(entity_kind_t kind)
331 {
332         static const size_t sizes[] = {
333                 [ENTITY_VARIABLE]        = sizeof(variable_t),
334                 [ENTITY_PARAMETER]       = sizeof(parameter_t),
335                 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
336                 [ENTITY_FUNCTION]        = sizeof(function_t),
337                 [ENTITY_TYPEDEF]         = sizeof(typedef_t),
338                 [ENTITY_STRUCT]          = sizeof(compound_t),
339                 [ENTITY_UNION]           = sizeof(compound_t),
340                 [ENTITY_ENUM]            = sizeof(enum_t),
341                 [ENTITY_ENUM_VALUE]      = sizeof(enum_value_t),
342                 [ENTITY_LABEL]           = sizeof(label_t),
343                 [ENTITY_LOCAL_LABEL]     = sizeof(label_t),
344                 [ENTITY_NAMESPACE]       = sizeof(namespace_t)
345         };
346         assert(kind < sizeof(sizes) / sizeof(sizes[0]));
347         assert(sizes[kind] != 0);
348         return sizes[kind];
349 }
350
351 static entity_t *allocate_entity_zero(entity_kind_t kind)
352 {
353         size_t    size   = get_entity_struct_size(kind);
354         entity_t *entity = allocate_ast_zero(size);
355         entity->kind     = kind;
356         return entity;
357 }
358
359 /**
360  * Returns the size of a statement node.
361  *
362  * @param kind  the statement kind
363  */
364 static size_t get_statement_struct_size(statement_kind_t kind)
365 {
366         static const size_t sizes[] = {
367                 [STATEMENT_INVALID]     = sizeof(invalid_statement_t),
368                 [STATEMENT_EMPTY]       = sizeof(empty_statement_t),
369                 [STATEMENT_COMPOUND]    = sizeof(compound_statement_t),
370                 [STATEMENT_RETURN]      = sizeof(return_statement_t),
371                 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
372                 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
373                 [STATEMENT_IF]          = sizeof(if_statement_t),
374                 [STATEMENT_SWITCH]      = sizeof(switch_statement_t),
375                 [STATEMENT_EXPRESSION]  = sizeof(expression_statement_t),
376                 [STATEMENT_CONTINUE]    = sizeof(statement_base_t),
377                 [STATEMENT_BREAK]       = sizeof(statement_base_t),
378                 [STATEMENT_GOTO]        = sizeof(goto_statement_t),
379                 [STATEMENT_LABEL]       = sizeof(label_statement_t),
380                 [STATEMENT_CASE_LABEL]  = sizeof(case_label_statement_t),
381                 [STATEMENT_WHILE]       = sizeof(while_statement_t),
382                 [STATEMENT_DO_WHILE]    = sizeof(do_while_statement_t),
383                 [STATEMENT_FOR]         = sizeof(for_statement_t),
384                 [STATEMENT_ASM]         = sizeof(asm_statement_t),
385                 [STATEMENT_MS_TRY]      = sizeof(ms_try_statement_t),
386                 [STATEMENT_LEAVE]       = sizeof(leave_statement_t)
387         };
388         assert(kind < sizeof(sizes) / sizeof(sizes[0]));
389         assert(sizes[kind] != 0);
390         return sizes[kind];
391 }
392
393 /**
394  * Returns the size of an expression node.
395  *
396  * @param kind  the expression kind
397  */
398 static size_t get_expression_struct_size(expression_kind_t kind)
399 {
400         static const size_t sizes[] = {
401                 [EXPR_INVALID]                 = sizeof(expression_base_t),
402                 [EXPR_REFERENCE]               = sizeof(reference_expression_t),
403                 [EXPR_REFERENCE_ENUM_VALUE]    = sizeof(reference_expression_t),
404                 [EXPR_CONST]                   = sizeof(const_expression_t),
405                 [EXPR_CHARACTER_CONSTANT]      = sizeof(const_expression_t),
406                 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
407                 [EXPR_STRING_LITERAL]          = sizeof(string_literal_expression_t),
408                 [EXPR_WIDE_STRING_LITERAL]     = sizeof(wide_string_literal_expression_t),
409                 [EXPR_COMPOUND_LITERAL]        = sizeof(compound_literal_expression_t),
410                 [EXPR_CALL]                    = sizeof(call_expression_t),
411                 [EXPR_UNARY_FIRST]             = sizeof(unary_expression_t),
412                 [EXPR_BINARY_FIRST]            = sizeof(binary_expression_t),
413                 [EXPR_CONDITIONAL]             = sizeof(conditional_expression_t),
414                 [EXPR_SELECT]                  = sizeof(select_expression_t),
415                 [EXPR_ARRAY_ACCESS]            = sizeof(array_access_expression_t),
416                 [EXPR_SIZEOF]                  = sizeof(typeprop_expression_t),
417                 [EXPR_ALIGNOF]                 = sizeof(typeprop_expression_t),
418                 [EXPR_CLASSIFY_TYPE]           = sizeof(classify_type_expression_t),
419                 [EXPR_FUNCNAME]                = sizeof(funcname_expression_t),
420                 [EXPR_BUILTIN_SYMBOL]          = sizeof(builtin_symbol_expression_t),
421                 [EXPR_BUILTIN_CONSTANT_P]      = sizeof(builtin_constant_expression_t),
422                 [EXPR_BUILTIN_PREFETCH]        = sizeof(builtin_prefetch_expression_t),
423                 [EXPR_OFFSETOF]                = sizeof(offsetof_expression_t),
424                 [EXPR_VA_START]                = sizeof(va_start_expression_t),
425                 [EXPR_VA_ARG]                  = sizeof(va_arg_expression_t),
426                 [EXPR_STATEMENT]               = sizeof(statement_expression_t),
427                 [EXPR_LABEL_ADDRESS]           = sizeof(label_address_expression_t),
428         };
429         if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
430                 return sizes[EXPR_UNARY_FIRST];
431         }
432         if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
433                 return sizes[EXPR_BINARY_FIRST];
434         }
435         assert(kind < sizeof(sizes) / sizeof(sizes[0]));
436         assert(sizes[kind] != 0);
437         return sizes[kind];
438 }
439
440 /**
441  * Allocate a statement node of given kind and initialize all
442  * fields with zero.
443  */
444 static statement_t *allocate_statement_zero(statement_kind_t kind)
445 {
446         size_t       size = get_statement_struct_size(kind);
447         statement_t *res  = allocate_ast_zero(size);
448
449         res->base.kind            = kind;
450         res->base.parent          = current_parent;
451         res->base.source_position = token.source_position;
452         return res;
453 }
454
455 /**
456  * Allocate an expression node of given kind and initialize all
457  * fields with zero.
458  */
459 static expression_t *allocate_expression_zero(expression_kind_t kind)
460 {
461         size_t        size = get_expression_struct_size(kind);
462         expression_t *res  = allocate_ast_zero(size);
463
464         res->base.kind            = kind;
465         res->base.type            = type_error_type;
466         res->base.source_position = token.source_position;
467         return res;
468 }
469
470 /**
471  * Creates a new invalid expression.
472  */
473 static expression_t *create_invalid_expression(void)
474 {
475         return allocate_expression_zero(EXPR_INVALID);
476 }
477
478 /**
479  * Creates a new invalid statement.
480  */
481 static statement_t *create_invalid_statement(void)
482 {
483         return allocate_statement_zero(STATEMENT_INVALID);
484 }
485
486 /**
487  * Allocate a new empty statement.
488  */
489 static statement_t *create_empty_statement(void)
490 {
491         return allocate_statement_zero(STATEMENT_EMPTY);
492 }
493
494 /**
495  * Returns the size of a type node.
496  *
497  * @param kind  the type kind
498  */
499 static size_t get_type_struct_size(type_kind_t kind)
500 {
501         static const size_t sizes[] = {
502                 [TYPE_ATOMIC]          = sizeof(atomic_type_t),
503                 [TYPE_COMPLEX]         = sizeof(complex_type_t),
504                 [TYPE_IMAGINARY]       = sizeof(imaginary_type_t),
505                 [TYPE_BITFIELD]        = sizeof(bitfield_type_t),
506                 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
507                 [TYPE_COMPOUND_UNION]  = sizeof(compound_type_t),
508                 [TYPE_ENUM]            = sizeof(enum_type_t),
509                 [TYPE_FUNCTION]        = sizeof(function_type_t),
510                 [TYPE_POINTER]         = sizeof(pointer_type_t),
511                 [TYPE_ARRAY]           = sizeof(array_type_t),
512                 [TYPE_BUILTIN]         = sizeof(builtin_type_t),
513                 [TYPE_TYPEDEF]         = sizeof(typedef_type_t),
514                 [TYPE_TYPEOF]          = sizeof(typeof_type_t),
515         };
516         assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
517         assert(kind <= TYPE_TYPEOF);
518         assert(sizes[kind] != 0);
519         return sizes[kind];
520 }
521
522 /**
523  * Allocate a type node of given kind and initialize all
524  * fields with zero.
525  *
526  * @param kind             type kind to allocate
527  */
528 static type_t *allocate_type_zero(type_kind_t kind)
529 {
530         size_t  size = get_type_struct_size(kind);
531         type_t *res  = obstack_alloc(type_obst, size);
532         memset(res, 0, size);
533         res->base.kind = kind;
534
535         return res;
536 }
537
538 /**
539  * Returns the size of an initializer node.
540  *
541  * @param kind  the initializer kind
542  */
543 static size_t get_initializer_size(initializer_kind_t kind)
544 {
545         static const size_t sizes[] = {
546                 [INITIALIZER_VALUE]       = sizeof(initializer_value_t),
547                 [INITIALIZER_STRING]      = sizeof(initializer_string_t),
548                 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
549                 [INITIALIZER_LIST]        = sizeof(initializer_list_t),
550                 [INITIALIZER_DESIGNATOR]  = sizeof(initializer_designator_t)
551         };
552         assert(kind < sizeof(sizes) / sizeof(*sizes));
553         assert(sizes[kind] != 0);
554         return sizes[kind];
555 }
556
557 /**
558  * Allocate an initializer node of given kind and initialize all
559  * fields with zero.
560  */
561 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
562 {
563         initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
564         result->kind          = kind;
565
566         return result;
567 }
568
569 /**
570  * Free a type from the type obstack.
571  */
572 static void free_type(void *type)
573 {
574         obstack_free(type_obst, type);
575 }
576
577 /**
578  * Returns the index of the top element of the environment stack.
579  */
580 static size_t environment_top(void)
581 {
582         return ARR_LEN(environment_stack);
583 }
584
585 /**
586  * Returns the index of the top element of the global label stack.
587  */
588 static size_t label_top(void)
589 {
590         return ARR_LEN(label_stack);
591 }
592
593 /**
594  * Return the next token.
595  */
596 static inline void next_token(void)
597 {
598         token                              = lookahead_buffer[lookahead_bufpos];
599         lookahead_buffer[lookahead_bufpos] = lexer_token;
600         lexer_next_token();
601
602         lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
603
604 #ifdef PRINT_TOKENS
605         print_token(stderr, &token);
606         fprintf(stderr, "\n");
607 #endif
608 }
609
610 /**
611  * Return the next token with a given lookahead.
612  */
613 static inline const token_t *look_ahead(int num)
614 {
615         assert(num > 0 && num <= MAX_LOOKAHEAD);
616         int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
617         return &lookahead_buffer[pos];
618 }
619
620 /**
621  * Adds a token to the token anchor set (a multi-set).
622  */
623 static void add_anchor_token(int token_type)
624 {
625         assert(0 <= token_type && token_type < T_LAST_TOKEN);
626         ++token_anchor_set[token_type];
627 }
628
629 static int save_and_reset_anchor_state(int token_type)
630 {
631         assert(0 <= token_type && token_type < T_LAST_TOKEN);
632         int count = token_anchor_set[token_type];
633         token_anchor_set[token_type] = 0;
634         return count;
635 }
636
637 static void restore_anchor_state(int token_type, int count)
638 {
639         assert(0 <= token_type && token_type < T_LAST_TOKEN);
640         token_anchor_set[token_type] = count;
641 }
642
643 /**
644  * Remove a token from the token anchor set (a multi-set).
645  */
646 static void rem_anchor_token(int token_type)
647 {
648         assert(0 <= token_type && token_type < T_LAST_TOKEN);
649         assert(token_anchor_set[token_type] != 0);
650         --token_anchor_set[token_type];
651 }
652
653 static bool at_anchor(void)
654 {
655         if (token.type < 0)
656                 return false;
657         return token_anchor_set[token.type];
658 }
659
660 /**
661  * Eat tokens until a matching token is found.
662  */
663 static void eat_until_matching_token(int type)
664 {
665         int end_token;
666         switch (type) {
667                 case '(': end_token = ')';  break;
668                 case '{': end_token = '}';  break;
669                 case '[': end_token = ']';  break;
670                 default:  end_token = type; break;
671         }
672
673         unsigned parenthesis_count = 0;
674         unsigned brace_count       = 0;
675         unsigned bracket_count     = 0;
676         while (token.type        != end_token ||
677                parenthesis_count != 0         ||
678                brace_count       != 0         ||
679                bracket_count     != 0) {
680                 switch (token.type) {
681                 case T_EOF: return;
682                 case '(': ++parenthesis_count; break;
683                 case '{': ++brace_count;       break;
684                 case '[': ++bracket_count;     break;
685
686                 case ')':
687                         if (parenthesis_count > 0)
688                                 --parenthesis_count;
689                         goto check_stop;
690
691                 case '}':
692                         if (brace_count > 0)
693                                 --brace_count;
694                         goto check_stop;
695
696                 case ']':
697                         if (bracket_count > 0)
698                                 --bracket_count;
699 check_stop:
700                         if (token.type        == end_token &&
701                             parenthesis_count == 0         &&
702                             brace_count       == 0         &&
703                             bracket_count     == 0)
704                                 return;
705                         break;
706
707                 default:
708                         break;
709                 }
710                 next_token();
711         }
712 }
713
714 /**
715  * Eat input tokens until an anchor is found.
716  */
717 static void eat_until_anchor(void)
718 {
719         while (token_anchor_set[token.type] == 0) {
720                 if (token.type == '(' || token.type == '{' || token.type == '[')
721                         eat_until_matching_token(token.type);
722                 next_token();
723         }
724 }
725
726 static void eat_block(void)
727 {
728         eat_until_matching_token('{');
729         if (token.type == '}')
730                 next_token();
731 }
732
733 #define eat(token_type)  do { assert(token.type == (token_type)); next_token(); } while (0)
734
735 /**
736  * Report a parse error because an expected token was not found.
737  */
738 static
739 #if defined __GNUC__ && __GNUC__ >= 4
740 __attribute__((sentinel))
741 #endif
742 void parse_error_expected(const char *message, ...)
743 {
744         if (message != NULL) {
745                 errorf(HERE, "%s", message);
746         }
747         va_list ap;
748         va_start(ap, message);
749         errorf(HERE, "got '%K', expected %#k", &token, &ap, ", ");
750         va_end(ap);
751 }
752
753 /**
754  * Report an incompatible type.
755  */
756 static void type_error_incompatible(const char *msg,
757                 const source_position_t *source_position, type_t *type1, type_t *type2)
758 {
759         errorf(source_position, "%s, incompatible types: '%T' - '%T'",
760                msg, type1, type2);
761 }
762
763 /**
764  * Expect the the current token is the expected token.
765  * If not, generate an error, eat the current statement,
766  * and goto the end_error label.
767  */
768 #define expect(expected)                                  \
769         do {                                                  \
770                 if (UNLIKELY(token.type != (expected))) {         \
771                         parse_error_expected(NULL, (expected), NULL); \
772                         add_anchor_token(expected);                   \
773                         eat_until_anchor();                           \
774                         if (token.type == expected)                   \
775                                 next_token();                             \
776                         rem_anchor_token(expected);                   \
777                         goto end_error;                               \
778                 }                                                 \
779                 next_token();                                     \
780         } while (0)
781
782 static scope_t *scope_push(scope_t *new_scope)
783 {
784         if (current_scope != NULL) {
785                 new_scope->depth = current_scope->depth + 1;
786         }
787
788         scope_t *old_scope = current_scope;
789         current_scope      = new_scope;
790         return old_scope;
791 }
792
793 static void scope_pop(scope_t *old_scope)
794 {
795         current_scope = old_scope;
796 }
797
798 /**
799  * Search an entity by its symbol in a given namespace.
800  */
801 static entity_t *get_entity(const symbol_t *const symbol,
802                             namespace_tag_t namespc)
803 {
804         entity_t *entity = symbol->entity;
805         for (; entity != NULL; entity = entity->base.symbol_next) {
806                 if (entity->base.namespc == namespc)
807                         return entity;
808         }
809
810         return NULL;
811 }
812
813 /**
814  * pushs an entity on the environment stack and links the corresponding symbol
815  * it.
816  */
817 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
818 {
819         symbol_t           *symbol  = entity->base.symbol;
820         entity_namespace_t  namespc = entity->base.namespc;
821         assert(namespc != NAMESPACE_INVALID);
822
823         /* replace/add entity into entity list of the symbol */
824         entity_t **anchor;
825         entity_t  *iter;
826         for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
827                 iter = *anchor;
828                 if (iter == NULL)
829                         break;
830
831                 /* replace an entry? */
832                 if (iter->base.namespc == namespc) {
833                         entity->base.symbol_next = iter->base.symbol_next;
834                         break;
835                 }
836         }
837         *anchor = entity;
838
839         /* remember old declaration */
840         stack_entry_t entry;
841         entry.symbol     = symbol;
842         entry.old_entity = iter;
843         entry.namespc    = namespc;
844         ARR_APP1(stack_entry_t, *stack_ptr, entry);
845 }
846
847 /**
848  * Push an entity on the environment stack.
849  */
850 static void environment_push(entity_t *entity)
851 {
852         assert(entity->base.source_position.input_name != NULL);
853         assert(entity->base.parent_scope != NULL);
854         stack_push(&environment_stack, entity);
855 }
856
857 /**
858  * Push a declaration on the global label stack.
859  *
860  * @param declaration  the declaration
861  */
862 static void label_push(entity_t *label)
863 {
864         /* we abuse the parameters scope as parent for the labels */
865         label->base.parent_scope = &current_function->parameters;
866         stack_push(&label_stack, label);
867 }
868
869 /**
870  * pops symbols from the environment stack until @p new_top is the top element
871  */
872 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
873 {
874         stack_entry_t *stack = *stack_ptr;
875         size_t         top   = ARR_LEN(stack);
876         size_t         i;
877
878         assert(new_top <= top);
879         if (new_top == top)
880                 return;
881
882         for (i = top; i > new_top; --i) {
883                 stack_entry_t *entry = &stack[i - 1];
884
885                 entity_t           *old_entity = entry->old_entity;
886                 symbol_t           *symbol     = entry->symbol;
887                 entity_namespace_t  namespc    = entry->namespc;
888
889                 /* replace with old_entity/remove */
890                 entity_t **anchor;
891                 entity_t  *iter;
892                 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
893                         iter = *anchor;
894                         assert(iter != NULL);
895                         /* replace an entry? */
896                         if (iter->base.namespc == namespc)
897                                 break;
898                 }
899
900                 /* restore definition from outer scopes (if there was one) */
901                 if (old_entity != NULL) {
902                         old_entity->base.symbol_next = iter->base.symbol_next;
903                         *anchor                      = old_entity;
904                 } else {
905                         /* remove entry from list */
906                         *anchor = iter->base.symbol_next;
907                 }
908         }
909
910         ARR_SHRINKLEN(*stack_ptr, (int) new_top);
911 }
912
913 /**
914  * Pop all entries from the environment stack until the new_top
915  * is reached.
916  *
917  * @param new_top  the new stack top
918  */
919 static void environment_pop_to(size_t new_top)
920 {
921         stack_pop_to(&environment_stack, new_top);
922 }
923
924 /**
925  * Pop all entries from the global label stack until the new_top
926  * is reached.
927  *
928  * @param new_top  the new stack top
929  */
930 static void label_pop_to(size_t new_top)
931 {
932         stack_pop_to(&label_stack, new_top);
933 }
934
935 static int get_akind_rank(atomic_type_kind_t akind)
936 {
937         return (int) akind;
938 }
939
940 static int get_rank(const type_t *type)
941 {
942         assert(!is_typeref(type));
943         /* The C-standard allows promoting enums to int or unsigned int (see Â§ 7.2.2
944          * and esp. footnote 108). However we can't fold constants (yet), so we
945          * can't decide whether unsigned int is possible, while int always works.
946          * (unsigned int would be preferable when possible... for stuff like
947          *  struct { enum { ... } bla : 4; } ) */
948         if (type->kind == TYPE_ENUM)
949                 return get_akind_rank(ATOMIC_TYPE_INT);
950
951         assert(type->kind == TYPE_ATOMIC);
952         return get_akind_rank(type->atomic.akind);
953 }
954
955 static type_t *promote_integer(type_t *type)
956 {
957         if (type->kind == TYPE_BITFIELD)
958                 type = type->bitfield.base_type;
959
960         if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
961                 type = type_int;
962
963         return type;
964 }
965
966 /**
967  * Create a cast expression.
968  *
969  * @param expression  the expression to cast
970  * @param dest_type   the destination type
971  */
972 static expression_t *create_cast_expression(expression_t *expression,
973                                             type_t *dest_type)
974 {
975         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
976
977         cast->unary.value = expression;
978         cast->base.type   = dest_type;
979
980         return cast;
981 }
982
983 /**
984  * Check if a given expression represents the 0 pointer constant.
985  */
986 static bool is_null_pointer_constant(const expression_t *expression)
987 {
988         /* skip void* cast */
989         if (expression->kind == EXPR_UNARY_CAST
990                         || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
991                 expression = expression->unary.value;
992         }
993
994         /* TODO: not correct yet, should be any constant integer expression
995          * which evaluates to 0 */
996         if (expression->kind != EXPR_CONST)
997                 return false;
998
999         type_t *const type = skip_typeref(expression->base.type);
1000         if (!is_type_integer(type))
1001                 return false;
1002
1003         return expression->conste.v.int_value == 0;
1004 }
1005
1006 /**
1007  * Create an implicit cast expression.
1008  *
1009  * @param expression  the expression to cast
1010  * @param dest_type   the destination type
1011  */
1012 static expression_t *create_implicit_cast(expression_t *expression,
1013                                           type_t *dest_type)
1014 {
1015         type_t *const source_type = expression->base.type;
1016
1017         if (source_type == dest_type)
1018                 return expression;
1019
1020         return create_cast_expression(expression, dest_type);
1021 }
1022
1023 typedef enum assign_error_t {
1024         ASSIGN_SUCCESS,
1025         ASSIGN_ERROR_INCOMPATIBLE,
1026         ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1027         ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1028         ASSIGN_WARNING_POINTER_FROM_INT,
1029         ASSIGN_WARNING_INT_FROM_POINTER
1030 } assign_error_t;
1031
1032 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1033                                 const expression_t *const right,
1034                                 const char *context,
1035                                 const source_position_t *source_position)
1036 {
1037         type_t *const orig_type_right = right->base.type;
1038         type_t *const type_left       = skip_typeref(orig_type_left);
1039         type_t *const type_right      = skip_typeref(orig_type_right);
1040
1041         switch (error) {
1042         case ASSIGN_SUCCESS:
1043                 return;
1044         case ASSIGN_ERROR_INCOMPATIBLE:
1045                 errorf(source_position,
1046                        "destination type '%T' in %s is incompatible with type '%T'",
1047                        orig_type_left, context, orig_type_right);
1048                 return;
1049
1050         case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1051                 if (warning.other) {
1052                         type_t *points_to_left  = skip_typeref(type_left->pointer.points_to);
1053                         type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1054
1055                         /* the left type has all qualifiers from the right type */
1056                         unsigned missing_qualifiers
1057                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1058                         warningf(source_position,
1059                                         "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1060                                         orig_type_left, context, orig_type_right, missing_qualifiers);
1061                 }
1062                 return;
1063         }
1064
1065         case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1066                 if (warning.other) {
1067                         warningf(source_position,
1068                                         "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1069                                         orig_type_left, context, right, orig_type_right);
1070                 }
1071                 return;
1072
1073         case ASSIGN_WARNING_POINTER_FROM_INT:
1074                 if (warning.other) {
1075                         warningf(source_position,
1076                                         "%s makes pointer '%T' from integer '%T' without a cast",
1077                                         context, orig_type_left, orig_type_right);
1078                 }
1079                 return;
1080
1081         case ASSIGN_WARNING_INT_FROM_POINTER:
1082                 if (warning.other) {
1083                         warningf(source_position,
1084                                         "%s makes integer '%T' from pointer '%T' without a cast",
1085                                         context, orig_type_left, orig_type_right);
1086                 }
1087                 return;
1088
1089         default:
1090                 panic("invalid error value");
1091         }
1092 }
1093
1094 /** Implements the rules from Â§ 6.5.16.1 */
1095 static assign_error_t semantic_assign(type_t *orig_type_left,
1096                                       const expression_t *const right)
1097 {
1098         type_t *const orig_type_right = right->base.type;
1099         type_t *const type_left       = skip_typeref(orig_type_left);
1100         type_t *const type_right      = skip_typeref(orig_type_right);
1101
1102         if (is_type_pointer(type_left)) {
1103                 if (is_null_pointer_constant(right)) {
1104                         return ASSIGN_SUCCESS;
1105                 } else if (is_type_pointer(type_right)) {
1106                         type_t *points_to_left
1107                                 = skip_typeref(type_left->pointer.points_to);
1108                         type_t *points_to_right
1109                                 = skip_typeref(type_right->pointer.points_to);
1110                         assign_error_t res = ASSIGN_SUCCESS;
1111
1112                         /* the left type has all qualifiers from the right type */
1113                         unsigned missing_qualifiers
1114                                 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1115                         if (missing_qualifiers != 0) {
1116                                 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1117                         }
1118
1119                         points_to_left  = get_unqualified_type(points_to_left);
1120                         points_to_right = get_unqualified_type(points_to_right);
1121
1122                         if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1123                                 return res;
1124
1125                         if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1126                                 /* ISO/IEC 14882:1998(E) Â§C.1.2:6 */
1127                                 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1128                         }
1129
1130                         if (!types_compatible(points_to_left, points_to_right)) {
1131                                 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1132                         }
1133
1134                         return res;
1135                 } else if (is_type_integer(type_right)) {
1136                         return ASSIGN_WARNING_POINTER_FROM_INT;
1137                 }
1138         } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1139             (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1140                 && is_type_pointer(type_right))) {
1141                 return ASSIGN_SUCCESS;
1142         } else if ((is_type_compound(type_left)  && is_type_compound(type_right))
1143                         || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1144                 type_t *const unqual_type_left  = get_unqualified_type(type_left);
1145                 type_t *const unqual_type_right = get_unqualified_type(type_right);
1146                 if (types_compatible(unqual_type_left, unqual_type_right)) {
1147                         return ASSIGN_SUCCESS;
1148                 }
1149         } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1150                 return ASSIGN_WARNING_INT_FROM_POINTER;
1151         }
1152
1153         if (!is_type_valid(type_left) || !is_type_valid(type_right))
1154                 return ASSIGN_SUCCESS;
1155
1156         return ASSIGN_ERROR_INCOMPATIBLE;
1157 }
1158
1159 static expression_t *parse_constant_expression(void)
1160 {
1161         expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1162
1163         if (!is_constant_expression(result)) {
1164                 errorf(&result->base.source_position,
1165                        "expression '%E' is not constant", result);
1166         }
1167
1168         return result;
1169 }
1170
1171 static expression_t *parse_assignment_expression(void)
1172 {
1173         return parse_sub_expression(PREC_ASSIGNMENT);
1174 }
1175
1176 static string_t parse_string_literals(void)
1177 {
1178         assert(token.type == T_STRING_LITERAL);
1179         string_t result = token.v.string;
1180
1181         next_token();
1182
1183         while (token.type == T_STRING_LITERAL) {
1184                 result = concat_strings(&result, &token.v.string);
1185                 next_token();
1186         }
1187
1188         return result;
1189 }
1190
1191 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1192         [GNU_AK_CONST]                  = "const",
1193         [GNU_AK_VOLATILE]               = "volatile",
1194         [GNU_AK_CDECL]                  = "cdecl",
1195         [GNU_AK_STDCALL]                = "stdcall",
1196         [GNU_AK_FASTCALL]               = "fastcall",
1197         [GNU_AK_DEPRECATED]             = "deprecated",
1198         [GNU_AK_NOINLINE]               = "noinline",
1199         [GNU_AK_NORETURN]               = "noreturn",
1200         [GNU_AK_NAKED]                  = "naked",
1201         [GNU_AK_PURE]                   = "pure",
1202         [GNU_AK_ALWAYS_INLINE]          = "always_inline",
1203         [GNU_AK_MALLOC]                 = "malloc",
1204         [GNU_AK_WEAK]                   = "weak",
1205         [GNU_AK_CONSTRUCTOR]            = "constructor",
1206         [GNU_AK_DESTRUCTOR]             = "destructor",
1207         [GNU_AK_NOTHROW]                = "nothrow",
1208         [GNU_AK_TRANSPARENT_UNION]      = "transparent_union",
1209         [GNU_AK_COMMON]                 = "common",
1210         [GNU_AK_NOCOMMON]               = "nocommon",
1211         [GNU_AK_PACKED]                 = "packed",
1212         [GNU_AK_SHARED]                 = "shared",
1213         [GNU_AK_NOTSHARED]              = "notshared",
1214         [GNU_AK_USED]                   = "used",
1215         [GNU_AK_UNUSED]                 = "unused",
1216         [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1217         [GNU_AK_WARN_UNUSED_RESULT]     = "warn_unused_result",
1218         [GNU_AK_LONGCALL]               = "longcall",
1219         [GNU_AK_SHORTCALL]              = "shortcall",
1220         [GNU_AK_LONG_CALL]              = "long_call",
1221         [GNU_AK_SHORT_CALL]             = "short_call",
1222         [GNU_AK_FUNCTION_VECTOR]        = "function_vector",
1223         [GNU_AK_INTERRUPT]              = "interrupt",
1224         [GNU_AK_INTERRUPT_HANDLER]      = "interrupt_handler",
1225         [GNU_AK_NMI_HANDLER]            = "nmi_handler",
1226         [GNU_AK_NESTING]                = "nesting",
1227         [GNU_AK_NEAR]                   = "near",
1228         [GNU_AK_FAR]                    = "far",
1229         [GNU_AK_SIGNAL]                 = "signal",
1230         [GNU_AK_EIGTHBIT_DATA]          = "eightbit_data",
1231         [GNU_AK_TINY_DATA]              = "tiny_data",
1232         [GNU_AK_SAVEALL]                = "saveall",
1233         [GNU_AK_FLATTEN]                = "flatten",
1234         [GNU_AK_SSEREGPARM]             = "sseregparm",
1235         [GNU_AK_EXTERNALLY_VISIBLE]     = "externally_visible",
1236         [GNU_AK_RETURN_TWICE]           = "return_twice",
1237         [GNU_AK_MAY_ALIAS]              = "may_alias",
1238         [GNU_AK_MS_STRUCT]              = "ms_struct",
1239         [GNU_AK_GCC_STRUCT]             = "gcc_struct",
1240         [GNU_AK_DLLIMPORT]              = "dllimport",
1241         [GNU_AK_DLLEXPORT]              = "dllexport",
1242         [GNU_AK_ALIGNED]                = "aligned",
1243         [GNU_AK_ALIAS]                  = "alias",
1244         [GNU_AK_SECTION]                = "section",
1245         [GNU_AK_FORMAT]                 = "format",
1246         [GNU_AK_FORMAT_ARG]             = "format_arg",
1247         [GNU_AK_WEAKREF]                = "weakref",
1248         [GNU_AK_NONNULL]                = "nonnull",
1249         [GNU_AK_TLS_MODEL]              = "tls_model",
1250         [GNU_AK_VISIBILITY]             = "visibility",
1251         [GNU_AK_REGPARM]                = "regparm",
1252         [GNU_AK_MODE]                   = "mode",
1253         [GNU_AK_MODEL]                  = "model",
1254         [GNU_AK_TRAP_EXIT]              = "trap_exit",
1255         [GNU_AK_SP_SWITCH]              = "sp_switch",
1256         [GNU_AK_SENTINEL]               = "sentinel"
1257 };
1258
1259 /**
1260  * compare two string, ignoring double underscores on the second.
1261  */
1262 static int strcmp_underscore(const char *s1, const char *s2)
1263 {
1264         if (s2[0] == '_' && s2[1] == '_') {
1265                 size_t len2 = strlen(s2);
1266                 size_t len1 = strlen(s1);
1267                 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1268                         return strncmp(s1, s2+2, len2-4);
1269                 }
1270         }
1271
1272         return strcmp(s1, s2);
1273 }
1274
1275 /**
1276  * Allocate a new gnu temporal attribute.
1277  */
1278 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1279 {
1280         gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1281         attribute->kind            = kind;
1282         attribute->next            = NULL;
1283         attribute->invalid         = false;
1284         attribute->have_arguments  = false;
1285
1286         return attribute;
1287 }
1288
1289 /**
1290  * parse one constant expression argument.
1291  */
1292 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1293 {
1294         expression_t *expression;
1295         add_anchor_token(')');
1296         expression = parse_constant_expression();
1297         rem_anchor_token(')');
1298         expect(')');
1299         attribute->u.argument = fold_constant(expression);
1300         return;
1301 end_error:
1302         attribute->invalid = true;
1303 }
1304
1305 /**
1306  * parse a list of constant expressions arguments.
1307  */
1308 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1309 {
1310         argument_list_t **list = &attribute->u.arguments;
1311         argument_list_t  *entry;
1312         expression_t     *expression;
1313         add_anchor_token(')');
1314         add_anchor_token(',');
1315         while (true) {
1316                 expression = parse_constant_expression();
1317                 entry = obstack_alloc(&temp_obst, sizeof(entry));
1318                 entry->argument = fold_constant(expression);
1319                 entry->next     = NULL;
1320                 *list = entry;
1321                 list = &entry->next;
1322                 if (token.type != ',')
1323                         break;
1324                 next_token();
1325         }
1326         rem_anchor_token(',');
1327         rem_anchor_token(')');
1328         expect(')');
1329         return;
1330 end_error:
1331         attribute->invalid = true;
1332 }
1333
1334 /**
1335  * parse one string literal argument.
1336  */
1337 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1338                                            string_t *string)
1339 {
1340         add_anchor_token('(');
1341         if (token.type != T_STRING_LITERAL) {
1342                 parse_error_expected("while parsing attribute directive",
1343                                      T_STRING_LITERAL, NULL);
1344                 goto end_error;
1345         }
1346         *string = parse_string_literals();
1347         rem_anchor_token('(');
1348         expect(')');
1349         return;
1350 end_error:
1351         attribute->invalid = true;
1352 }
1353
1354 /**
1355  * parse one tls model.
1356  */
1357 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1358 {
1359         static const char *const tls_models[] = {
1360                 "global-dynamic",
1361                 "local-dynamic",
1362                 "initial-exec",
1363                 "local-exec"
1364         };
1365         string_t string = { NULL, 0 };
1366         parse_gnu_attribute_string_arg(attribute, &string);
1367         if (string.begin != NULL) {
1368                 for (size_t i = 0; i < 4; ++i) {
1369                         if (strcmp(tls_models[i], string.begin) == 0) {
1370                                 attribute->u.value = i;
1371                                 return;
1372                         }
1373                 }
1374                 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1375         }
1376         attribute->invalid = true;
1377 }
1378
1379 /**
1380  * parse one tls model.
1381  */
1382 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1383 {
1384         static const char *const visibilities[] = {
1385                 "default",
1386                 "protected",
1387                 "hidden",
1388                 "internal"
1389         };
1390         string_t string = { NULL, 0 };
1391         parse_gnu_attribute_string_arg(attribute, &string);
1392         if (string.begin != NULL) {
1393                 for (size_t i = 0; i < 4; ++i) {
1394                         if (strcmp(visibilities[i], string.begin) == 0) {
1395                                 attribute->u.value = i;
1396                                 return;
1397                         }
1398                 }
1399                 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1400         }
1401         attribute->invalid = true;
1402 }
1403
1404 /**
1405  * parse one (code) model.
1406  */
1407 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1408 {
1409         static const char *const visibilities[] = {
1410                 "small",
1411                 "medium",
1412                 "large"
1413         };
1414         string_t string = { NULL, 0 };
1415         parse_gnu_attribute_string_arg(attribute, &string);
1416         if (string.begin != NULL) {
1417                 for (int i = 0; i < 3; ++i) {
1418                         if (strcmp(visibilities[i], string.begin) == 0) {
1419                                 attribute->u.value = i;
1420                                 return;
1421                         }
1422                 }
1423                 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1424         }
1425         attribute->invalid = true;
1426 }
1427
1428 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1429 {
1430         /* TODO: find out what is allowed here... */
1431
1432         /* at least: byte, word, pointer, list of machine modes
1433          * __XXX___ is interpreted as XXX */
1434         add_anchor_token(')');
1435
1436         if (token.type != T_IDENTIFIER) {
1437                 expect(T_IDENTIFIER);
1438         }
1439
1440         /* This isn't really correct, the backend should provide a list of machine
1441          * specific modes (according to gcc philosophy that is...) */
1442         const char *symbol_str = token.v.symbol->string;
1443         if (strcmp_underscore("QI",   symbol_str) == 0 ||
1444             strcmp_underscore("byte", symbol_str) == 0) {
1445                 attribute->u.akind = ATOMIC_TYPE_CHAR;
1446         } else if (strcmp_underscore("HI", symbol_str) == 0) {
1447                 attribute->u.akind = ATOMIC_TYPE_SHORT;
1448         } else if (strcmp_underscore("SI",      symbol_str) == 0
1449                 || strcmp_underscore("word",    symbol_str) == 0
1450                 || strcmp_underscore("pointer", symbol_str) == 0) {
1451                 attribute->u.akind = ATOMIC_TYPE_INT;
1452         } else if (strcmp_underscore("DI", symbol_str) == 0) {
1453                 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1454         } else {
1455                 if (warning.other)
1456                         warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1457                 attribute->invalid = true;
1458         }
1459         next_token();
1460
1461         rem_anchor_token(')');
1462         expect(')');
1463         return;
1464 end_error:
1465         attribute->invalid = true;
1466 }
1467
1468 /**
1469  * parse one interrupt argument.
1470  */
1471 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1472 {
1473         static const char *const interrupts[] = {
1474                 "IRQ",
1475                 "FIQ",
1476                 "SWI",
1477                 "ABORT",
1478                 "UNDEF"
1479         };
1480         string_t string = { NULL, 0 };
1481         parse_gnu_attribute_string_arg(attribute, &string);
1482         if (string.begin != NULL) {
1483                 for (size_t i = 0; i < 5; ++i) {
1484                         if (strcmp(interrupts[i], string.begin) == 0) {
1485                                 attribute->u.value = i;
1486                                 return;
1487                         }
1488                 }
1489                 errorf(HERE, "'%s' is not an interrupt", string.begin);
1490         }
1491         attribute->invalid = true;
1492 }
1493
1494 /**
1495  * parse ( identifier, const expression, const expression )
1496  */
1497 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1498 {
1499         static const char *const format_names[] = {
1500                 "printf",
1501                 "scanf",
1502                 "strftime",
1503                 "strfmon"
1504         };
1505         int i;
1506
1507         if (token.type != T_IDENTIFIER) {
1508                 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1509                 goto end_error;
1510         }
1511         const char *name = token.v.symbol->string;
1512         for (i = 0; i < 4; ++i) {
1513                 if (strcmp_underscore(format_names[i], name) == 0)
1514                         break;
1515         }
1516         if (i >= 4) {
1517                 if (warning.attribute)
1518                         warningf(HERE, "'%s' is an unrecognized format function type", name);
1519         }
1520         next_token();
1521
1522         expect(',');
1523         add_anchor_token(')');
1524         add_anchor_token(',');
1525         parse_constant_expression();
1526         rem_anchor_token(',');
1527         rem_anchor_token(')');
1528
1529         expect(',');
1530         add_anchor_token(')');
1531         parse_constant_expression();
1532         rem_anchor_token(')');
1533         expect(')');
1534         return;
1535 end_error:
1536         attribute->u.value = true;
1537 }
1538
1539 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1540 {
1541         if (!attribute->have_arguments)
1542                 return;
1543
1544         /* should have no arguments */
1545         errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1546         eat_until_matching_token('(');
1547         /* we have already consumed '(', so we stop before ')', eat it */
1548         eat(')');
1549         attribute->invalid = true;
1550 }
1551
1552 /**
1553  * Parse one GNU attribute.
1554  *
1555  * Note that attribute names can be specified WITH or WITHOUT
1556  * double underscores, ie const or __const__.
1557  *
1558  * The following attributes are parsed without arguments
1559  *  const
1560  *  volatile
1561  *  cdecl
1562  *  stdcall
1563  *  fastcall
1564  *  deprecated
1565  *  noinline
1566  *  noreturn
1567  *  naked
1568  *  pure
1569  *  always_inline
1570  *  malloc
1571  *  weak
1572  *  constructor
1573  *  destructor
1574  *  nothrow
1575  *  transparent_union
1576  *  common
1577  *  nocommon
1578  *  packed
1579  *  shared
1580  *  notshared
1581  *  used
1582  *  unused
1583  *  no_instrument_function
1584  *  warn_unused_result
1585  *  longcall
1586  *  shortcall
1587  *  long_call
1588  *  short_call
1589  *  function_vector
1590  *  interrupt_handler
1591  *  nmi_handler
1592  *  nesting
1593  *  near
1594  *  far
1595  *  signal
1596  *  eightbit_data
1597  *  tiny_data
1598  *  saveall
1599  *  flatten
1600  *  sseregparm
1601  *  externally_visible
1602  *  return_twice
1603  *  may_alias
1604  *  ms_struct
1605  *  gcc_struct
1606  *  dllimport
1607  *  dllexport
1608  *
1609  * The following attributes are parsed with arguments
1610  *  aligned( const expression )
1611  *  alias( string literal )
1612  *  section( string literal )
1613  *  format( identifier, const expression, const expression )
1614  *  format_arg( const expression )
1615  *  tls_model( string literal )
1616  *  visibility( string literal )
1617  *  regparm( const expression )
1618  *  model( string leteral )
1619  *  trap_exit( const expression )
1620  *  sp_switch( string literal )
1621  *
1622  * The following attributes might have arguments
1623  *  weak_ref( string literal )
1624  *  non_null( const expression // ',' )
1625  *  interrupt( string literal )
1626  *  sentinel( constant expression )
1627  */
1628 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1629 {
1630         gnu_attribute_t *head      = *attributes;
1631         gnu_attribute_t *last      = *attributes;
1632         decl_modifiers_t modifiers = 0;
1633         gnu_attribute_t *attribute;
1634
1635         eat(T___attribute__);
1636         expect('(');
1637         expect('(');
1638
1639         if (token.type != ')') {
1640                 /* find the end of the list */
1641                 if (last != NULL) {
1642                         while (last->next != NULL)
1643                                 last = last->next;
1644                 }
1645
1646                 /* non-empty attribute list */
1647                 while (true) {
1648                         const char *name;
1649                         if (token.type == T_const) {
1650                                 name = "const";
1651                         } else if (token.type == T_volatile) {
1652                                 name = "volatile";
1653                         } else if (token.type == T_cdecl) {
1654                                 /* __attribute__((cdecl)), WITH ms mode */
1655                                 name = "cdecl";
1656                         } else if (token.type == T_IDENTIFIER) {
1657                                 const symbol_t *sym = token.v.symbol;
1658                                 name = sym->string;
1659                         } else {
1660                                 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1661                                 break;
1662                         }
1663
1664                         next_token();
1665
1666                         int i;
1667                         for (i = 0; i < GNU_AK_LAST; ++i) {
1668                                 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1669                                         break;
1670                         }
1671                         gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1672
1673                         attribute = NULL;
1674                         if (kind == GNU_AK_LAST) {
1675                                 if (warning.attribute)
1676                                         warningf(HERE, "'%s' attribute directive ignored", name);
1677
1678                                 /* skip possible arguments */
1679                                 if (token.type == '(') {
1680                                         eat_until_matching_token(')');
1681                                 }
1682                         } else {
1683                                 /* check for arguments */
1684                                 attribute = allocate_gnu_attribute(kind);
1685                                 if (token.type == '(') {
1686                                         next_token();
1687                                         if (token.type == ')') {
1688                                                 /* empty args are allowed */
1689                                                 next_token();
1690                                         } else
1691                                                 attribute->have_arguments = true;
1692                                 }
1693
1694                                 switch (kind) {
1695                                 case GNU_AK_VOLATILE:
1696                                 case GNU_AK_NAKED:
1697                                 case GNU_AK_MALLOC:
1698                                 case GNU_AK_WEAK:
1699                                 case GNU_AK_COMMON:
1700                                 case GNU_AK_NOCOMMON:
1701                                 case GNU_AK_SHARED:
1702                                 case GNU_AK_NOTSHARED:
1703                                 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1704                                 case GNU_AK_WARN_UNUSED_RESULT:
1705                                 case GNU_AK_LONGCALL:
1706                                 case GNU_AK_SHORTCALL:
1707                                 case GNU_AK_LONG_CALL:
1708                                 case GNU_AK_SHORT_CALL:
1709                                 case GNU_AK_FUNCTION_VECTOR:
1710                                 case GNU_AK_INTERRUPT_HANDLER:
1711                                 case GNU_AK_NMI_HANDLER:
1712                                 case GNU_AK_NESTING:
1713                                 case GNU_AK_NEAR:
1714                                 case GNU_AK_FAR:
1715                                 case GNU_AK_SIGNAL:
1716                                 case GNU_AK_EIGTHBIT_DATA:
1717                                 case GNU_AK_TINY_DATA:
1718                                 case GNU_AK_SAVEALL:
1719                                 case GNU_AK_FLATTEN:
1720                                 case GNU_AK_SSEREGPARM:
1721                                 case GNU_AK_EXTERNALLY_VISIBLE:
1722                                 case GNU_AK_RETURN_TWICE:
1723                                 case GNU_AK_MAY_ALIAS:
1724                                 case GNU_AK_MS_STRUCT:
1725                                 case GNU_AK_GCC_STRUCT:
1726                                         goto no_arg;
1727
1728                                 case GNU_AK_CDECL:             modifiers |= DM_CDECL;             goto no_arg;
1729                                 case GNU_AK_FASTCALL:          modifiers |= DM_FASTCALL;          goto no_arg;
1730                                 case GNU_AK_STDCALL:           modifiers |= DM_STDCALL;           goto no_arg;
1731                                 case GNU_AK_UNUSED:            modifiers |= DM_UNUSED;            goto no_arg;
1732                                 case GNU_AK_USED:              modifiers |= DM_USED;              goto no_arg;
1733                                 case GNU_AK_PURE:              modifiers |= DM_PURE;              goto no_arg;
1734                                 case GNU_AK_CONST:             modifiers |= DM_CONST;             goto no_arg;
1735                                 case GNU_AK_ALWAYS_INLINE:     modifiers |= DM_FORCEINLINE;       goto no_arg;
1736                                 case GNU_AK_DLLIMPORT:         modifiers |= DM_DLLIMPORT;         goto no_arg;
1737                                 case GNU_AK_DLLEXPORT:         modifiers |= DM_DLLEXPORT;         goto no_arg;
1738                                 case GNU_AK_PACKED:            modifiers |= DM_PACKED;            goto no_arg;
1739                                 case GNU_AK_NOINLINE:          modifiers |= DM_NOINLINE;          goto no_arg;
1740                                 case GNU_AK_NORETURN:          modifiers |= DM_NORETURN;          goto no_arg;
1741                                 case GNU_AK_NOTHROW:           modifiers |= DM_NOTHROW;           goto no_arg;
1742                                 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1743                                 case GNU_AK_CONSTRUCTOR:       modifiers |= DM_CONSTRUCTOR;       goto no_arg;
1744                                 case GNU_AK_DESTRUCTOR:        modifiers |= DM_DESTRUCTOR;        goto no_arg;
1745                                 case GNU_AK_DEPRECATED:        modifiers |= DM_DEPRECATED;        goto no_arg;
1746
1747                                 case GNU_AK_ALIGNED:
1748                                         /* __align__ may be used without an argument */
1749                                         if (attribute->have_arguments) {
1750                                                 parse_gnu_attribute_const_arg(attribute);
1751                                         }
1752                                         break;
1753
1754                                 case GNU_AK_FORMAT_ARG:
1755                                 case GNU_AK_REGPARM:
1756                                 case GNU_AK_TRAP_EXIT:
1757                                         if (!attribute->have_arguments) {
1758                                                 /* should have arguments */
1759                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1760                                                 attribute->invalid = true;
1761                                         } else
1762                                                 parse_gnu_attribute_const_arg(attribute);
1763                                         break;
1764                                 case GNU_AK_ALIAS:
1765                                 case GNU_AK_SECTION:
1766                                 case GNU_AK_SP_SWITCH:
1767                                         if (!attribute->have_arguments) {
1768                                                 /* should have arguments */
1769                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1770                                                 attribute->invalid = true;
1771                                         } else
1772                                                 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1773                                         break;
1774                                 case GNU_AK_FORMAT:
1775                                         if (!attribute->have_arguments) {
1776                                                 /* should have arguments */
1777                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1778                                                 attribute->invalid = true;
1779                                         } else
1780                                                 parse_gnu_attribute_format_args(attribute);
1781                                         break;
1782                                 case GNU_AK_WEAKREF:
1783                                         /* may have one string argument */
1784                                         if (attribute->have_arguments)
1785                                                 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1786                                         break;
1787                                 case GNU_AK_NONNULL:
1788                                         if (attribute->have_arguments)
1789                                                 parse_gnu_attribute_const_arg_list(attribute);
1790                                         break;
1791                                 case GNU_AK_TLS_MODEL:
1792                                         if (!attribute->have_arguments) {
1793                                                 /* should have arguments */
1794                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795                                         } else
1796                                                 parse_gnu_attribute_tls_model_arg(attribute);
1797                                         break;
1798                                 case GNU_AK_VISIBILITY:
1799                                         if (!attribute->have_arguments) {
1800                                                 /* should have arguments */
1801                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802                                         } else
1803                                                 parse_gnu_attribute_visibility_arg(attribute);
1804                                         break;
1805                                 case GNU_AK_MODEL:
1806                                         if (!attribute->have_arguments) {
1807                                                 /* should have arguments */
1808                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1809                                         } else {
1810                                                 parse_gnu_attribute_model_arg(attribute);
1811                                         }
1812                                         break;
1813                                 case GNU_AK_MODE:
1814                                         if (!attribute->have_arguments) {
1815                                                 /* should have arguments */
1816                                                 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1817                                         } else {
1818                                                 parse_gnu_attribute_mode_arg(attribute);
1819                                         }
1820                                         break;
1821                                 case GNU_AK_INTERRUPT:
1822                                         /* may have one string argument */
1823                                         if (attribute->have_arguments)
1824                                                 parse_gnu_attribute_interrupt_arg(attribute);
1825                                         break;
1826                                 case GNU_AK_SENTINEL:
1827                                         /* may have one string argument */
1828                                         if (attribute->have_arguments)
1829                                                 parse_gnu_attribute_const_arg(attribute);
1830                                         break;
1831                                 case GNU_AK_LAST:
1832                                         /* already handled */
1833                                         break;
1834
1835 no_arg:
1836                                         check_no_argument(attribute, name);
1837                                 }
1838                         }
1839                         if (attribute != NULL) {
1840                                 if (last != NULL) {
1841                                         last->next = attribute;
1842                                         last       = attribute;
1843                                 } else {
1844                                         head = last = attribute;
1845                                 }
1846                         }
1847
1848                         if (token.type != ',')
1849                                 break;
1850                         next_token();
1851                 }
1852         }
1853         expect(')');
1854         expect(')');
1855 end_error:
1856         *attributes = head;
1857
1858         return modifiers;
1859 }
1860
1861 /**
1862  * Parse GNU attributes.
1863  */
1864 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1865 {
1866         decl_modifiers_t modifiers = 0;
1867
1868         while (true) {
1869                 switch (token.type) {
1870                 case T___attribute__:
1871                         modifiers |= parse_gnu_attribute(attributes);
1872                         continue;
1873
1874                 case T_asm:
1875                         next_token();
1876                         expect('(');
1877                         if (token.type != T_STRING_LITERAL) {
1878                                 parse_error_expected("while parsing assembler attribute",
1879                                                      T_STRING_LITERAL, NULL);
1880                                 eat_until_matching_token('(');
1881                                 break;
1882                         } else {
1883                                 parse_string_literals();
1884                         }
1885                         expect(')');
1886                         continue;
1887
1888                 case T_cdecl:     modifiers |= DM_CDECL;    break;
1889                 case T__fastcall: modifiers |= DM_FASTCALL; break;
1890                 case T__stdcall:  modifiers |= DM_STDCALL;  break;
1891
1892                 case T___thiscall:
1893                         /* TODO record modifier */
1894                         if (warning.other)
1895                                 warningf(HERE, "Ignoring declaration modifier '%K'", &token);
1896                         break;
1897
1898 end_error:
1899                 default: return modifiers;
1900                 }
1901
1902                 next_token();
1903         }
1904 }
1905
1906 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1907
1908 static entity_t *determine_lhs_ent(expression_t *const expr,
1909                                    entity_t *lhs_ent)
1910 {
1911         switch (expr->kind) {
1912                 case EXPR_REFERENCE: {
1913                         entity_t *const entity = expr->reference.entity;
1914                         /* we should only find variables as lvalues... */
1915                         if (entity->base.kind != ENTITY_VARIABLE
1916                                         && entity->base.kind != ENTITY_PARAMETER)
1917                                 return NULL;
1918
1919                         return entity;
1920                 }
1921
1922                 case EXPR_ARRAY_ACCESS: {
1923                         expression_t *const ref = expr->array_access.array_ref;
1924                         entity_t     *      ent = NULL;
1925                         if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1926                                 ent     = determine_lhs_ent(ref, lhs_ent);
1927                                 lhs_ent = ent;
1928                         } else {
1929                                 mark_vars_read(expr->select.compound, lhs_ent);
1930                         }
1931                         mark_vars_read(expr->array_access.index, lhs_ent);
1932                         return ent;
1933                 }
1934
1935                 case EXPR_SELECT: {
1936                         if (is_type_compound(skip_typeref(expr->base.type))) {
1937                                 return determine_lhs_ent(expr->select.compound, lhs_ent);
1938                         } else {
1939                                 mark_vars_read(expr->select.compound, lhs_ent);
1940                                 return NULL;
1941                         }
1942                 }
1943
1944                 case EXPR_UNARY_DEREFERENCE: {
1945                         expression_t *const val = expr->unary.value;
1946                         if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1947                                 /* *&x is a NOP */
1948                                 return determine_lhs_ent(val->unary.value, lhs_ent);
1949                         } else {
1950                                 mark_vars_read(val, NULL);
1951                                 return NULL;
1952                         }
1953                 }
1954
1955                 default:
1956                         mark_vars_read(expr, NULL);
1957                         return NULL;
1958         }
1959 }
1960
1961 #define ENT_ANY ((entity_t*)-1)
1962
1963 /**
1964  * Mark declarations, which are read.  This is used to detect variables, which
1965  * are never read.
1966  * Example:
1967  * x = x + 1;
1968  *   x is not marked as "read", because it is only read to calculate its own new
1969  *   value.
1970  *
1971  * x += y; y += x;
1972  *   x and y are not detected as "not read", because multiple variables are
1973  *   involved.
1974  */
1975 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1976 {
1977         switch (expr->kind) {
1978                 case EXPR_REFERENCE: {
1979                         entity_t *const entity = expr->reference.entity;
1980                         if (entity->kind != ENTITY_VARIABLE
1981                                         && entity->kind != ENTITY_PARAMETER)
1982                                 return;
1983
1984                         if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1985                                 if (entity->kind == ENTITY_VARIABLE) {
1986                                         entity->variable.read = true;
1987                                 } else {
1988                                         entity->parameter.read = true;
1989                                 }
1990                         }
1991                         return;
1992                 }
1993
1994                 case EXPR_CALL:
1995                         // TODO respect pure/const
1996                         mark_vars_read(expr->call.function, NULL);
1997                         for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1998                                 mark_vars_read(arg->expression, NULL);
1999                         }
2000                         return;
2001
2002                 case EXPR_CONDITIONAL:
2003                         // TODO lhs_decl should depend on whether true/false have an effect
2004                         mark_vars_read(expr->conditional.condition, NULL);
2005                         if (expr->conditional.true_expression != NULL)
2006                                 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2007                         mark_vars_read(expr->conditional.false_expression, lhs_ent);
2008                         return;
2009
2010                 case EXPR_SELECT:
2011                         if (lhs_ent == ENT_ANY
2012                                         && !is_type_compound(skip_typeref(expr->base.type)))
2013                                 lhs_ent = NULL;
2014                         mark_vars_read(expr->select.compound, lhs_ent);
2015                         return;
2016
2017                 case EXPR_ARRAY_ACCESS: {
2018                         expression_t *const ref = expr->array_access.array_ref;
2019                         mark_vars_read(ref, lhs_ent);
2020                         lhs_ent = determine_lhs_ent(ref, lhs_ent);
2021                         mark_vars_read(expr->array_access.index, lhs_ent);
2022                         return;
2023                 }
2024
2025                 case EXPR_VA_ARG:
2026                         mark_vars_read(expr->va_arge.ap, lhs_ent);
2027                         return;
2028
2029                 case EXPR_UNARY_CAST:
2030                         /* Special case: Use void cast to mark a variable as "read" */
2031                         if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2032                                 lhs_ent = NULL;
2033                         goto unary;
2034
2035
2036                 case EXPR_UNARY_THROW:
2037                         if (expr->unary.value == NULL)
2038                                 return;
2039                         /* FALLTHROUGH */
2040                 case EXPR_UNARY_DEREFERENCE:
2041                 case EXPR_UNARY_DELETE:
2042                 case EXPR_UNARY_DELETE_ARRAY:
2043                         if (lhs_ent == ENT_ANY)
2044                                 lhs_ent = NULL;
2045                         goto unary;
2046
2047                 case EXPR_UNARY_NEGATE:
2048                 case EXPR_UNARY_PLUS:
2049                 case EXPR_UNARY_BITWISE_NEGATE:
2050                 case EXPR_UNARY_NOT:
2051                 case EXPR_UNARY_TAKE_ADDRESS:
2052                 case EXPR_UNARY_POSTFIX_INCREMENT:
2053                 case EXPR_UNARY_POSTFIX_DECREMENT:
2054                 case EXPR_UNARY_PREFIX_INCREMENT:
2055                 case EXPR_UNARY_PREFIX_DECREMENT:
2056                 case EXPR_UNARY_CAST_IMPLICIT:
2057                 case EXPR_UNARY_ASSUME:
2058 unary:
2059                         mark_vars_read(expr->unary.value, lhs_ent);
2060                         return;
2061
2062                 case EXPR_BINARY_ADD:
2063                 case EXPR_BINARY_SUB:
2064                 case EXPR_BINARY_MUL:
2065                 case EXPR_BINARY_DIV:
2066                 case EXPR_BINARY_MOD:
2067                 case EXPR_BINARY_EQUAL:
2068                 case EXPR_BINARY_NOTEQUAL:
2069                 case EXPR_BINARY_LESS:
2070                 case EXPR_BINARY_LESSEQUAL:
2071                 case EXPR_BINARY_GREATER:
2072                 case EXPR_BINARY_GREATEREQUAL:
2073                 case EXPR_BINARY_BITWISE_AND:
2074                 case EXPR_BINARY_BITWISE_OR:
2075                 case EXPR_BINARY_BITWISE_XOR:
2076                 case EXPR_BINARY_LOGICAL_AND:
2077                 case EXPR_BINARY_LOGICAL_OR:
2078                 case EXPR_BINARY_SHIFTLEFT:
2079                 case EXPR_BINARY_SHIFTRIGHT:
2080                 case EXPR_BINARY_COMMA:
2081                 case EXPR_BINARY_ISGREATER:
2082                 case EXPR_BINARY_ISGREATEREQUAL:
2083                 case EXPR_BINARY_ISLESS:
2084                 case EXPR_BINARY_ISLESSEQUAL:
2085                 case EXPR_BINARY_ISLESSGREATER:
2086                 case EXPR_BINARY_ISUNORDERED:
2087                         mark_vars_read(expr->binary.left,  lhs_ent);
2088                         mark_vars_read(expr->binary.right, lhs_ent);
2089                         return;
2090
2091                 case EXPR_BINARY_ASSIGN:
2092                 case EXPR_BINARY_MUL_ASSIGN:
2093                 case EXPR_BINARY_DIV_ASSIGN:
2094                 case EXPR_BINARY_MOD_ASSIGN:
2095                 case EXPR_BINARY_ADD_ASSIGN:
2096                 case EXPR_BINARY_SUB_ASSIGN:
2097                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2098                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2099                 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2100                 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2101                 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2102                         if (lhs_ent == ENT_ANY)
2103                                 lhs_ent = NULL;
2104                         lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2105                         mark_vars_read(expr->binary.right, lhs_ent);
2106                         return;
2107                 }
2108
2109                 case EXPR_VA_START:
2110                         determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2111                         return;
2112
2113                 case EXPR_UNKNOWN:
2114                 case EXPR_INVALID:
2115                 case EXPR_CONST:
2116                 case EXPR_CHARACTER_CONSTANT:
2117                 case EXPR_WIDE_CHARACTER_CONSTANT:
2118                 case EXPR_STRING_LITERAL:
2119                 case EXPR_WIDE_STRING_LITERAL:
2120                 case EXPR_COMPOUND_LITERAL: // TODO init?
2121                 case EXPR_SIZEOF:
2122                 case EXPR_CLASSIFY_TYPE:
2123                 case EXPR_ALIGNOF:
2124                 case EXPR_FUNCNAME:
2125                 case EXPR_BUILTIN_SYMBOL:
2126                 case EXPR_BUILTIN_CONSTANT_P:
2127                 case EXPR_BUILTIN_PREFETCH:
2128                 case EXPR_OFFSETOF:
2129                 case EXPR_STATEMENT: // TODO
2130                 case EXPR_LABEL_ADDRESS:
2131                 case EXPR_BINARY_BUILTIN_EXPECT:
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         assert(symbol != NULL);
4898         entity_t *previous_entity = get_entity(symbol, namespc);
4899         /* pushing the same entity twice will break the stack structure */
4900         assert(previous_entity != entity);
4901
4902         if (entity->kind == ENTITY_FUNCTION) {
4903                 type_t *const orig_type = entity->declaration.type;
4904                 type_t *const type      = skip_typeref(orig_type);
4905
4906                 assert(is_type_function(type));
4907                 if (type->function.unspecified_parameters &&
4908                                 warning.strict_prototypes &&
4909                                 previous_entity == NULL) {
4910                         warningf(pos, "function declaration '%#T' is not a prototype",
4911                                          orig_type, symbol);
4912                 }
4913
4914                 if (warning.main && current_scope == file_scope
4915                                 && is_sym_main(symbol)) {
4916                         check_type_of_main(entity);
4917                 }
4918         }
4919
4920         if (is_declaration(entity)) {
4921                 if (warning.nested_externs
4922                                 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4923                                 && current_scope != file_scope) {
4924                         warningf(pos, "nested extern declaration of '%#T'",
4925                                  entity->declaration.type, symbol);
4926                 }
4927         }
4928
4929         if (previous_entity != NULL
4930             && previous_entity->base.parent_scope == &current_function->parameters
4931                 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4932
4933                 assert(previous_entity->kind == ENTITY_PARAMETER);
4934                 errorf(pos,
4935                        "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4936                        entity->declaration.type, symbol,
4937                            previous_entity->declaration.type, symbol,
4938                            &previous_entity->base.source_position);
4939                 goto finish;
4940         }
4941
4942         if (previous_entity != NULL
4943                         && previous_entity->base.parent_scope == current_scope) {
4944
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,
4952                                    "redeclaration of enum entry '%Y' (declared %P)",
4953                                    symbol, &previous_entity->base.source_position);
4954                         goto finish;
4955                 }
4956                 if (previous_entity->kind == ENTITY_TYPEDEF) {
4957                         /* TODO: C++ allows this for exactly the same type */
4958                         errorf(pos,
4959                                "redefinition of typedef '%Y' (declared %P)",
4960                                symbol, &previous_entity->base.source_position);
4961                         goto finish;
4962                 }
4963
4964                 /* at this point we should have only VARIABLES or FUNCTIONS */
4965                 assert(is_declaration(previous_entity) && is_declaration(entity));
4966
4967                 /* can happen for K&R style declarations */
4968                 if (previous_entity->kind == ENTITY_PARAMETER
4969                                 && previous_entity->declaration.type == NULL
4970                                 && entity->kind == ENTITY_PARAMETER) {
4971                         previous_entity->declaration.type = entity->declaration.type;
4972                         previous_entity->declaration.storage_class
4973                                 = entity->declaration.storage_class;
4974                         previous_entity->declaration.declared_storage_class
4975                                 = entity->declaration.declared_storage_class;
4976                         previous_entity->declaration.modifiers
4977                                 = entity->declaration.modifiers;
4978                         previous_entity->declaration.deprecated_string
4979                                 = entity->declaration.deprecated_string;
4980                 }
4981                 assert(entity->declaration.type != NULL);
4982
4983                 declaration_t *const previous_declaration
4984                         = &previous_entity->declaration;
4985                 declaration_t *const declaration = &entity->declaration;
4986                 type_t *const orig_type = entity->declaration.type;
4987                 type_t *const type      = skip_typeref(orig_type);
4988
4989                 type_t *prev_type       = skip_typeref(previous_declaration->type);
4990
4991                 if (!types_compatible(type, prev_type)) {
4992                         errorf(pos,
4993                                    "declaration '%#T' is incompatible with '%#T' (declared %P)",
4994                                    orig_type, symbol, previous_declaration->type, symbol,
4995                                    &previous_entity->base.source_position);
4996                 } else {
4997                         unsigned old_storage_class = previous_declaration->storage_class;
4998                         if (warning.redundant_decls     && is_definition
4999                                 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
5000                                 && !(previous_declaration->modifiers & DM_USED)
5001                                 && !previous_declaration->used) {
5002                                 warningf(&previous_entity->base.source_position,
5003                                          "unnecessary static forward declaration for '%#T'",
5004                                          previous_declaration->type, symbol);
5005                         }
5006
5007                         unsigned new_storage_class = declaration->storage_class;
5008                         if (is_type_incomplete(prev_type)) {
5009                                 previous_declaration->type = type;
5010                                 prev_type                  = type;
5011                         }
5012
5013                         /* pretend no storage class means extern for function
5014                          * declarations (except if the previous declaration is neither
5015                          * none nor extern) */
5016                         if (entity->kind == ENTITY_FUNCTION) {
5017                                 if (prev_type->function.unspecified_parameters) {
5018                                         previous_declaration->type = type;
5019                                         prev_type                  = type;
5020                                 }
5021
5022                                 switch (old_storage_class) {
5023                                 case STORAGE_CLASS_NONE:
5024                                         old_storage_class = STORAGE_CLASS_EXTERN;
5025                                         /* FALLTHROUGH */
5026
5027                                 case STORAGE_CLASS_EXTERN:
5028                                         if (is_definition) {
5029                                                 if (warning.missing_prototypes &&
5030                                                     prev_type->function.unspecified_parameters &&
5031                                                     !is_sym_main(symbol)) {
5032                                                         warningf(pos, "no previous prototype for '%#T'",
5033                                                                          orig_type, symbol);
5034                                                 }
5035                                         } else if (new_storage_class == STORAGE_CLASS_NONE) {
5036                                                 new_storage_class = STORAGE_CLASS_EXTERN;
5037                                         }
5038                                         break;
5039
5040                                 default:
5041                                         break;
5042                                 }
5043                         }
5044
5045                         if (old_storage_class == STORAGE_CLASS_EXTERN &&
5046                                         new_storage_class == STORAGE_CLASS_EXTERN) {
5047 warn_redundant_declaration:
5048                                 if (!is_definition           &&
5049                                     warning.redundant_decls  &&
5050                                     is_type_valid(prev_type) &&
5051                                     strcmp(previous_entity->base.source_position.input_name,
5052                                            "<builtin>") != 0) {
5053                                         warningf(pos,
5054                                                  "redundant declaration for '%Y' (declared %P)",
5055                                                  symbol, &previous_entity->base.source_position);
5056                                 }
5057                         } else if (current_function == NULL) {
5058                                 if (old_storage_class != STORAGE_CLASS_STATIC &&
5059                                     new_storage_class == STORAGE_CLASS_STATIC) {
5060                                         errorf(pos,
5061                                                "static declaration of '%Y' follows non-static declaration (declared %P)",
5062                                                symbol, &previous_entity->base.source_position);
5063                                 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5064                                         previous_declaration->storage_class          = STORAGE_CLASS_NONE;
5065                                         previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5066                                 } else {
5067                                         /* ISO/IEC 14882:1998(E) Â§C.1.2:1 */
5068                                         if (c_mode & _CXX)
5069                                                 goto error_redeclaration;
5070                                         goto warn_redundant_declaration;
5071                                 }
5072                         } else if (is_type_valid(prev_type)) {
5073                                 if (old_storage_class == new_storage_class) {
5074 error_redeclaration:
5075                                         errorf(pos, "redeclaration of '%Y' (declared %P)",
5076                                                symbol, &previous_entity->base.source_position);
5077                                 } else {
5078                                         errorf(pos,
5079                                                "redeclaration of '%Y' with different linkage (declared %P)",
5080                                                symbol, &previous_entity->base.source_position);
5081                                 }
5082                         }
5083                 }
5084
5085                 previous_declaration->modifiers |= declaration->modifiers;
5086                 if (entity->kind == ENTITY_FUNCTION) {
5087                         previous_entity->function.is_inline |= entity->function.is_inline;
5088                 }
5089                 return previous_entity;
5090         }
5091
5092         if (entity->kind == ENTITY_FUNCTION) {
5093                 if (is_definition &&
5094                                 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5095                         if (warning.missing_prototypes && !is_sym_main(symbol)) {
5096                                 warningf(pos, "no previous prototype for '%#T'",
5097                                          entity->declaration.type, symbol);
5098                         } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5099                                 warningf(pos, "no previous declaration for '%#T'",
5100                                          entity->declaration.type, symbol);
5101                         }
5102                 }
5103         } else if (warning.missing_declarations
5104                         && entity->kind == ENTITY_VARIABLE
5105                         && current_scope == file_scope) {
5106                 declaration_t *declaration = &entity->declaration;
5107                 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5108                         warningf(pos, "no previous declaration for '%#T'",
5109                                  declaration->type, symbol);
5110                 }
5111         }
5112
5113 finish:
5114         assert(entity->base.parent_scope == NULL);
5115         assert(current_scope != NULL);
5116
5117         entity->base.parent_scope = current_scope;
5118         entity->base.namespc      = NAMESPACE_NORMAL;
5119         environment_push(entity);
5120         append_entity(current_scope, entity);
5121
5122         return entity;
5123 }
5124
5125 static void parser_error_multiple_definition(entity_t *entity,
5126                 const source_position_t *source_position)
5127 {
5128         errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5129                entity->base.symbol, &entity->base.source_position);
5130 }
5131
5132 static bool is_declaration_specifier(const token_t *token,
5133                                      bool only_specifiers_qualifiers)
5134 {
5135         switch (token->type) {
5136                 TYPE_SPECIFIERS
5137                 TYPE_QUALIFIERS
5138                         return true;
5139                 case T_IDENTIFIER:
5140                         return is_typedef_symbol(token->v.symbol);
5141
5142                 case T___extension__:
5143                 STORAGE_CLASSES
5144                         return !only_specifiers_qualifiers;
5145
5146                 default:
5147                         return false;
5148         }
5149 }
5150
5151 static void parse_init_declarator_rest(entity_t *entity)
5152 {
5153         assert(is_declaration(entity));
5154         declaration_t *const declaration = &entity->declaration;
5155
5156         eat('=');
5157
5158         type_t *orig_type = declaration->type;
5159         type_t *type      = skip_typeref(orig_type);
5160
5161         if (entity->kind == ENTITY_VARIABLE
5162                         && entity->variable.initializer != NULL) {
5163                 parser_error_multiple_definition(entity, HERE);
5164         }
5165
5166         bool must_be_constant = false;
5167         if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5168             entity->base.parent_scope  == file_scope) {
5169                 must_be_constant = true;
5170         }
5171
5172         if (is_type_function(type)) {
5173                 errorf(&entity->base.source_position,
5174                        "function '%#T' is initialized like a variable",
5175                        orig_type, entity->base.symbol);
5176                 orig_type = type_error_type;
5177         }
5178
5179         parse_initializer_env_t env;
5180         env.type             = orig_type;
5181         env.must_be_constant = must_be_constant;
5182         env.entity           = entity;
5183         current_init_decl    = entity;
5184
5185         initializer_t *initializer = parse_initializer(&env);
5186         current_init_decl = NULL;
5187
5188         if (entity->kind == ENTITY_VARIABLE) {
5189                 /* Â§ 6.7.5 (22)  array initializers for arrays with unknown size
5190                  * determine the array type size */
5191                 declaration->type            = env.type;
5192                 entity->variable.initializer = initializer;
5193         }
5194 }
5195
5196 /* parse rest of a declaration without any declarator */
5197 static void parse_anonymous_declaration_rest(
5198                 const declaration_specifiers_t *specifiers)
5199 {
5200         eat(';');
5201         anonymous_entity = NULL;
5202
5203         if (warning.other) {
5204                 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5205                                 specifiers->thread_local) {
5206                         warningf(&specifiers->source_position,
5207                                  "useless storage class in empty declaration");
5208                 }
5209
5210                 type_t *type = specifiers->type;
5211                 switch (type->kind) {
5212                         case TYPE_COMPOUND_STRUCT:
5213                         case TYPE_COMPOUND_UNION: {
5214                                 if (type->compound.compound->base.symbol == NULL) {
5215                                         warningf(&specifiers->source_position,
5216                                                  "unnamed struct/union that defines no instances");
5217                                 }
5218                                 break;
5219                         }
5220
5221                         case TYPE_ENUM:
5222                                 break;
5223
5224                         default:
5225                                 warningf(&specifiers->source_position, "empty declaration");
5226                                 break;
5227                 }
5228         }
5229 }
5230
5231 static void check_variable_type_complete(entity_t *ent)
5232 {
5233         if (ent->kind != ENTITY_VARIABLE)
5234                 return;
5235
5236         /* Â§6.7:7  If an identifier for an object is declared with no linkage, the
5237          *         type for the object shall be complete [...] */
5238         declaration_t *decl = &ent->declaration;
5239         if (decl->storage_class != STORAGE_CLASS_NONE)
5240                 return;
5241
5242         type_t *type = decl->type;
5243         if (!is_type_incomplete(skip_typeref(type)))
5244                 return;
5245
5246         errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5247                         type, ent->base.symbol);
5248 }
5249
5250
5251 static void parse_declaration_rest(entity_t *ndeclaration,
5252                 const declaration_specifiers_t *specifiers,
5253                 parsed_declaration_func         finished_declaration,
5254                 declarator_flags_t              flags)
5255 {
5256         add_anchor_token(';');
5257         add_anchor_token(',');
5258         while (true) {
5259                 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5260
5261                 if (token.type == '=') {
5262                         parse_init_declarator_rest(entity);
5263                 } else if (entity->kind == ENTITY_VARIABLE) {
5264                         /* ISO/IEC 14882:1998(E) Â§8.5.3:3  The initializer can be omitted
5265                          * [...] where the extern specifier is explicitly used. */
5266                         declaration_t *decl = &entity->declaration;
5267                         if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5268                                 type_t *type = decl->type;
5269                                 if (is_type_reference(skip_typeref(type))) {
5270                                         errorf(&entity->base.source_position,
5271                                                         "reference '%#T' must be initialized",
5272                                                         type, entity->base.symbol);
5273                                 }
5274                         }
5275                 }
5276
5277                 check_variable_type_complete(entity);
5278
5279                 if (token.type != ',')
5280                         break;
5281                 eat(',');
5282
5283                 add_anchor_token('=');
5284                 ndeclaration = parse_declarator(specifiers, flags);
5285                 rem_anchor_token('=');
5286         }
5287         expect(';');
5288
5289 end_error:
5290         anonymous_entity = NULL;
5291         rem_anchor_token(';');
5292         rem_anchor_token(',');
5293 }
5294
5295 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5296 {
5297         symbol_t *symbol = entity->base.symbol;
5298         if (symbol == NULL) {
5299                 errorf(HERE, "anonymous declaration not valid as function parameter");
5300                 return entity;
5301         }
5302
5303         assert(entity->base.namespc == NAMESPACE_NORMAL);
5304         entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5305         if (previous_entity == NULL
5306                         || previous_entity->base.parent_scope != current_scope) {
5307                 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5308                        symbol);
5309                 return entity;
5310         }
5311
5312         if (is_definition) {
5313                 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5314         }
5315
5316         return record_entity(entity, false);
5317 }
5318
5319 static void parse_declaration(parsed_declaration_func finished_declaration,
5320                               declarator_flags_t      flags)
5321 {
5322         declaration_specifiers_t specifiers;
5323         memset(&specifiers, 0, sizeof(specifiers));
5324
5325         add_anchor_token(';');
5326         parse_declaration_specifiers(&specifiers);
5327         rem_anchor_token(';');
5328
5329         if (token.type == ';') {
5330                 parse_anonymous_declaration_rest(&specifiers);
5331         } else {
5332                 entity_t *entity = parse_declarator(&specifiers, flags);
5333                 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5334         }
5335 }
5336
5337 static type_t *get_default_promoted_type(type_t *orig_type)
5338 {
5339         type_t *result = orig_type;
5340
5341         type_t *type = skip_typeref(orig_type);
5342         if (is_type_integer(type)) {
5343                 result = promote_integer(type);
5344         } else if (type == type_float) {
5345                 result = type_double;
5346         }
5347
5348         return result;
5349 }
5350
5351 static void parse_kr_declaration_list(entity_t *entity)
5352 {
5353         if (entity->kind != ENTITY_FUNCTION)
5354                 return;
5355
5356         type_t *type = skip_typeref(entity->declaration.type);
5357         assert(is_type_function(type));
5358         if (!type->function.kr_style_parameters)
5359                 return;
5360
5361
5362         add_anchor_token('{');
5363
5364         /* push function parameters */
5365         size_t const  top       = environment_top();
5366         scope_t      *old_scope = scope_push(&entity->function.parameters);
5367
5368         entity_t *parameter = entity->function.parameters.entities;
5369         for ( ; parameter != NULL; parameter = parameter->base.next) {
5370                 assert(parameter->base.parent_scope == NULL);
5371                 parameter->base.parent_scope = current_scope;
5372                 environment_push(parameter);
5373         }
5374
5375         /* parse declaration list */
5376         for (;;) {
5377                 switch (token.type) {
5378                         DECLARATION_START
5379                         case T___extension__:
5380                         /* This covers symbols, which are no type, too, and results in
5381                          * better error messages.  The typical cases are misspelled type
5382                          * names and missing includes. */
5383                         case T_IDENTIFIER:
5384                                 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5385                                 break;
5386                         default:
5387                                 goto decl_list_end;
5388                 }
5389         }
5390 decl_list_end:
5391
5392         /* pop function parameters */
5393         assert(current_scope == &entity->function.parameters);
5394         scope_pop(old_scope);
5395         environment_pop_to(top);
5396
5397         /* update function type */
5398         type_t *new_type = duplicate_type(type);
5399
5400         function_parameter_t *parameters     = NULL;
5401         function_parameter_t *last_parameter = NULL;
5402
5403         parameter = entity->function.parameters.entities;
5404         for (; parameter != NULL; parameter = parameter->base.next) {
5405                 type_t *parameter_type = parameter->declaration.type;
5406                 if (parameter_type == NULL) {
5407                         if (strict_mode) {
5408                                 errorf(HERE, "no type specified for function parameter '%Y'",
5409                                        parameter->base.symbol);
5410                         } else {
5411                                 if (warning.implicit_int) {
5412                                         warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5413                                                  parameter->base.symbol);
5414                                 }
5415                                 parameter_type              = type_int;
5416                                 parameter->declaration.type = parameter_type;
5417                         }
5418                 }
5419
5420                 semantic_parameter_incomplete(parameter);
5421                 parameter_type = parameter->declaration.type;
5422
5423                 /*
5424                  * we need the default promoted types for the function type
5425                  */
5426                 parameter_type = get_default_promoted_type(parameter_type);
5427
5428                 function_parameter_t *function_parameter
5429                         = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5430                 memset(function_parameter, 0, sizeof(function_parameter[0]));
5431
5432                 function_parameter->type = parameter_type;
5433                 if (last_parameter != NULL) {
5434                         last_parameter->next = function_parameter;
5435                 } else {
5436                         parameters = function_parameter;
5437                 }
5438                 last_parameter = function_parameter;
5439         }
5440
5441         /* Â§ 6.9.1.7: A K&R style parameter list does NOT act as a function
5442          * prototype */
5443         new_type->function.parameters             = parameters;
5444         new_type->function.unspecified_parameters = true;
5445
5446         type = typehash_insert(new_type);
5447         if (type != new_type) {
5448                 obstack_free(type_obst, new_type);
5449         }
5450
5451         entity->declaration.type = type;
5452
5453         rem_anchor_token('{');
5454 }
5455
5456 static bool first_err = true;
5457
5458 /**
5459  * When called with first_err set, prints the name of the current function,
5460  * else does noting.
5461  */
5462 static void print_in_function(void)
5463 {
5464         if (first_err) {
5465                 first_err = false;
5466                 diagnosticf("%s: In function '%Y':\n",
5467                             current_function->base.base.source_position.input_name,
5468                             current_function->base.base.symbol);
5469         }
5470 }
5471
5472 /**
5473  * Check if all labels are defined in the current function.
5474  * Check if all labels are used in the current function.
5475  */
5476 static void check_labels(void)
5477 {
5478         for (const goto_statement_t *goto_statement = goto_first;
5479             goto_statement != NULL;
5480             goto_statement = goto_statement->next) {
5481                 /* skip computed gotos */
5482                 if (goto_statement->expression != NULL)
5483                         continue;
5484
5485                 label_t *label = goto_statement->label;
5486
5487                 label->used = true;
5488                 if (label->base.source_position.input_name == NULL) {
5489                         print_in_function();
5490                         errorf(&goto_statement->base.source_position,
5491                                "label '%Y' used but not defined", label->base.symbol);
5492                  }
5493         }
5494
5495         if (warning.unused_label) {
5496                 for (const label_statement_t *label_statement = label_first;
5497                          label_statement != NULL;
5498                          label_statement = label_statement->next) {
5499                         label_t *label = label_statement->label;
5500
5501                         if (! label->used) {
5502                                 print_in_function();
5503                                 warningf(&label_statement->base.source_position,
5504                                          "label '%Y' defined but not used", label->base.symbol);
5505                         }
5506                 }
5507         }
5508 }
5509
5510 static void warn_unused_entity(entity_t *entity, entity_t *end)
5511 {
5512         for (; entity != NULL; entity = entity->base.next) {
5513                 if (!is_declaration(entity))
5514                         continue;
5515
5516                 declaration_t *declaration = &entity->declaration;
5517                 if (declaration->implicit)
5518                         continue;
5519
5520                 if (!declaration->used) {
5521                         print_in_function();
5522                         const char *what = get_entity_kind_name(entity->kind);
5523                         warningf(&entity->base.source_position, "%s '%Y' is unused",
5524                                  what, entity->base.symbol);
5525                 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5526                         print_in_function();
5527                         const char *what = get_entity_kind_name(entity->kind);
5528                         warningf(&entity->base.source_position, "%s '%Y' is never read",
5529                                  what, entity->base.symbol);
5530                 }
5531
5532                 if (entity == end)
5533                         break;
5534         }
5535 }
5536
5537 static void check_unused_variables(statement_t *const stmt, void *const env)
5538 {
5539         (void)env;
5540
5541         switch (stmt->kind) {
5542                 case STATEMENT_DECLARATION: {
5543                         declaration_statement_t const *const decls = &stmt->declaration;
5544                         warn_unused_entity(decls->declarations_begin,
5545                                            decls->declarations_end);
5546                         return;
5547                 }
5548
5549                 case STATEMENT_FOR:
5550                         warn_unused_entity(stmt->fors.scope.entities, NULL);
5551                         return;
5552
5553                 default:
5554                         return;
5555         }
5556 }
5557
5558 /**
5559  * Check declarations of current_function for unused entities.
5560  */
5561 static void check_declarations(void)
5562 {
5563         if (warning.unused_parameter) {
5564                 const scope_t *scope = &current_function->parameters;
5565
5566                 /* do not issue unused warnings for main */
5567                 if (!is_sym_main(current_function->base.base.symbol)) {
5568                         warn_unused_entity(scope->entities, NULL);
5569                 }
5570         }
5571         if (warning.unused_variable) {
5572                 walk_statements(current_function->statement, check_unused_variables,
5573                                 NULL);
5574         }
5575 }
5576
5577 static int determine_truth(expression_t const* const cond)
5578 {
5579         return
5580                 !is_constant_expression(cond) ? 0 :
5581                 fold_constant(cond) != 0      ? 1 :
5582                 -1;
5583 }
5584
5585 static void check_reachable(statement_t *);
5586
5587 static bool expression_returns(expression_t const *const expr)
5588 {
5589         switch (expr->kind) {
5590                 case EXPR_CALL: {
5591                         expression_t const *const func = expr->call.function;
5592                         if (func->kind == EXPR_REFERENCE) {
5593                                 entity_t *entity = func->reference.entity;
5594                                 if (entity->kind == ENTITY_FUNCTION
5595                                                 && entity->declaration.modifiers & DM_NORETURN)
5596                                         return false;
5597                         }
5598
5599                         if (!expression_returns(func))
5600                                 return false;
5601
5602                         for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5603                                 if (!expression_returns(arg->expression))
5604                                         return false;
5605                         }
5606
5607                         return true;
5608                 }
5609
5610                 case EXPR_REFERENCE:
5611                 case EXPR_REFERENCE_ENUM_VALUE:
5612                 case EXPR_CONST:
5613                 case EXPR_CHARACTER_CONSTANT:
5614                 case EXPR_WIDE_CHARACTER_CONSTANT:
5615                 case EXPR_STRING_LITERAL:
5616                 case EXPR_WIDE_STRING_LITERAL:
5617                 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5618                 case EXPR_LABEL_ADDRESS:
5619                 case EXPR_CLASSIFY_TYPE:
5620                 case EXPR_SIZEOF: // TODO handle obscure VLA case
5621                 case EXPR_ALIGNOF:
5622                 case EXPR_FUNCNAME:
5623                 case EXPR_BUILTIN_SYMBOL:
5624                 case EXPR_BUILTIN_CONSTANT_P:
5625                 case EXPR_BUILTIN_PREFETCH:
5626                 case EXPR_OFFSETOF:
5627                 case EXPR_INVALID:
5628                         return true;
5629
5630                 case EXPR_STATEMENT:
5631                         check_reachable(expr->statement.statement);
5632                         // TODO check if statement can be left
5633                         return true;
5634
5635                 case EXPR_CONDITIONAL:
5636                         // TODO handle constant expression
5637
5638                         if (!expression_returns(expr->conditional.condition))
5639                                 return false;
5640
5641                         if (expr->conditional.true_expression != NULL
5642                                         && expression_returns(expr->conditional.true_expression))
5643                                 return true;
5644
5645                         return expression_returns(expr->conditional.false_expression);
5646
5647                 case EXPR_SELECT:
5648                         return expression_returns(expr->select.compound);
5649
5650                 case EXPR_ARRAY_ACCESS:
5651                         return
5652                                 expression_returns(expr->array_access.array_ref) &&
5653                                 expression_returns(expr->array_access.index);
5654
5655                 case EXPR_VA_START:
5656                         return expression_returns(expr->va_starte.ap);
5657
5658                 case EXPR_VA_ARG:
5659                         return expression_returns(expr->va_arge.ap);
5660
5661                 EXPR_UNARY_CASES_MANDATORY
5662                         return expression_returns(expr->unary.value);
5663
5664                 case EXPR_UNARY_THROW:
5665                         return false;
5666
5667                 EXPR_BINARY_CASES
5668                         // TODO handle constant lhs of && and ||
5669                         return
5670                                 expression_returns(expr->binary.left) &&
5671                                 expression_returns(expr->binary.right);
5672
5673                 case EXPR_UNKNOWN:
5674                         break;
5675         }
5676
5677         panic("unhandled expression");
5678 }
5679
5680 static bool initializer_returns(initializer_t const *const init)
5681 {
5682         switch (init->kind) {
5683                 case INITIALIZER_VALUE:
5684                         return expression_returns(init->value.value);
5685
5686                 case INITIALIZER_LIST: {
5687                         initializer_t * const*       i       = init->list.initializers;
5688                         initializer_t * const* const end     = i + init->list.len;
5689                         bool                         returns = true;
5690                         for (; i != end; ++i) {
5691                                 if (!initializer_returns(*i))
5692                                         returns = false;
5693                         }
5694                         return returns;
5695                 }
5696
5697                 case INITIALIZER_STRING:
5698                 case INITIALIZER_WIDE_STRING:
5699                 case INITIALIZER_DESIGNATOR: // designators have no payload
5700                         return true;
5701         }
5702         panic("unhandled initializer");
5703 }
5704
5705 static bool noreturn_candidate;
5706
5707 static void check_reachable(statement_t *const stmt)
5708 {
5709         if (stmt->base.reachable)
5710                 return;
5711         if (stmt->kind != STATEMENT_DO_WHILE)
5712                 stmt->base.reachable = true;
5713
5714         statement_t *last = stmt;
5715         statement_t *next;
5716         switch (stmt->kind) {
5717                 case STATEMENT_INVALID:
5718                 case STATEMENT_EMPTY:
5719                 case STATEMENT_LOCAL_LABEL:
5720                 case STATEMENT_ASM:
5721                         next = stmt->base.next;
5722                         break;
5723
5724                 case STATEMENT_DECLARATION: {
5725                         declaration_statement_t const *const decl = &stmt->declaration;
5726                         entity_t                const *      ent  = decl->declarations_begin;
5727                         entity_t                const *const last = decl->declarations_end;
5728                         for (;; ent = ent->base.next) {
5729                                 if (ent->kind                 == ENTITY_VARIABLE &&
5730                                                 ent->variable.initializer != NULL            &&
5731                                                 !initializer_returns(ent->variable.initializer)) {
5732                                         return;
5733                                 }
5734                                 if (ent == last)
5735                                         break;
5736                         }
5737                         next = stmt->base.next;
5738                         break;
5739                 }
5740
5741                 case STATEMENT_COMPOUND:
5742                         next = stmt->compound.statements;
5743                         break;
5744
5745                 case STATEMENT_RETURN: {
5746                         expression_t const *const val = stmt->returns.value;
5747                         if (val == NULL || expression_returns(val))
5748                                 noreturn_candidate = false;
5749                         return;
5750                 }
5751
5752                 case STATEMENT_IF: {
5753                         if_statement_t const *const ifs  = &stmt->ifs;
5754                         expression_t   const *const cond = ifs->condition;
5755
5756                         if (!expression_returns(cond))
5757                                 return;
5758
5759                         int const val = determine_truth(cond);
5760
5761                         if (val >= 0)
5762                                 check_reachable(ifs->true_statement);
5763
5764                         if (val > 0)
5765                                 return;
5766
5767                         if (ifs->false_statement != NULL) {
5768                                 check_reachable(ifs->false_statement);
5769                                 return;
5770                         }
5771
5772                         next = stmt->base.next;
5773                         break;
5774                 }
5775
5776                 case STATEMENT_SWITCH: {
5777                         switch_statement_t const *const switchs = &stmt->switchs;
5778                         expression_t       const *const expr    = switchs->expression;
5779
5780                         if (!expression_returns(expr))
5781                                 return;
5782
5783                         if (is_constant_expression(expr)) {
5784                                 long                    const val      = fold_constant(expr);
5785                                 case_label_statement_t *      defaults = NULL;
5786                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5787                                         if (i->expression == NULL) {
5788                                                 defaults = i;
5789                                                 continue;
5790                                         }
5791
5792                                         if (i->first_case <= val && val <= i->last_case) {
5793                                                 check_reachable((statement_t*)i);
5794                                                 return;
5795                                         }
5796                                 }
5797
5798                                 if (defaults != NULL) {
5799                                         check_reachable((statement_t*)defaults);
5800                                         return;
5801                                 }
5802                         } else {
5803                                 bool has_default = false;
5804                                 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5805                                         if (i->expression == NULL)
5806                                                 has_default = true;
5807
5808                                         check_reachable((statement_t*)i);
5809                                 }
5810
5811                                 if (has_default)
5812                                         return;
5813                         }
5814
5815                         next = stmt->base.next;
5816                         break;
5817                 }
5818
5819                 case STATEMENT_EXPRESSION: {
5820                         /* Check for noreturn function call */
5821                         expression_t const *const expr = stmt->expression.expression;
5822                         if (!expression_returns(expr))
5823                                 return;
5824
5825                         next = stmt->base.next;
5826                         break;
5827                 }
5828
5829                 case STATEMENT_CONTINUE: {
5830                         statement_t *parent = stmt;
5831                         for (;;) {
5832                                 parent = parent->base.parent;
5833                                 if (parent == NULL) /* continue not within loop */
5834                                         return;
5835
5836                                 next = parent;
5837                                 switch (parent->kind) {
5838                                         case STATEMENT_WHILE:    goto continue_while;
5839                                         case STATEMENT_DO_WHILE: goto continue_do_while;
5840                                         case STATEMENT_FOR:      goto continue_for;
5841
5842                                         default: break;
5843                                 }
5844                         }
5845                 }
5846
5847                 case STATEMENT_BREAK: {
5848                         statement_t *parent = stmt;
5849                         for (;;) {
5850                                 parent = parent->base.parent;
5851                                 if (parent == NULL) /* break not within loop/switch */
5852                                         return;
5853
5854                                 switch (parent->kind) {
5855                                         case STATEMENT_SWITCH:
5856                                         case STATEMENT_WHILE:
5857                                         case STATEMENT_DO_WHILE:
5858                                         case STATEMENT_FOR:
5859                                                 last = parent;
5860                                                 next = parent->base.next;
5861                                                 goto found_break_parent;
5862
5863                                         default: break;
5864                                 }
5865                         }
5866 found_break_parent:
5867                         break;
5868                 }
5869
5870                 case STATEMENT_GOTO:
5871                         if (stmt->gotos.expression) {
5872                                 if (!expression_returns(stmt->gotos.expression))
5873                                         return;
5874
5875                                 statement_t *parent = stmt->base.parent;
5876                                 if (parent == NULL) /* top level goto */
5877                                         return;
5878                                 next = parent;
5879                         } else {
5880                                 next = stmt->gotos.label->statement;
5881                                 if (next == NULL) /* missing label */
5882                                         return;
5883                         }
5884                         break;
5885
5886                 case STATEMENT_LABEL:
5887                         next = stmt->label.statement;
5888                         break;
5889
5890                 case STATEMENT_CASE_LABEL:
5891                         next = stmt->case_label.statement;
5892                         break;
5893
5894                 case STATEMENT_WHILE: {
5895                         while_statement_t const *const whiles = &stmt->whiles;
5896                         expression_t      const *const cond   = whiles->condition;
5897
5898                         if (!expression_returns(cond))
5899                                 return;
5900
5901                         int const val = determine_truth(cond);
5902
5903                         if (val >= 0)
5904                                 check_reachable(whiles->body);
5905
5906                         if (val > 0)
5907                                 return;
5908
5909                         next = stmt->base.next;
5910                         break;
5911                 }
5912
5913                 case STATEMENT_DO_WHILE:
5914                         next = stmt->do_while.body;
5915                         break;
5916
5917                 case STATEMENT_FOR: {
5918                         for_statement_t *const fors = &stmt->fors;
5919
5920                         if (fors->condition_reachable)
5921                                 return;
5922                         fors->condition_reachable = true;
5923
5924                         expression_t const *const cond = fors->condition;
5925
5926                         int val;
5927                         if (cond == NULL) {
5928                                 val = 1;
5929                         } else if (expression_returns(cond)) {
5930                                 val = determine_truth(cond);
5931                         } else {
5932                                 return;
5933                         }
5934
5935                         if (val >= 0)
5936                                 check_reachable(fors->body);
5937
5938                         if (val > 0)
5939                                 return;
5940
5941                         next = stmt->base.next;
5942                         break;
5943                 }
5944
5945                 case STATEMENT_MS_TRY: {
5946                         ms_try_statement_t const *const ms_try = &stmt->ms_try;
5947                         check_reachable(ms_try->try_statement);
5948                         next = ms_try->final_statement;
5949                         break;
5950                 }
5951
5952                 case STATEMENT_LEAVE: {
5953                         statement_t *parent = stmt;
5954                         for (;;) {
5955                                 parent = parent->base.parent;
5956                                 if (parent == NULL) /* __leave not within __try */
5957                                         return;
5958
5959                                 if (parent->kind == STATEMENT_MS_TRY) {
5960                                         last = parent;
5961                                         next = parent->ms_try.final_statement;
5962                                         break;
5963                                 }
5964                         }
5965                         break;
5966                 }
5967         }
5968
5969         while (next == NULL) {
5970                 next = last->base.parent;
5971                 if (next == NULL) {
5972                         noreturn_candidate = false;
5973
5974                         type_t *const type = current_function->base.type;
5975                         assert(is_type_function(type));
5976                         type_t *const ret  = skip_typeref(type->function.return_type);
5977                         if (warning.return_type                    &&
5978                             !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5979                             is_type_valid(ret)                     &&
5980                             !is_sym_main(current_function->base.base.symbol)) {
5981                                 warningf(&stmt->base.source_position,
5982                                          "control reaches end of non-void function");
5983                         }
5984                         return;
5985                 }
5986
5987                 switch (next->kind) {
5988                         case STATEMENT_INVALID:
5989                         case STATEMENT_EMPTY:
5990                         case STATEMENT_DECLARATION:
5991                         case STATEMENT_LOCAL_LABEL:
5992                         case STATEMENT_EXPRESSION:
5993                         case STATEMENT_ASM:
5994                         case STATEMENT_RETURN:
5995                         case STATEMENT_CONTINUE:
5996                         case STATEMENT_BREAK:
5997                         case STATEMENT_GOTO:
5998                         case STATEMENT_LEAVE:
5999                                 panic("invalid control flow in function");
6000
6001                         case STATEMENT_COMPOUND:
6002                         case STATEMENT_IF:
6003                         case STATEMENT_SWITCH:
6004                         case STATEMENT_LABEL:
6005                         case STATEMENT_CASE_LABEL:
6006                                 last = next;
6007                                 next = next->base.next;
6008                                 break;
6009
6010                         case STATEMENT_WHILE: {
6011 continue_while:
6012                                 if (next->base.reachable)
6013                                         return;
6014                                 next->base.reachable = true;
6015
6016                                 while_statement_t const *const whiles = &next->whiles;
6017                                 expression_t      const *const cond   = whiles->condition;
6018
6019                                 if (!expression_returns(cond))
6020                                         return;
6021
6022                                 int const val = determine_truth(cond);
6023
6024                                 if (val >= 0)
6025                                         check_reachable(whiles->body);
6026
6027                                 if (val > 0)
6028                                         return;
6029
6030                                 last = next;
6031                                 next = next->base.next;
6032                                 break;
6033                         }
6034
6035                         case STATEMENT_DO_WHILE: {
6036 continue_do_while:
6037                                 if (next->base.reachable)
6038                                         return;
6039                                 next->base.reachable = true;
6040
6041                                 do_while_statement_t const *const dw   = &next->do_while;
6042                                 expression_t         const *const cond = dw->condition;
6043
6044                                 if (!expression_returns(cond))
6045                                         return;
6046
6047                                 int const val = determine_truth(cond);
6048
6049                                 if (val >= 0)
6050                                         check_reachable(dw->body);
6051
6052                                 if (val > 0)
6053                                         return;
6054
6055                                 last = next;
6056                                 next = next->base.next;
6057                                 break;
6058                         }
6059
6060                         case STATEMENT_FOR: {
6061 continue_for:;
6062                                 for_statement_t *const fors = &next->fors;
6063
6064                                 fors->step_reachable = true;
6065
6066                                 if (fors->condition_reachable)
6067                                         return;
6068                                 fors->condition_reachable = true;
6069
6070                                 expression_t const *const cond = fors->condition;
6071
6072                                 int val;
6073                                 if (cond == NULL) {
6074                                         val = 1;
6075                                 } else if (expression_returns(cond)) {
6076                                         val = determine_truth(cond);
6077                                 } else {
6078                                         return;
6079                                 }
6080
6081                                 if (val >= 0)
6082                                         check_reachable(fors->body);
6083
6084                                 if (val > 0)
6085                                         return;
6086
6087                                 last = next;
6088                                 next = next->base.next;
6089                                 break;
6090                         }
6091
6092                         case STATEMENT_MS_TRY:
6093                                 last = next;
6094                                 next = next->ms_try.final_statement;
6095                                 break;
6096                 }
6097         }
6098
6099         check_reachable(next);
6100 }
6101
6102 static void check_unreachable(statement_t* const stmt, void *const env)
6103 {
6104         (void)env;
6105
6106         switch (stmt->kind) {
6107                 case STATEMENT_DO_WHILE:
6108                         if (!stmt->base.reachable) {
6109                                 expression_t const *const cond = stmt->do_while.condition;
6110                                 if (determine_truth(cond) >= 0) {
6111                                         warningf(&cond->base.source_position,
6112                                                  "condition of do-while-loop is unreachable");
6113                                 }
6114                         }
6115                         return;
6116
6117                 case STATEMENT_FOR: {
6118                         for_statement_t const* const fors = &stmt->fors;
6119
6120                         // if init and step are unreachable, cond is unreachable, too
6121                         if (!stmt->base.reachable && !fors->step_reachable) {
6122                                 warningf(&stmt->base.source_position, "statement is unreachable");
6123                         } else {
6124                                 if (!stmt->base.reachable && fors->initialisation != NULL) {
6125                                         warningf(&fors->initialisation->base.source_position,
6126                                                  "initialisation of for-statement is unreachable");
6127                                 }
6128
6129                                 if (!fors->condition_reachable && fors->condition != NULL) {
6130                                         warningf(&fors->condition->base.source_position,
6131                                                  "condition of for-statement is unreachable");
6132                                 }
6133
6134                                 if (!fors->step_reachable && fors->step != NULL) {
6135                                         warningf(&fors->step->base.source_position,
6136                                                  "step of for-statement is unreachable");
6137                                 }
6138                         }
6139                         return;
6140                 }
6141
6142                 case STATEMENT_COMPOUND:
6143                         if (stmt->compound.statements != NULL)
6144                                 return;
6145                         goto warn_unreachable;
6146
6147                 case STATEMENT_DECLARATION: {
6148                         /* Only warn if there is at least one declarator with an initializer.
6149                          * This typically occurs in switch statements. */
6150                         declaration_statement_t const *const decl = &stmt->declaration;
6151                         entity_t                const *      ent  = decl->declarations_begin;
6152                         entity_t                const *const last = decl->declarations_end;
6153                         for (;; ent = ent->base.next) {
6154                                 if (ent->kind                 == ENTITY_VARIABLE &&
6155                                                 ent->variable.initializer != NULL) {
6156                                         goto warn_unreachable;
6157                                 }
6158                                 if (ent == last)
6159                                         return;
6160                         }
6161                 }
6162
6163                 default:
6164 warn_unreachable:
6165                         if (!stmt->base.reachable)
6166                                 warningf(&stmt->base.source_position, "statement is unreachable");
6167                         return;
6168         }
6169 }
6170
6171 static void parse_external_declaration(void)
6172 {
6173         /* function-definitions and declarations both start with declaration
6174          * specifiers */
6175         declaration_specifiers_t specifiers;
6176         memset(&specifiers, 0, sizeof(specifiers));
6177
6178         add_anchor_token(';');
6179         parse_declaration_specifiers(&specifiers);
6180         rem_anchor_token(';');
6181
6182         /* must be a declaration */
6183         if (token.type == ';') {
6184                 parse_anonymous_declaration_rest(&specifiers);
6185                 return;
6186         }
6187
6188         add_anchor_token(',');
6189         add_anchor_token('=');
6190         add_anchor_token(';');
6191         add_anchor_token('{');
6192
6193         /* declarator is common to both function-definitions and declarations */
6194         entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6195
6196         rem_anchor_token('{');
6197         rem_anchor_token(';');
6198         rem_anchor_token('=');
6199         rem_anchor_token(',');
6200
6201         /* must be a declaration */
6202         switch (token.type) {
6203                 case ',':
6204                 case ';':
6205                 case '=':
6206                         parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6207                                         DECL_FLAGS_NONE);
6208                         return;
6209         }
6210
6211         /* must be a function definition */
6212         parse_kr_declaration_list(ndeclaration);
6213
6214         if (token.type != '{') {
6215                 parse_error_expected("while parsing function definition", '{', NULL);
6216                 eat_until_matching_token(';');
6217                 return;
6218         }
6219
6220         assert(is_declaration(ndeclaration));
6221         type_t *type = skip_typeref(ndeclaration->declaration.type);
6222
6223         if (!is_type_function(type)) {
6224                 if (is_type_valid(type)) {
6225                         errorf(HERE, "declarator '%#T' has a body but is not a function type",
6226                                type, ndeclaration->base.symbol);
6227                 }
6228                 eat_block();
6229                 return;
6230         }
6231
6232         if (warning.aggregate_return &&
6233             is_type_compound(skip_typeref(type->function.return_type))) {
6234                 warningf(HERE, "function '%Y' returns an aggregate",
6235                          ndeclaration->base.symbol);
6236         }
6237         if (warning.traditional && !type->function.unspecified_parameters) {
6238                 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6239                         ndeclaration->base.symbol);
6240         }
6241         if (warning.old_style_definition && type->function.unspecified_parameters) {
6242                 warningf(HERE, "old-style function definition '%Y'",
6243                         ndeclaration->base.symbol);
6244         }
6245
6246         /* Â§ 6.7.5.3 (14) a function definition with () means no
6247          * parameters (and not unspecified parameters) */
6248         if (type->function.unspecified_parameters
6249                         && type->function.parameters == NULL
6250                         && !type->function.kr_style_parameters) {
6251                 type_t *duplicate = duplicate_type(type);
6252                 duplicate->function.unspecified_parameters = false;
6253
6254                 type = typehash_insert(duplicate);
6255                 if (type != duplicate) {
6256                         obstack_free(type_obst, duplicate);
6257                 }
6258                 ndeclaration->declaration.type = type;
6259         }
6260
6261         entity_t *const entity = record_entity(ndeclaration, true);
6262         assert(entity->kind == ENTITY_FUNCTION);
6263         assert(ndeclaration->kind == ENTITY_FUNCTION);
6264
6265         function_t *function = &entity->function;
6266         if (ndeclaration != entity) {
6267                 function->parameters = ndeclaration->function.parameters;
6268         }
6269         assert(is_declaration(entity));
6270         type = skip_typeref(entity->declaration.type);
6271
6272         /* push function parameters and switch scope */
6273         size_t const  top       = environment_top();
6274         scope_t      *old_scope = scope_push(&function->parameters);
6275
6276         entity_t *parameter = function->parameters.entities;
6277         for (; parameter != NULL; parameter = parameter->base.next) {
6278                 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6279                         parameter->base.parent_scope = current_scope;
6280                 }
6281                 assert(parameter->base.parent_scope == NULL
6282                                 || parameter->base.parent_scope == current_scope);
6283                 parameter->base.parent_scope = current_scope;
6284                 if (parameter->base.symbol == NULL) {
6285                         errorf(&parameter->base.source_position, "parameter name omitted");
6286                         continue;
6287                 }
6288                 environment_push(parameter);
6289         }
6290
6291         if (function->statement != NULL) {
6292                 parser_error_multiple_definition(entity, HERE);
6293                 eat_block();
6294         } else {
6295                 /* parse function body */
6296                 int         label_stack_top      = label_top();
6297                 function_t *old_current_function = current_function;
6298                 current_function                 = function;
6299                 current_parent                   = NULL;
6300
6301                 goto_first   = NULL;
6302                 goto_anchor  = &goto_first;
6303                 label_first  = NULL;
6304                 label_anchor = &label_first;
6305
6306                 statement_t *const body = parse_compound_statement(false);
6307                 function->statement = body;
6308                 first_err = true;
6309                 check_labels();
6310                 check_declarations();
6311                 if (warning.return_type      ||
6312                     warning.unreachable_code ||
6313                     (warning.missing_noreturn
6314                      && !(function->base.modifiers & DM_NORETURN))) {
6315                         noreturn_candidate = true;
6316                         check_reachable(body);
6317                         if (warning.unreachable_code)
6318                                 walk_statements(body, check_unreachable, NULL);
6319                         if (warning.missing_noreturn &&
6320                             noreturn_candidate       &&
6321                             !(function->base.modifiers & DM_NORETURN)) {
6322                                 warningf(&body->base.source_position,
6323                                          "function '%#T' is candidate for attribute 'noreturn'",
6324                                          type, entity->base.symbol);
6325                         }
6326                 }
6327
6328                 assert(current_parent   == NULL);
6329                 assert(current_function == function);
6330                 current_function = old_current_function;
6331                 label_pop_to(label_stack_top);
6332         }
6333
6334         assert(current_scope == &function->parameters);
6335         scope_pop(old_scope);
6336         environment_pop_to(top);
6337 }
6338
6339 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6340                                   source_position_t *source_position,
6341                                   const symbol_t *symbol)
6342 {
6343         type_t *type = allocate_type_zero(TYPE_BITFIELD);
6344
6345         type->bitfield.base_type       = base_type;
6346         type->bitfield.size_expression = size;
6347
6348         il_size_t bit_size;
6349         type_t *skipped_type = skip_typeref(base_type);
6350         if (!is_type_integer(skipped_type)) {
6351                 errorf(HERE, "bitfield base type '%T' is not an integer type",
6352                         base_type);
6353                 bit_size = 0;
6354         } else {
6355                 bit_size = skipped_type->base.size * 8;
6356         }
6357
6358         if (is_constant_expression(size)) {
6359                 long v = fold_constant(size);
6360
6361                 if (v < 0) {
6362                         errorf(source_position, "negative width in bit-field '%Y'", symbol);
6363                 } else if (v == 0) {
6364                         errorf(source_position, "zero width for bit-field '%Y'", symbol);
6365                 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6366                         errorf(source_position, "width of '%Y' exceeds its type", symbol);
6367                 } else {
6368                         type->bitfield.bit_size = v;
6369                 }
6370         }
6371
6372         return type;
6373 }
6374
6375 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6376 {
6377         entity_t *iter = compound->members.entities;
6378         for (; iter != NULL; iter = iter->base.next) {
6379                 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6380                         continue;
6381
6382                 if (iter->base.symbol == symbol) {
6383                         return iter;
6384                 } else if (iter->base.symbol == NULL) {
6385                         type_t *type = skip_typeref(iter->declaration.type);
6386                         if (is_type_compound(type)) {
6387                                 entity_t *result
6388                                         = find_compound_entry(type->compound.compound, symbol);
6389                                 if (result != NULL)
6390                                         return result;
6391                         }
6392                         continue;
6393                 }
6394         }
6395
6396         return NULL;
6397 }
6398
6399 static void parse_compound_declarators(compound_t *compound,
6400                 const declaration_specifiers_t *specifiers)
6401 {
6402         while (true) {
6403                 entity_t *entity;
6404
6405                 if (token.type == ':') {
6406                         source_position_t source_position = *HERE;
6407                         next_token();
6408
6409                         type_t *base_type = specifiers->type;
6410                         expression_t *size = parse_constant_expression();
6411
6412                         type_t *type = make_bitfield_type(base_type, size,
6413                                         &source_position, sym_anonymous);
6414
6415                         entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6416                         entity->base.namespc                       = NAMESPACE_NORMAL;
6417                         entity->base.source_position               = source_position;
6418                         entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6419                         entity->declaration.storage_class          = STORAGE_CLASS_NONE;
6420                         entity->declaration.modifiers              = specifiers->modifiers;
6421                         entity->declaration.type                   = type;
6422                 } else {
6423                         entity = parse_declarator(specifiers,
6424                                         DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6425                         assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6426
6427                         if (token.type == ':') {
6428                                 source_position_t source_position = *HERE;
6429                                 next_token();
6430                                 expression_t *size = parse_constant_expression();
6431
6432                                 type_t *type = entity->declaration.type;
6433                                 type_t *bitfield_type = make_bitfield_type(type, size,
6434                                                 &source_position, entity->base.symbol);
6435                                 entity->declaration.type = bitfield_type;
6436                         }
6437                 }
6438
6439                 /* make sure we don't define a symbol multiple times */
6440                 symbol_t *symbol = entity->base.symbol;
6441                 if (symbol != NULL) {
6442                         entity_t *prev = find_compound_entry(compound, symbol);
6443
6444                         if (prev != NULL) {
6445                                 errorf(&entity->base.source_position,
6446                                        "multiple declarations of symbol '%Y' (declared %P)",
6447                                        symbol, &prev->base.source_position);
6448                         }
6449                 }
6450
6451                 append_entity(&compound->members, entity);
6452
6453                 type_t *orig_type = entity->declaration.type;
6454                 type_t *type      = skip_typeref(orig_type);
6455                 if (is_type_function(type)) {
6456                         errorf(&entity->base.source_position,
6457                                         "compound member '%Y' must not have function type '%T'",
6458                                         entity->base.symbol, orig_type);
6459                 } else if (is_type_incomplete(type)) {
6460                         /* Â§6.7.2.1:16 flexible array member */
6461                         if (is_type_array(type) &&
6462                                         token.type == ';'   &&
6463                                         look_ahead(1)->type == '}') {
6464                                 compound->has_flexible_member = true;
6465                         } else {
6466                                 errorf(&entity->base.source_position,
6467                                                 "compound member '%Y' has incomplete type '%T'",
6468                                                 entity->base.symbol, orig_type);
6469                         }
6470                 }
6471
6472                 if (token.type != ',')
6473                         break;
6474                 next_token();
6475         }
6476         expect(';');
6477
6478 end_error:
6479         anonymous_entity = NULL;
6480 }
6481
6482 static void parse_compound_type_entries(compound_t *compound)
6483 {
6484         eat('{');
6485         add_anchor_token('}');
6486
6487         while (token.type != '}') {
6488                 if (token.type == T_EOF) {
6489                         errorf(HERE, "EOF while parsing struct");
6490                         break;
6491                 }
6492                 declaration_specifiers_t specifiers;
6493                 memset(&specifiers, 0, sizeof(specifiers));
6494                 parse_declaration_specifiers(&specifiers);
6495
6496                 parse_compound_declarators(compound, &specifiers);
6497         }
6498         rem_anchor_token('}');
6499         next_token();
6500
6501         /* Â§6.7.2.1:7 */
6502         compound->complete = true;
6503 }
6504
6505 static type_t *parse_typename(void)
6506 {
6507         declaration_specifiers_t specifiers;
6508         memset(&specifiers, 0, sizeof(specifiers));
6509         parse_declaration_specifiers(&specifiers);
6510         if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6511                         specifiers.thread_local) {
6512                 /* TODO: improve error message, user does probably not know what a
6513                  * storage class is...
6514                  */
6515                 errorf(HERE, "typename may not have a storage class");
6516         }
6517
6518         type_t *result = parse_abstract_declarator(specifiers.type);
6519
6520         return result;
6521 }
6522
6523
6524
6525
6526 typedef expression_t* (*parse_expression_function)(void);
6527 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6528
6529 typedef struct expression_parser_function_t expression_parser_function_t;
6530 struct expression_parser_function_t {
6531         parse_expression_function        parser;
6532         unsigned                         infix_precedence;
6533         parse_expression_infix_function  infix_parser;
6534 };
6535
6536 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6537
6538 /**
6539  * Prints an error message if an expression was expected but not read
6540  */
6541 static expression_t *expected_expression_error(void)
6542 {
6543         /* skip the error message if the error token was read */
6544         if (token.type != T_ERROR) {
6545                 errorf(HERE, "expected expression, got token '%K'", &token);
6546         }
6547         next_token();
6548
6549         return create_invalid_expression();
6550 }
6551
6552 /**
6553  * Parse a string constant.
6554  */
6555 static expression_t *parse_string_const(void)
6556 {
6557         wide_string_t wres;
6558         if (token.type == T_STRING_LITERAL) {
6559                 string_t res = token.v.string;
6560                 next_token();
6561                 while (token.type == T_STRING_LITERAL) {
6562                         res = concat_strings(&res, &token.v.string);
6563                         next_token();
6564                 }
6565                 if (token.type != T_WIDE_STRING_LITERAL) {
6566                         expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6567                         /* note: that we use type_char_ptr here, which is already the
6568                          * automatic converted type. revert_automatic_type_conversion
6569                          * will construct the array type */
6570                         cnst->base.type    = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6571                         cnst->string.value = res;
6572                         return cnst;
6573                 }
6574
6575                 wres = concat_string_wide_string(&res, &token.v.wide_string);
6576         } else {
6577                 wres = token.v.wide_string;
6578         }
6579         next_token();
6580
6581         for (;;) {
6582                 switch (token.type) {
6583                         case T_WIDE_STRING_LITERAL:
6584                                 wres = concat_wide_strings(&wres, &token.v.wide_string);
6585                                 break;
6586
6587                         case T_STRING_LITERAL:
6588                                 wres = concat_wide_string_string(&wres, &token.v.string);
6589                                 break;
6590
6591                         default: {
6592                                 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6593                                 cnst->base.type         = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6594                                 cnst->wide_string.value = wres;
6595                                 return cnst;
6596                         }
6597                 }
6598                 next_token();
6599         }
6600 }
6601
6602 /**
6603  * Parse a boolean constant.
6604  */
6605 static expression_t *parse_bool_const(bool value)
6606 {
6607         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6608         cnst->base.type          = type_bool;
6609         cnst->conste.v.int_value = value;
6610
6611         next_token();
6612
6613         return cnst;
6614 }
6615
6616 /**
6617  * Parse an integer constant.
6618  */
6619 static expression_t *parse_int_const(void)
6620 {
6621         expression_t *cnst       = allocate_expression_zero(EXPR_CONST);
6622         cnst->base.type          = token.datatype;
6623         cnst->conste.v.int_value = token.v.intvalue;
6624
6625         next_token();
6626
6627         return cnst;
6628 }
6629
6630 /**
6631  * Parse a character constant.
6632  */
6633 static expression_t *parse_character_constant(void)
6634 {
6635         expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6636         cnst->base.type          = token.datatype;
6637         cnst->conste.v.character = token.v.string;
6638
6639         if (cnst->conste.v.character.size != 1) {
6640                 if (!GNU_MODE) {
6641                         errorf(HERE, "more than 1 character in character constant");
6642                 } else if (warning.multichar) {
6643                         warningf(HERE, "multi-character character constant");
6644                 }
6645         }
6646         next_token();
6647
6648         return cnst;
6649 }
6650
6651 /**
6652  * Parse a wide character constant.
6653  */
6654 static expression_t *parse_wide_character_constant(void)
6655 {
6656         expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6657         cnst->base.type               = token.datatype;
6658         cnst->conste.v.wide_character = token.v.wide_string;
6659
6660         if (cnst->conste.v.wide_character.size != 1) {
6661                 if (!GNU_MODE) {
6662                         errorf(HERE, "more than 1 character in character constant");
6663                 } else if (warning.multichar) {
6664                         warningf(HERE, "multi-character character constant");
6665                 }
6666         }
6667         next_token();
6668
6669         return cnst;
6670 }
6671
6672 /**
6673  * Parse a float constant.
6674  */
6675 static expression_t *parse_float_const(void)
6676 {
6677         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
6678         cnst->base.type            = token.datatype;
6679         cnst->conste.v.float_value = token.v.floatvalue;
6680
6681         next_token();
6682
6683         return cnst;
6684 }
6685
6686 static entity_t *create_implicit_function(symbol_t *symbol,
6687                 const source_position_t *source_position)
6688 {
6689         type_t *ntype                          = allocate_type_zero(TYPE_FUNCTION);
6690         ntype->function.return_type            = type_int;
6691         ntype->function.unspecified_parameters = true;
6692
6693         type_t *type = typehash_insert(ntype);
6694         if (type != ntype) {
6695                 free_type(ntype);
6696         }
6697
6698         entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6699         entity->declaration.storage_class          = STORAGE_CLASS_EXTERN;
6700         entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6701         entity->declaration.type                   = type;
6702         entity->declaration.implicit               = true;
6703         entity->base.symbol                        = symbol;
6704         entity->base.source_position               = *source_position;
6705
6706         bool strict_prototypes_old = warning.strict_prototypes;
6707         warning.strict_prototypes  = false;
6708         record_entity(entity, false);
6709         warning.strict_prototypes = strict_prototypes_old;
6710
6711         return entity;
6712 }
6713
6714 /**
6715  * Creates a return_type (func)(argument_type) function type if not
6716  * already exists.
6717  */
6718 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6719                                     type_t *argument_type2)
6720 {
6721         function_parameter_t *parameter2
6722                 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6723         memset(parameter2, 0, sizeof(parameter2[0]));
6724         parameter2->type = argument_type2;
6725
6726         function_parameter_t *parameter1
6727                 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6728         memset(parameter1, 0, sizeof(parameter1[0]));
6729         parameter1->type = argument_type1;
6730         parameter1->next = parameter2;
6731
6732         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6733         type->function.return_type = return_type;
6734         type->function.parameters  = parameter1;
6735
6736         type_t *result = typehash_insert(type);
6737         if (result != type) {
6738                 free_type(type);
6739         }
6740
6741         return result;
6742 }
6743
6744 /**
6745  * Creates a return_type (func)(argument_type) function type if not
6746  * already exists.
6747  *
6748  * @param return_type    the return type
6749  * @param argument_type  the argument type
6750  */
6751 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6752 {
6753         function_parameter_t *parameter
6754                 = obstack_alloc(type_obst, sizeof(parameter[0]));
6755         memset(parameter, 0, sizeof(parameter[0]));
6756         parameter->type = argument_type;
6757
6758         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6759         type->function.return_type = return_type;
6760         type->function.parameters  = parameter;
6761
6762         type_t *result = typehash_insert(type);
6763         if (result != type) {
6764                 free_type(type);
6765         }
6766
6767         return result;
6768 }
6769
6770 static type_t *make_function_0_type(type_t *return_type)
6771 {
6772         type_t *type               = allocate_type_zero(TYPE_FUNCTION);
6773         type->function.return_type = return_type;
6774         type->function.parameters  = NULL;
6775
6776         type_t *result = typehash_insert(type);
6777         if (result != type) {
6778                 free_type(type);
6779         }
6780
6781         return result;
6782 }
6783
6784 /**
6785  * Creates a function type for some function like builtins.
6786  *
6787  * @param symbol   the symbol describing the builtin
6788  */
6789 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6790 {
6791         switch (symbol->ID) {
6792         case T___builtin_alloca:
6793                 return make_function_1_type(type_void_ptr, type_size_t);
6794         case T___builtin_huge_val:
6795                 return make_function_0_type(type_double);
6796         case T___builtin_inf:
6797                 return make_function_0_type(type_double);
6798         case T___builtin_inff:
6799                 return make_function_0_type(type_float);
6800         case T___builtin_infl:
6801                 return make_function_0_type(type_long_double);
6802         case T___builtin_nan:
6803                 return make_function_1_type(type_double, type_char_ptr);
6804         case T___builtin_nanf:
6805                 return make_function_1_type(type_float, type_char_ptr);
6806         case T___builtin_nanl:
6807                 return make_function_1_type(type_long_double, type_char_ptr);
6808         case T___builtin_va_end:
6809                 return make_function_1_type(type_void, type_valist);
6810         case T___builtin_expect:
6811                 return make_function_2_type(type_long, type_long, type_long);
6812         default:
6813                 internal_errorf(HERE, "not implemented builtin symbol found");
6814         }
6815 }
6816
6817 /**
6818  * Performs automatic type cast as described in Â§ 6.3.2.1.
6819  *
6820  * @param orig_type  the original type
6821  */
6822 static type_t *automatic_type_conversion(type_t *orig_type)
6823 {
6824         type_t *type = skip_typeref(orig_type);
6825         if (is_type_array(type)) {
6826                 array_type_t *array_type   = &type->array;
6827                 type_t       *element_type = array_type->element_type;
6828                 unsigned      qualifiers   = array_type->base.qualifiers;
6829
6830                 return make_pointer_type(element_type, qualifiers);
6831         }
6832
6833         if (is_type_function(type)) {
6834                 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6835         }
6836
6837         return orig_type;
6838 }
6839
6840 /**
6841  * reverts the automatic casts of array to pointer types and function
6842  * to function-pointer types as defined Â§ 6.3.2.1
6843  */
6844 type_t *revert_automatic_type_conversion(const expression_t *expression)
6845 {
6846         switch (expression->kind) {
6847                 case EXPR_REFERENCE: {
6848                         entity_t *entity = expression->reference.entity;
6849                         if (is_declaration(entity)) {
6850                                 return entity->declaration.type;
6851                         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6852                                 return entity->enum_value.enum_type;
6853                         } else {
6854                                 panic("no declaration or enum in reference");
6855                         }
6856                 }
6857
6858                 case EXPR_SELECT: {
6859                         entity_t *entity = expression->select.compound_entry;
6860                         assert(is_declaration(entity));
6861                         type_t   *type   = entity->declaration.type;
6862                         return get_qualified_type(type,
6863                                                   expression->base.type->base.qualifiers);
6864                 }
6865
6866                 case EXPR_UNARY_DEREFERENCE: {
6867                         const expression_t *const value = expression->unary.value;
6868                         type_t             *const type  = skip_typeref(value->base.type);
6869                         assert(is_type_pointer(type));
6870                         return type->pointer.points_to;
6871                 }
6872
6873                 case EXPR_BUILTIN_SYMBOL:
6874                         return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6875
6876                 case EXPR_ARRAY_ACCESS: {
6877                         const expression_t *array_ref = expression->array_access.array_ref;
6878                         type_t             *type_left = skip_typeref(array_ref->base.type);
6879                         if (!is_type_valid(type_left))
6880                                 return type_left;
6881                         assert(is_type_pointer(type_left));
6882                         return type_left->pointer.points_to;
6883                 }
6884
6885                 case EXPR_STRING_LITERAL: {
6886                         size_t size = expression->string.value.size;
6887                         return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6888                 }
6889
6890                 case EXPR_WIDE_STRING_LITERAL: {
6891                         size_t size = expression->wide_string.value.size;
6892                         return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6893                 }
6894
6895                 case EXPR_COMPOUND_LITERAL:
6896                         return expression->compound_literal.type;
6897
6898                 default: break;
6899         }
6900
6901         return expression->base.type;
6902 }
6903
6904 static expression_t *parse_reference(void)
6905 {
6906         symbol_t *const symbol = token.v.symbol;
6907
6908         entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6909
6910         if (entity == NULL) {
6911                 if (!strict_mode && look_ahead(1)->type == '(') {
6912                         /* an implicitly declared function */
6913                         if (warning.implicit_function_declaration) {
6914                                 warningf(HERE, "implicit declaration of function '%Y'",
6915                                         symbol);
6916                         }
6917
6918                         entity = create_implicit_function(symbol, HERE);
6919                 } else {
6920                         errorf(HERE, "unknown symbol '%Y' found.", symbol);
6921                         entity = create_error_entity(symbol, ENTITY_VARIABLE);
6922                 }
6923         }
6924
6925         type_t *orig_type;
6926
6927         if (is_declaration(entity)) {
6928                 orig_type = entity->declaration.type;
6929         } else if (entity->kind == ENTITY_ENUM_VALUE) {
6930                 orig_type = entity->enum_value.enum_type;
6931         } else if (entity->kind == ENTITY_TYPEDEF) {
6932                 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6933                         symbol);
6934                 next_token();
6935                 return create_invalid_expression();
6936         } else {
6937                 panic("expected declaration or enum value in reference");
6938         }
6939
6940         /* we always do the auto-type conversions; the & and sizeof parser contains
6941          * code to revert this! */
6942         type_t *type = automatic_type_conversion(orig_type);
6943
6944         expression_kind_t kind = EXPR_REFERENCE;
6945         if (entity->kind == ENTITY_ENUM_VALUE)
6946                 kind = EXPR_REFERENCE_ENUM_VALUE;
6947
6948         expression_t *expression     = allocate_expression_zero(kind);
6949         expression->reference.entity = entity;
6950         expression->base.type        = type;
6951
6952         /* this declaration is used */
6953         if (is_declaration(entity)) {
6954                 entity->declaration.used = true;
6955         }
6956
6957         if (entity->base.parent_scope != file_scope
6958                 && entity->base.parent_scope->depth < current_function->parameters.depth
6959                 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6960                 if (entity->kind == ENTITY_VARIABLE) {
6961                         /* access of a variable from an outer function */
6962                         entity->variable.address_taken = true;
6963                 } else if (entity->kind == ENTITY_PARAMETER) {
6964                         entity->parameter.address_taken = true;
6965                 }
6966                 current_function->need_closure = true;
6967         }
6968
6969         /* check for deprecated functions */
6970         if (warning.deprecated_declarations
6971                 && is_declaration(entity)
6972                 && entity->declaration.modifiers & DM_DEPRECATED) {
6973                 declaration_t *declaration = &entity->declaration;
6974
6975                 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6976                         "function" : "variable";
6977
6978                 if (declaration->deprecated_string != NULL) {
6979                         warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6980                                  prefix, entity->base.symbol, &entity->base.source_position,
6981                                  declaration->deprecated_string);
6982                 } else {
6983                         warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6984                                  entity->base.symbol, &entity->base.source_position);
6985                 }
6986         }
6987
6988         if (warning.init_self && entity == current_init_decl && !in_type_prop
6989             && entity->kind == ENTITY_VARIABLE) {
6990                 current_init_decl = NULL;
6991                 warningf(HERE, "variable '%#T' is initialized by itself",
6992                          entity->declaration.type, entity->base.symbol);
6993         }
6994
6995         next_token();
6996         return expression;
6997 }
6998
6999 static bool semantic_cast(expression_t *cast)
7000 {
7001         expression_t            *expression      = cast->unary.value;
7002         type_t                  *orig_dest_type  = cast->base.type;
7003         type_t                  *orig_type_right = expression->base.type;
7004         type_t            const *dst_type        = skip_typeref(orig_dest_type);
7005         type_t            const *src_type        = skip_typeref(orig_type_right);
7006         source_position_t const *pos             = &cast->base.source_position;
7007
7008         /* Â§6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7009         if (dst_type == type_void)
7010                 return true;
7011
7012         /* only integer and pointer can be casted to pointer */
7013         if (is_type_pointer(dst_type)  &&
7014             !is_type_pointer(src_type) &&
7015             !is_type_integer(src_type) &&
7016             is_type_valid(src_type)) {
7017                 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7018                 return false;
7019         }
7020
7021         if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7022                 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7023                 return false;
7024         }
7025
7026         if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7027                 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7028                 return false;
7029         }
7030
7031         if (warning.cast_qual &&
7032             is_type_pointer(src_type) &&
7033             is_type_pointer(dst_type)) {
7034                 type_t *src = skip_typeref(src_type->pointer.points_to);
7035                 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7036                 unsigned missing_qualifiers =
7037                         src->base.qualifiers & ~dst->base.qualifiers;
7038                 if (missing_qualifiers != 0) {
7039                         warningf(pos,
7040                                  "cast discards qualifiers '%Q' in pointer target type of '%T'",
7041                                  missing_qualifiers, orig_type_right);
7042                 }
7043         }
7044         return true;
7045 }
7046
7047 static expression_t *parse_compound_literal(type_t *type)
7048 {
7049         expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7050
7051         parse_initializer_env_t env;
7052         env.type             = type;
7053         env.entity           = NULL;
7054         env.must_be_constant = false;
7055         initializer_t *initializer = parse_initializer(&env);
7056         type = env.type;
7057
7058         expression->compound_literal.initializer = initializer;
7059         expression->compound_literal.type        = type;
7060         expression->base.type                    = automatic_type_conversion(type);
7061
7062         return expression;
7063 }
7064
7065 /**
7066  * Parse a cast expression.
7067  */
7068 static expression_t *parse_cast(void)
7069 {
7070         add_anchor_token(')');
7071
7072         source_position_t source_position = token.source_position;
7073
7074         type_t *type = parse_typename();
7075
7076         rem_anchor_token(')');
7077         expect(')');
7078
7079         if (token.type == '{') {
7080                 return parse_compound_literal(type);
7081         }
7082
7083         expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7084         cast->base.source_position = source_position;
7085
7086         expression_t *value = parse_sub_expression(PREC_CAST);
7087         cast->base.type   = type;
7088         cast->unary.value = value;
7089
7090         if (! semantic_cast(cast)) {
7091                 /* TODO: record the error in the AST. else it is impossible to detect it */
7092         }
7093
7094         return cast;
7095 end_error:
7096         return create_invalid_expression();
7097 }
7098
7099 /**
7100  * Parse a statement expression.
7101  */
7102 static expression_t *parse_statement_expression(void)
7103 {
7104         add_anchor_token(')');
7105
7106         expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7107
7108         statement_t *statement          = parse_compound_statement(true);
7109         expression->statement.statement = statement;
7110
7111         /* find last statement and use its type */
7112         type_t *type = type_void;
7113         const statement_t *stmt = statement->compound.statements;
7114         if (stmt != NULL) {
7115                 while (stmt->base.next != NULL)
7116                         stmt = stmt->base.next;
7117
7118                 if (stmt->kind == STATEMENT_EXPRESSION) {
7119                         type = stmt->expression.expression->base.type;
7120                 }
7121         } else if (warning.other) {
7122                 warningf(&expression->base.source_position, "empty statement expression ({})");
7123         }
7124         expression->base.type = type;
7125
7126         rem_anchor_token(')');
7127         expect(')');
7128
7129 end_error:
7130         return expression;
7131 }
7132
7133 /**
7134  * Parse a parenthesized expression.
7135  */
7136 static expression_t *parse_parenthesized_expression(void)
7137 {
7138         eat('(');
7139
7140         switch (token.type) {
7141         case '{':
7142                 /* gcc extension: a statement expression */
7143                 return parse_statement_expression();
7144
7145         TYPE_QUALIFIERS
7146         TYPE_SPECIFIERS
7147                 return parse_cast();
7148         case T_IDENTIFIER:
7149                 if (is_typedef_symbol(token.v.symbol)) {
7150                         return parse_cast();
7151                 }
7152         }
7153
7154         add_anchor_token(')');
7155         expression_t *result = parse_expression();
7156         rem_anchor_token(')');
7157         expect(')');
7158
7159 end_error:
7160         return result;
7161 }
7162
7163 static expression_t *parse_function_keyword(void)
7164 {
7165         /* TODO */
7166
7167         if (current_function == NULL) {
7168                 errorf(HERE, "'__func__' used outside of a function");
7169         }
7170
7171         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7172         expression->base.type     = type_char_ptr;
7173         expression->funcname.kind = FUNCNAME_FUNCTION;
7174
7175         next_token();
7176
7177         return expression;
7178 }
7179
7180 static expression_t *parse_pretty_function_keyword(void)
7181 {
7182         if (current_function == NULL) {
7183                 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7184         }
7185
7186         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7187         expression->base.type     = type_char_ptr;
7188         expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7189
7190         eat(T___PRETTY_FUNCTION__);
7191
7192         return expression;
7193 }
7194
7195 static expression_t *parse_funcsig_keyword(void)
7196 {
7197         if (current_function == NULL) {
7198                 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7199         }
7200
7201         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7202         expression->base.type     = type_char_ptr;
7203         expression->funcname.kind = FUNCNAME_FUNCSIG;
7204
7205         eat(T___FUNCSIG__);
7206
7207         return expression;
7208 }
7209
7210 static expression_t *parse_funcdname_keyword(void)
7211 {
7212         if (current_function == NULL) {
7213                 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7214         }
7215
7216         expression_t *expression  = allocate_expression_zero(EXPR_FUNCNAME);
7217         expression->base.type     = type_char_ptr;
7218         expression->funcname.kind = FUNCNAME_FUNCDNAME;
7219
7220         eat(T___FUNCDNAME__);
7221
7222         return expression;
7223 }
7224
7225 static designator_t *parse_designator(void)
7226 {
7227         designator_t *result    = allocate_ast_zero(sizeof(result[0]));
7228         result->source_position = *HERE;
7229
7230         if (token.type != T_IDENTIFIER) {
7231                 parse_error_expected("while parsing member designator",
7232                                      T_IDENTIFIER, NULL);
7233                 return NULL;
7234         }
7235         result->symbol = token.v.symbol;
7236         next_token();
7237
7238         designator_t *last_designator = result;
7239         while (true) {
7240                 if (token.type == '.') {
7241                         next_token();
7242                         if (token.type != T_IDENTIFIER) {
7243                                 parse_error_expected("while parsing member designator",
7244                                                      T_IDENTIFIER, NULL);
7245                                 return NULL;
7246                         }
7247                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7248                         designator->source_position = *HERE;
7249                         designator->symbol          = token.v.symbol;
7250                         next_token();
7251
7252                         last_designator->next = designator;
7253                         last_designator       = designator;
7254                         continue;
7255                 }
7256                 if (token.type == '[') {
7257                         next_token();
7258                         add_anchor_token(']');
7259                         designator_t *designator    = allocate_ast_zero(sizeof(result[0]));
7260                         designator->source_position = *HERE;
7261                         designator->array_index     = parse_expression();
7262                         rem_anchor_token(']');
7263                         expect(']');
7264                         if (designator->array_index == NULL) {
7265                                 return NULL;
7266                         }
7267
7268                         last_designator->next = designator;
7269                         last_designator       = designator;
7270                         continue;
7271                 }
7272                 break;
7273         }
7274
7275         return result;
7276 end_error:
7277         return NULL;
7278 }
7279
7280 /**
7281  * Parse the __builtin_offsetof() expression.
7282  */
7283 static expression_t *parse_offsetof(void)
7284 {
7285         expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7286         expression->base.type    = type_size_t;
7287
7288         eat(T___builtin_offsetof);
7289
7290         expect('(');
7291         add_anchor_token(',');
7292         type_t *type = parse_typename();
7293         rem_anchor_token(',');
7294         expect(',');
7295         add_anchor_token(')');
7296         designator_t *designator = parse_designator();
7297         rem_anchor_token(')');
7298         expect(')');
7299
7300         expression->offsetofe.type       = type;
7301         expression->offsetofe.designator = designator;
7302
7303         type_path_t path;
7304         memset(&path, 0, sizeof(path));
7305         path.top_type = type;
7306         path.path     = NEW_ARR_F(type_path_entry_t, 0);
7307
7308         descend_into_subtype(&path);
7309
7310         if (!walk_designator(&path, designator, true)) {
7311                 return create_invalid_expression();
7312         }
7313
7314         DEL_ARR_F(path.path);
7315
7316         return expression;
7317 end_error:
7318         return create_invalid_expression();
7319 }
7320
7321 /**
7322  * Parses a _builtin_va_start() expression.
7323  */
7324 static expression_t *parse_va_start(void)
7325 {
7326         expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7327
7328         eat(T___builtin_va_start);
7329
7330         expect('(');
7331         add_anchor_token(',');
7332         expression->va_starte.ap = parse_assignment_expression();
7333         rem_anchor_token(',');
7334         expect(',');
7335         expression_t *const expr = parse_assignment_expression();
7336         if (expr->kind == EXPR_REFERENCE) {
7337                 entity_t *const entity = expr->reference.entity;
7338                 if (entity->base.parent_scope != &current_function->parameters
7339                                 || entity->base.next != NULL
7340                                 || entity->kind != ENTITY_PARAMETER) {
7341                         errorf(&expr->base.source_position,
7342                                "second argument of 'va_start' must be last parameter of the current function");
7343                 } else {
7344                         expression->va_starte.parameter = &entity->variable;
7345                 }
7346                 expect(')');
7347                 return expression;
7348         }
7349         expect(')');
7350 end_error:
7351         return create_invalid_expression();
7352 }
7353
7354 /**
7355  * Parses a _builtin_va_arg() expression.
7356  */
7357 static expression_t *parse_va_arg(void)
7358 {
7359         expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7360
7361         eat(T___builtin_va_arg);
7362
7363         expect('(');
7364         expression->va_arge.ap = parse_assignment_expression();
7365         expect(',');
7366         expression->base.type = parse_typename();
7367         expect(')');
7368
7369         return expression;
7370 end_error:
7371         return create_invalid_expression();
7372 }
7373
7374 static expression_t *parse_builtin_symbol(void)
7375 {
7376         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7377
7378         symbol_t *symbol = token.v.symbol;
7379
7380         expression->builtin_symbol.symbol = symbol;
7381         next_token();
7382
7383         type_t *type = get_builtin_symbol_type(symbol);
7384         type = automatic_type_conversion(type);
7385
7386         expression->base.type = type;
7387         return expression;
7388 }
7389
7390 /**
7391  * Parses a __builtin_constant() expression.
7392  */
7393 static expression_t *parse_builtin_constant(void)
7394 {
7395         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7396
7397         eat(T___builtin_constant_p);
7398
7399         expect('(');
7400         add_anchor_token(')');
7401         expression->builtin_constant.value = parse_assignment_expression();
7402         rem_anchor_token(')');
7403         expect(')');
7404         expression->base.type = type_int;
7405
7406         return expression;
7407 end_error:
7408         return create_invalid_expression();
7409 }
7410
7411 /**
7412  * Parses a __builtin_prefetch() expression.
7413  */
7414 static expression_t *parse_builtin_prefetch(void)
7415 {
7416         expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7417
7418         eat(T___builtin_prefetch);
7419
7420         expect('(');
7421         add_anchor_token(')');
7422         expression->builtin_prefetch.adr = parse_assignment_expression();
7423         if (token.type == ',') {
7424                 next_token();
7425                 expression->builtin_prefetch.rw = parse_assignment_expression();
7426         }
7427         if (token.type == ',') {
7428                 next_token();
7429                 expression->builtin_prefetch.locality = parse_assignment_expression();
7430         }
7431         rem_anchor_token(')');
7432         expect(')');
7433         expression->base.type = type_void;
7434
7435         return expression;
7436 end_error:
7437         return create_invalid_expression();
7438 }
7439
7440 /**
7441  * Parses a __builtin_is_*() compare expression.
7442  */
7443 static expression_t *parse_compare_builtin(void)
7444 {
7445         expression_t *expression;
7446
7447         switch (token.type) {
7448         case T___builtin_isgreater:
7449                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7450                 break;
7451         case T___builtin_isgreaterequal:
7452                 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7453                 break;
7454         case T___builtin_isless:
7455                 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7456                 break;
7457         case T___builtin_islessequal:
7458                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7459                 break;
7460         case T___builtin_islessgreater:
7461                 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7462                 break;
7463         case T___builtin_isunordered:
7464                 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7465                 break;
7466         default:
7467                 internal_errorf(HERE, "invalid compare builtin found");
7468         }
7469         expression->base.source_position = *HERE;
7470         next_token();
7471
7472         expect('(');
7473         expression->binary.left = parse_assignment_expression();
7474         expect(',');
7475         expression->binary.right = parse_assignment_expression();
7476         expect(')');
7477
7478         type_t *const orig_type_left  = expression->binary.left->base.type;
7479         type_t *const orig_type_right = expression->binary.right->base.type;
7480
7481         type_t *const type_left  = skip_typeref(orig_type_left);
7482         type_t *const type_right = skip_typeref(orig_type_right);
7483         if (!is_type_float(type_left) && !is_type_float(type_right)) {
7484                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7485                         type_error_incompatible("invalid operands in comparison",
7486                                 &expression->base.source_position, orig_type_left, orig_type_right);
7487                 }
7488         } else {
7489                 semantic_comparison(&expression->binary);
7490         }
7491
7492         return expression;
7493 end_error:
7494         return create_invalid_expression();
7495 }
7496
7497 #if 0
7498 /**
7499  * Parses a __builtin_expect() expression.
7500  */
7501 static expression_t *parse_builtin_expect(void)
7502 {
7503         expression_t *expression
7504                 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7505
7506         eat(T___builtin_expect);
7507
7508         expect('(');
7509         expression->binary.left = parse_assignment_expression();
7510         expect(',');
7511         expression->binary.right = parse_constant_expression();
7512         expect(')');
7513
7514         expression->base.type = expression->binary.left->base.type;
7515
7516         return expression;
7517 end_error:
7518         return create_invalid_expression();
7519 }
7520 #endif
7521
7522 /**
7523  * Parses a MS assume() expression.
7524  */
7525 static expression_t *parse_assume(void)
7526 {
7527         expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7528
7529         eat(T__assume);
7530
7531         expect('(');
7532         add_anchor_token(')');
7533         expression->unary.value = parse_assignment_expression();
7534         rem_anchor_token(')');
7535         expect(')');
7536
7537         expression->base.type = type_void;
7538         return expression;
7539 end_error:
7540         return create_invalid_expression();
7541 }
7542
7543 /**
7544  * Return the declaration for a given label symbol or create a new one.
7545  *
7546  * @param symbol  the symbol of the label
7547  */
7548 static label_t *get_label(symbol_t *symbol)
7549 {
7550         entity_t *label;
7551         assert(current_function != NULL);
7552
7553         label = get_entity(symbol, NAMESPACE_LABEL);
7554         /* if we found a local label, we already created the declaration */
7555         if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7556                 if (label->base.parent_scope != current_scope) {
7557                         assert(label->base.parent_scope->depth < current_scope->depth);
7558                         current_function->goto_to_outer = true;
7559                 }
7560                 return &label->label;
7561         }
7562
7563         label = get_entity(symbol, NAMESPACE_LABEL);
7564         /* if we found a label in the same function, then we already created the
7565          * declaration */
7566         if (label != NULL
7567                         && label->base.parent_scope == &current_function->parameters) {
7568                 return &label->label;
7569         }
7570
7571         /* otherwise we need to create a new one */
7572         label               = allocate_entity_zero(ENTITY_LABEL);
7573         label->base.namespc = NAMESPACE_LABEL;
7574         label->base.symbol  = symbol;
7575
7576         label_push(label);
7577
7578         return &label->label;
7579 }
7580
7581 /**
7582  * Parses a GNU && label address expression.
7583  */
7584 static expression_t *parse_label_address(void)
7585 {
7586         source_position_t source_position = token.source_position;
7587         eat(T_ANDAND);
7588         if (token.type != T_IDENTIFIER) {
7589                 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7590                 goto end_error;
7591         }
7592         symbol_t *symbol = token.v.symbol;
7593         next_token();
7594
7595         label_t *label       = get_label(symbol);
7596         label->used          = true;
7597         label->address_taken = true;
7598
7599         expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7600         expression->base.source_position = source_position;
7601
7602         /* label address is threaten as a void pointer */
7603         expression->base.type           = type_void_ptr;
7604         expression->label_address.label = label;
7605         return expression;
7606 end_error:
7607         return create_invalid_expression();
7608 }
7609
7610 /**
7611  * Parse a microsoft __noop expression.
7612  */
7613 static expression_t *parse_noop_expression(void)
7614 {
7615         /* the result is a (int)0 */
7616         expression_t *cnst         = allocate_expression_zero(EXPR_CONST);
7617         cnst->base.type            = type_int;
7618         cnst->conste.v.int_value   = 0;
7619         cnst->conste.is_ms_noop    = true;
7620
7621         eat(T___noop);
7622
7623         if (token.type == '(') {
7624                 /* parse arguments */
7625                 eat('(');
7626                 add_anchor_token(')');
7627                 add_anchor_token(',');
7628
7629                 if (token.type != ')') {
7630                         while (true) {
7631                                 (void)parse_assignment_expression();
7632                                 if (token.type != ',')
7633                                         break;
7634                                 next_token();
7635                         }
7636                 }
7637         }
7638         rem_anchor_token(',');
7639         rem_anchor_token(')');
7640         expect(')');
7641
7642 end_error:
7643         return cnst;
7644 }
7645
7646 /**
7647  * Parses a primary expression.
7648  */
7649 static expression_t *parse_primary_expression(void)
7650 {
7651         switch (token.type) {
7652                 case T_false:                    return parse_bool_const(false);
7653                 case T_true:                     return parse_bool_const(true);
7654                 case T_INTEGER:                  return parse_int_const();
7655                 case T_CHARACTER_CONSTANT:       return parse_character_constant();
7656                 case T_WIDE_CHARACTER_CONSTANT:  return parse_wide_character_constant();
7657                 case T_FLOATINGPOINT:            return parse_float_const();
7658                 case T_STRING_LITERAL:
7659                 case T_WIDE_STRING_LITERAL:      return parse_string_const();
7660                 case T_IDENTIFIER:               return parse_reference();
7661                 case T___FUNCTION__:
7662                 case T___func__:                 return parse_function_keyword();
7663                 case T___PRETTY_FUNCTION__:      return parse_pretty_function_keyword();
7664                 case T___FUNCSIG__:              return parse_funcsig_keyword();
7665                 case T___FUNCDNAME__:            return parse_funcdname_keyword();
7666                 case T___builtin_offsetof:       return parse_offsetof();
7667                 case T___builtin_va_start:       return parse_va_start();
7668                 case T___builtin_va_arg:         return parse_va_arg();
7669                 case T___builtin_expect:
7670                 case T___builtin_alloca:
7671                 case T___builtin_inf:
7672                 case T___builtin_inff:
7673                 case T___builtin_infl:
7674                 case T___builtin_nan:
7675                 case T___builtin_nanf:
7676                 case T___builtin_nanl:
7677                 case T___builtin_huge_val:
7678                 case T___builtin_va_end:         return parse_builtin_symbol();
7679                 case T___builtin_isgreater:
7680                 case T___builtin_isgreaterequal:
7681                 case T___builtin_isless:
7682                 case T___builtin_islessequal:
7683                 case T___builtin_islessgreater:
7684                 case T___builtin_isunordered:    return parse_compare_builtin();
7685                 case T___builtin_constant_p:     return parse_builtin_constant();
7686                 case T___builtin_prefetch:       return parse_builtin_prefetch();
7687                 case T__assume:                  return parse_assume();
7688                 case T_ANDAND:
7689                         if (GNU_MODE)
7690                                 return parse_label_address();
7691                         break;
7692
7693                 case '(':                        return parse_parenthesized_expression();
7694                 case T___noop:                   return parse_noop_expression();
7695         }
7696
7697         errorf(HERE, "unexpected token '%K', expected an expression", &token);
7698         return create_invalid_expression();
7699 }
7700
7701 /**
7702  * Check if the expression has the character type and issue a warning then.
7703  */
7704 static void check_for_char_index_type(const expression_t *expression)
7705 {
7706         type_t       *const type      = expression->base.type;
7707         const type_t *const base_type = skip_typeref(type);
7708
7709         if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7710                         warning.char_subscripts) {
7711                 warningf(&expression->base.source_position,
7712                          "array subscript has type '%T'", type);
7713         }
7714 }
7715
7716 static expression_t *parse_array_expression(expression_t *left)
7717 {
7718         expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7719
7720         eat('[');
7721         add_anchor_token(']');
7722
7723         expression_t *inside = parse_expression();
7724
7725         type_t *const orig_type_left   = left->base.type;
7726         type_t *const orig_type_inside = inside->base.type;
7727
7728         type_t *const type_left   = skip_typeref(orig_type_left);
7729         type_t *const type_inside = skip_typeref(orig_type_inside);
7730
7731         type_t                    *return_type;
7732         array_access_expression_t *array_access = &expression->array_access;
7733         if (is_type_pointer(type_left)) {
7734                 return_type             = type_left->pointer.points_to;
7735                 array_access->array_ref = left;
7736                 array_access->index     = inside;
7737                 check_for_char_index_type(inside);
7738         } else if (is_type_pointer(type_inside)) {
7739                 return_type             = type_inside->pointer.points_to;
7740                 array_access->array_ref = inside;
7741                 array_access->index     = left;
7742                 array_access->flipped   = true;
7743                 check_for_char_index_type(left);
7744         } else {
7745                 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7746                         errorf(HERE,
7747                                 "array access on object with non-pointer types '%T', '%T'",
7748                                 orig_type_left, orig_type_inside);
7749                 }
7750                 return_type             = type_error_type;
7751                 array_access->array_ref = left;
7752                 array_access->index     = inside;
7753         }
7754
7755         expression->base.type = automatic_type_conversion(return_type);
7756
7757         rem_anchor_token(']');
7758         expect(']');
7759 end_error:
7760         return expression;
7761 }
7762
7763 static expression_t *parse_typeprop(expression_kind_t const kind)
7764 {
7765         expression_t  *tp_expression = allocate_expression_zero(kind);
7766         tp_expression->base.type     = type_size_t;
7767
7768         eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7769
7770         /* we only refer to a type property, mark this case */
7771         bool old     = in_type_prop;
7772         in_type_prop = true;
7773
7774         type_t       *orig_type;
7775         expression_t *expression;
7776         if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7777                 next_token();
7778                 add_anchor_token(')');
7779                 orig_type = parse_typename();
7780                 rem_anchor_token(')');
7781                 expect(')');
7782
7783                 if (token.type == '{') {
7784                         /* It was not sizeof(type) after all.  It is sizeof of an expression
7785                          * starting with a compound literal */
7786                         expression = parse_compound_literal(orig_type);
7787                         goto typeprop_expression;
7788                 }
7789         } else {
7790                 expression = parse_sub_expression(PREC_UNARY);
7791
7792 typeprop_expression:
7793                 tp_expression->typeprop.tp_expression = expression;
7794
7795                 orig_type = revert_automatic_type_conversion(expression);
7796                 expression->base.type = orig_type;
7797         }
7798
7799         tp_expression->typeprop.type   = orig_type;
7800         type_t const* const type       = skip_typeref(orig_type);
7801         char   const* const wrong_type =
7802                 is_type_incomplete(type)    ? "incomplete"          :
7803                 type->kind == TYPE_FUNCTION ? "function designator" :
7804                 type->kind == TYPE_BITFIELD ? "bitfield"            :
7805                 NULL;
7806         if (wrong_type != NULL) {
7807                 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7808                 errorf(&tp_expression->base.source_position,
7809                                 "operand of %s expression must not be of %s type '%T'",
7810                                 what, wrong_type, orig_type);
7811         }
7812
7813 end_error:
7814         in_type_prop = old;
7815         return tp_expression;
7816 }
7817
7818 static expression_t *parse_sizeof(void)
7819 {
7820         return parse_typeprop(EXPR_SIZEOF);
7821 }
7822
7823 static expression_t *parse_alignof(void)
7824 {
7825         return parse_typeprop(EXPR_ALIGNOF);
7826 }
7827
7828 static expression_t *parse_select_expression(expression_t *compound)
7829 {
7830         expression_t *select    = allocate_expression_zero(EXPR_SELECT);
7831         select->select.compound = compound;
7832
7833         assert(token.type == '.' || token.type == T_MINUSGREATER);
7834         bool is_pointer = (token.type == T_MINUSGREATER);
7835         next_token();
7836
7837         if (token.type != T_IDENTIFIER) {
7838                 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7839                 return select;
7840         }
7841         symbol_t *symbol = token.v.symbol;
7842         next_token();
7843
7844         type_t *const orig_type = compound->base.type;
7845         type_t *const type      = skip_typeref(orig_type);
7846
7847         type_t *type_left;
7848         bool    saw_error = false;
7849         if (is_type_pointer(type)) {
7850                 if (!is_pointer) {
7851                         errorf(HERE,
7852                                "request for member '%Y' in something not a struct or union, but '%T'",
7853                                symbol, orig_type);
7854                         saw_error = true;
7855                 }
7856                 type_left = skip_typeref(type->pointer.points_to);
7857         } else {
7858                 if (is_pointer && is_type_valid(type)) {
7859                         errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7860                         saw_error = true;
7861                 }
7862                 type_left = type;
7863         }
7864
7865         entity_t *entry;
7866         if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7867             type_left->kind == TYPE_COMPOUND_UNION) {
7868                 compound_t *compound = type_left->compound.compound;
7869
7870                 if (!compound->complete) {
7871                         errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7872                                symbol, type_left);
7873                         goto create_error_entry;
7874                 }
7875
7876                 entry = find_compound_entry(compound, symbol);
7877                 if (entry == NULL) {
7878                         errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7879                         goto create_error_entry;
7880                 }
7881         } else {
7882                 if (is_type_valid(type_left) && !saw_error) {
7883                         errorf(HERE,
7884                                "request for member '%Y' in something not a struct or union, but '%T'",
7885                                symbol, type_left);
7886                 }
7887 create_error_entry:
7888                 return create_invalid_expression();
7889         }
7890
7891         assert(is_declaration(entry));
7892         select->select.compound_entry = entry;
7893
7894         type_t *entry_type = entry->declaration.type;
7895         type_t *res_type
7896                 = get_qualified_type(entry_type, type_left->base.qualifiers);
7897
7898         /* we always do the auto-type conversions; the & and sizeof parser contains
7899          * code to revert this! */
7900         select->base.type = automatic_type_conversion(res_type);
7901
7902         type_t *skipped = skip_typeref(res_type);
7903         if (skipped->kind == TYPE_BITFIELD) {
7904                 select->base.type = skipped->bitfield.base_type;
7905         }
7906
7907         return select;
7908 }
7909
7910 static void check_call_argument(const function_parameter_t *parameter,
7911                                 call_argument_t *argument, unsigned pos)
7912 {
7913         type_t         *expected_type      = parameter->type;
7914         type_t         *expected_type_skip = skip_typeref(expected_type);
7915         assign_error_t  error              = ASSIGN_ERROR_INCOMPATIBLE;
7916         expression_t   *arg_expr           = argument->expression;
7917         type_t         *arg_type           = skip_typeref(arg_expr->base.type);
7918
7919         /* handle transparent union gnu extension */
7920         if (is_type_union(expected_type_skip)
7921                         && (expected_type_skip->base.modifiers
7922                                 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7923                 compound_t *union_decl  = expected_type_skip->compound.compound;
7924                 type_t     *best_type   = NULL;
7925                 entity_t   *entry       = union_decl->members.entities;
7926                 for ( ; entry != NULL; entry = entry->base.next) {
7927                         assert(is_declaration(entry));
7928                         type_t *decl_type = entry->declaration.type;
7929                         error = semantic_assign(decl_type, arg_expr);
7930                         if (error == ASSIGN_ERROR_INCOMPATIBLE
7931                                 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7932                                 continue;
7933
7934                         if (error == ASSIGN_SUCCESS) {
7935                                 best_type = decl_type;
7936                         } else if (best_type == NULL) {
7937                                 best_type = decl_type;
7938                         }
7939                 }
7940
7941                 if (best_type != NULL) {
7942                         expected_type = best_type;
7943                 }
7944         }
7945
7946         error                = semantic_assign(expected_type, arg_expr);
7947         argument->expression = create_implicit_cast(argument->expression,
7948                                                     expected_type);
7949
7950         if (error != ASSIGN_SUCCESS) {
7951                 /* report exact scope in error messages (like "in argument 3") */
7952                 char buf[64];
7953                 snprintf(buf, sizeof(buf), "call argument %u", pos);
7954                 report_assign_error(error, expected_type, arg_expr,     buf,
7955                                                         &arg_expr->base.source_position);
7956         } else if (warning.traditional || warning.conversion) {
7957                 type_t *const promoted_type = get_default_promoted_type(arg_type);
7958                 if (!types_compatible(expected_type_skip, promoted_type) &&
7959                     !types_compatible(expected_type_skip, type_void_ptr) &&
7960                     !types_compatible(type_void_ptr,      promoted_type)) {
7961                         /* Deliberately show the skipped types in this warning */
7962                         warningf(&arg_expr->base.source_position,
7963                                 "passing call argument %u as '%T' rather than '%T' due to prototype",
7964                                 pos, expected_type_skip, promoted_type);
7965                 }
7966         }
7967 }
7968
7969 /**
7970  * Parse a call expression, ie. expression '( ... )'.
7971  *
7972  * @param expression  the function address
7973  */
7974 static expression_t *parse_call_expression(expression_t *expression)
7975 {
7976         expression_t      *result = allocate_expression_zero(EXPR_CALL);
7977         call_expression_t *call   = &result->call;
7978         call->function            = expression;
7979
7980         type_t *const orig_type = expression->base.type;
7981         type_t *const type      = skip_typeref(orig_type);
7982
7983         function_type_t *function_type = NULL;
7984         if (is_type_pointer(type)) {
7985                 type_t *const to_type = skip_typeref(type->pointer.points_to);
7986
7987                 if (is_type_function(to_type)) {
7988                         function_type   = &to_type->function;
7989                         call->base.type = function_type->return_type;
7990                 }
7991         }
7992
7993         if (function_type == NULL && is_type_valid(type)) {
7994                 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7995         }
7996
7997         /* parse arguments */
7998         eat('(');
7999         add_anchor_token(')');
8000         add_anchor_token(',');
8001
8002         if (token.type != ')') {
8003                 call_argument_t *last_argument = NULL;
8004
8005                 while (true) {
8006                         call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8007
8008                         argument->expression = parse_assignment_expression();
8009                         if (last_argument == NULL) {
8010                                 call->arguments = argument;
8011                         } else {
8012                                 last_argument->next = argument;
8013                         }
8014                         last_argument = argument;
8015
8016                         if (token.type != ',')
8017                                 break;
8018                         next_token();
8019                 }
8020         }
8021         rem_anchor_token(',');
8022         rem_anchor_token(')');
8023         expect(')');
8024
8025         if (function_type == NULL)
8026                 return result;
8027
8028         function_parameter_t *parameter = function_type->parameters;
8029         call_argument_t      *argument  = call->arguments;
8030         if (!function_type->unspecified_parameters) {
8031                 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8032                                 parameter = parameter->next, argument = argument->next) {
8033                         check_call_argument(parameter, argument, ++pos);
8034                 }
8035
8036                 if (parameter != NULL) {
8037                         errorf(HERE, "too few arguments to function '%E'", expression);
8038                 } else if (argument != NULL && !function_type->variadic) {
8039                         errorf(HERE, "too many arguments to function '%E'", expression);
8040                 }
8041         }
8042
8043         /* do default promotion */
8044         for (; argument != NULL; argument = argument->next) {
8045                 type_t *type = argument->expression->base.type;
8046
8047                 type = get_default_promoted_type(type);
8048
8049                 argument->expression
8050                         = create_implicit_cast(argument->expression, type);
8051         }
8052
8053         check_format(&result->call);
8054
8055         if (warning.aggregate_return &&
8056             is_type_compound(skip_typeref(function_type->return_type))) {
8057                 warningf(&result->base.source_position,
8058                          "function call has aggregate value");
8059         }
8060
8061 end_error:
8062         return result;
8063 }
8064
8065 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8066
8067 static bool same_compound_type(const type_t *type1, const type_t *type2)
8068 {
8069         return
8070                 is_type_compound(type1) &&
8071                 type1->kind == type2->kind &&
8072                 type1->compound.compound == type2->compound.compound;
8073 }
8074
8075 static expression_t const *get_reference_address(expression_t const *expr)
8076 {
8077         bool regular_take_address = true;
8078         for (;;) {
8079                 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8080                         expr = expr->unary.value;
8081                 } else {
8082                         regular_take_address = false;
8083                 }
8084
8085                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8086                         break;
8087
8088                 expr = expr->unary.value;
8089         }
8090
8091         if (expr->kind != EXPR_REFERENCE)
8092                 return NULL;
8093
8094         /* special case for functions which are automatically converted to a
8095          * pointer to function without an extra TAKE_ADDRESS operation */
8096         if (!regular_take_address &&
8097                         expr->reference.entity->kind != ENTITY_FUNCTION) {
8098                 return NULL;
8099         }
8100
8101         return expr;
8102 }
8103
8104 static void warn_reference_address_as_bool(expression_t const* expr)
8105 {
8106         if (!warning.address)
8107                 return;
8108
8109         expr = get_reference_address(expr);
8110         if (expr != NULL) {
8111                 warningf(&expr->base.source_position,
8112                          "the address of '%Y' will always evaluate as 'true'",
8113                          expr->reference.entity->base.symbol);
8114         }
8115 }
8116
8117 static void semantic_condition(expression_t const *const expr,
8118                                char const *const context)
8119 {
8120         type_t *const type = skip_typeref(expr->base.type);
8121         if (is_type_scalar(type)) {
8122                 warn_reference_address_as_bool(expr);
8123         } else if (is_type_valid(type)) {
8124                 errorf(&expr->base.source_position,
8125                                 "%s must have scalar type", context);
8126         }
8127 }
8128
8129 /**
8130  * Parse a conditional expression, ie. 'expression ? ... : ...'.
8131  *
8132  * @param expression  the conditional expression
8133  */
8134 static expression_t *parse_conditional_expression(expression_t *expression)
8135 {
8136         expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8137
8138         conditional_expression_t *conditional = &result->conditional;
8139         conditional->condition                = expression;
8140
8141         eat('?');
8142         add_anchor_token(':');
8143
8144         /* Â§6.5.15:2  The first operand shall have scalar type. */
8145         semantic_condition(expression, "condition of conditional operator");
8146
8147         expression_t *true_expression = expression;
8148         bool          gnu_cond = false;
8149         if (GNU_MODE && token.type == ':') {
8150                 gnu_cond = true;
8151         } else {
8152                 true_expression = parse_expression();
8153         }
8154         rem_anchor_token(':');
8155         expect(':');
8156         expression_t *false_expression =
8157                 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8158
8159         type_t *const orig_true_type  = true_expression->base.type;
8160         type_t *const orig_false_type = false_expression->base.type;
8161         type_t *const true_type       = skip_typeref(orig_true_type);
8162         type_t *const false_type      = skip_typeref(orig_false_type);
8163
8164         /* 6.5.15.3 */
8165         type_t *result_type;
8166         if (is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8167                         is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8168                 /* ISO/IEC 14882:1998(E) Â§5.16:2 */
8169                 if (true_expression->kind == EXPR_UNARY_THROW) {
8170                         result_type = false_type;
8171                 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8172                         result_type = true_type;
8173                 } else {
8174                         if (warning.other && (
8175                                                 !is_type_atomic(true_type,  ATOMIC_TYPE_VOID) ||
8176                                                 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8177                                         )) {
8178                                 warningf(&conditional->base.source_position,
8179                                                 "ISO C forbids conditional expression with only one void side");
8180                         }
8181                         result_type = type_void;
8182                 }
8183         } else if (is_type_arithmetic(true_type)
8184                    && is_type_arithmetic(false_type)) {
8185                 result_type = semantic_arithmetic(true_type, false_type);
8186
8187                 true_expression  = create_implicit_cast(true_expression, result_type);
8188                 false_expression = create_implicit_cast(false_expression, result_type);
8189
8190                 conditional->true_expression  = true_expression;
8191                 conditional->false_expression = false_expression;
8192                 conditional->base.type        = result_type;
8193         } else if (same_compound_type(true_type, false_type)) {
8194                 /* just take 1 of the 2 types */
8195                 result_type = true_type;
8196         } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8197                 type_t *pointer_type;
8198                 type_t *other_type;
8199                 expression_t *other_expression;
8200                 if (is_type_pointer(true_type) &&
8201                                 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8202                         pointer_type     = true_type;
8203                         other_type       = false_type;
8204                         other_expression = false_expression;
8205                 } else {
8206                         pointer_type     = false_type;
8207                         other_type       = true_type;
8208                         other_expression = true_expression;
8209                 }
8210
8211                 if (is_null_pointer_constant(other_expression)) {
8212                         result_type = pointer_type;
8213                 } else if (is_type_pointer(other_type)) {
8214                         type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8215                         type_t *to2 = skip_typeref(other_type->pointer.points_to);
8216
8217                         type_t *to;
8218                         if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8219                             is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8220                                 to = type_void;
8221                         } else if (types_compatible(get_unqualified_type(to1),
8222                                                     get_unqualified_type(to2))) {
8223                                 to = to1;
8224                         } else {
8225                                 if (warning.other) {
8226                                         warningf(&conditional->base.source_position,
8227                                                         "pointer types '%T' and '%T' in conditional expression are incompatible",
8228                                                         true_type, false_type);
8229                                 }
8230                                 to = type_void;
8231                         }
8232
8233                         type_t *const type =
8234                                 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8235                         result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8236                 } else if (is_type_integer(other_type)) {
8237                         if (warning.other) {
8238                                 warningf(&conditional->base.source_position,
8239                                                 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8240                         }
8241                         result_type = pointer_type;
8242                 } else {
8243                         if (is_type_valid(other_type)) {
8244                                 type_error_incompatible("while parsing conditional",
8245                                                 &expression->base.source_position, true_type, false_type);
8246                         }
8247                         result_type = type_error_type;
8248                 }
8249         } else {
8250                 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8251                         type_error_incompatible("while parsing conditional",
8252                                                 &conditional->base.source_position, true_type,
8253                                                 false_type);
8254                 }
8255                 result_type = type_error_type;
8256         }
8257
8258         conditional->true_expression
8259                 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8260         conditional->false_expression
8261                 = create_implicit_cast(false_expression, result_type);
8262         conditional->base.type = result_type;
8263         return result;
8264 end_error:
8265         return create_invalid_expression();
8266 }
8267
8268 /**
8269  * Parse an extension expression.
8270  */
8271 static expression_t *parse_extension(void)
8272 {
8273         eat(T___extension__);
8274
8275         bool old_gcc_extension   = in_gcc_extension;
8276         in_gcc_extension         = true;
8277         expression_t *expression = parse_sub_expression(PREC_UNARY);
8278         in_gcc_extension         = old_gcc_extension;
8279         return expression;
8280 }
8281
8282 /**
8283  * Parse a __builtin_classify_type() expression.
8284  */
8285 static expression_t *parse_builtin_classify_type(void)
8286 {
8287         expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8288         result->base.type    = type_int;
8289
8290         eat(T___builtin_classify_type);
8291
8292         expect('(');
8293         add_anchor_token(')');
8294         expression_t *expression = parse_expression();
8295         rem_anchor_token(')');
8296         expect(')');
8297         result->classify_type.type_expression = expression;
8298
8299         return result;
8300 end_error:
8301         return create_invalid_expression();
8302 }
8303
8304 /**
8305  * Parse a delete expression
8306  * ISO/IEC 14882:1998(E) Â§5.3.5
8307  */
8308 static expression_t *parse_delete(void)
8309 {
8310         expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8311         result->base.type          = type_void;
8312
8313         eat(T_delete);
8314
8315         if (token.type == '[') {
8316                 next_token();
8317                 result->kind = EXPR_UNARY_DELETE_ARRAY;
8318                 expect(']');
8319 end_error:;
8320         }
8321
8322         expression_t *const value = parse_sub_expression(PREC_CAST);
8323         result->unary.value = value;
8324
8325         type_t *const type = skip_typeref(value->base.type);
8326         if (!is_type_pointer(type)) {
8327                 errorf(&value->base.source_position,
8328                                 "operand of delete must have pointer type");
8329         } else if (warning.other &&
8330                         is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8331                 warningf(&value->base.source_position,
8332                                 "deleting 'void*' is undefined");
8333         }
8334
8335         return result;
8336 }
8337
8338 /**
8339  * Parse a throw expression
8340  * ISO/IEC 14882:1998(E) Â§15:1
8341  */
8342 static expression_t *parse_throw(void)
8343 {
8344         expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8345         result->base.type          = type_void;
8346
8347         eat(T_throw);
8348
8349         expression_t *value = NULL;
8350         switch (token.type) {
8351                 EXPRESSION_START {
8352                         value = parse_assignment_expression();
8353                         /* ISO/IEC 14882:1998(E) Â§15.1:3 */
8354                         type_t *const orig_type = value->base.type;
8355                         type_t *const type      = skip_typeref(orig_type);
8356                         if (is_type_incomplete(type)) {
8357                                 errorf(&value->base.source_position,
8358                                                 "cannot throw object of incomplete type '%T'", orig_type);
8359                         } else if (is_type_pointer(type)) {
8360                                 type_t *const points_to = skip_typeref(type->pointer.points_to);
8361                                 if (is_type_incomplete(points_to) &&
8362                                                 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8363                                         errorf(&value->base.source_position,
8364                                                         "cannot throw pointer to incomplete type '%T'", orig_type);
8365                                 }
8366                         }
8367                 }
8368
8369                 default:
8370                         break;
8371         }
8372         result->unary.value = value;
8373
8374         return result;
8375 }
8376
8377 static bool check_pointer_arithmetic(const source_position_t *source_position,
8378                                      type_t *pointer_type,
8379                                      type_t *orig_pointer_type)
8380 {
8381         type_t *points_to = pointer_type->pointer.points_to;
8382         points_to = skip_typeref(points_to);
8383
8384         if (is_type_incomplete(points_to)) {
8385                 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8386                         errorf(source_position,
8387                                "arithmetic with pointer to incomplete type '%T' not allowed",
8388                                orig_pointer_type);
8389                         return false;
8390                 } else if (warning.pointer_arith) {
8391                         warningf(source_position,
8392                                  "pointer of type '%T' used in arithmetic",
8393                                  orig_pointer_type);
8394                 }
8395         } else if (is_type_function(points_to)) {
8396                 if (!GNU_MODE) {
8397                         errorf(source_position,
8398                                "arithmetic with pointer to function type '%T' not allowed",
8399                                orig_pointer_type);
8400                         return false;
8401                 } else if (warning.pointer_arith) {
8402                         warningf(source_position,
8403                                  "pointer to a function '%T' used in arithmetic",
8404                                  orig_pointer_type);
8405                 }
8406         }
8407         return true;
8408 }
8409
8410 static bool is_lvalue(const expression_t *expression)
8411 {
8412         /* TODO: doesn't seem to be consistent with Â§6.3.2.1 (1) */
8413         switch (expression->kind) {
8414         case EXPR_REFERENCE:
8415         case EXPR_ARRAY_ACCESS:
8416         case EXPR_SELECT:
8417         case EXPR_UNARY_DEREFERENCE:
8418                 return true;
8419
8420         default: {
8421           type_t *type = skip_typeref(expression->base.type);
8422           return
8423                 /* ISO/IEC 14882:1998(E) Â§3.10:3 */
8424                 is_type_reference(type) ||
8425                 /* Claim it is an lvalue, if the type is invalid.  There was a parse
8426                  * error before, which maybe prevented properly recognizing it as
8427                  * lvalue. */
8428                 !is_type_valid(type);
8429         }
8430         }
8431 }
8432
8433 static void semantic_incdec(unary_expression_t *expression)
8434 {
8435         type_t *const orig_type = expression->value->base.type;
8436         type_t *const type      = skip_typeref(orig_type);
8437         if (is_type_pointer(type)) {
8438                 if (!check_pointer_arithmetic(&expression->base.source_position,
8439                                               type, orig_type)) {
8440                         return;
8441                 }
8442         } else if (!is_type_real(type) && is_type_valid(type)) {
8443                 /* TODO: improve error message */
8444                 errorf(&expression->base.source_position,
8445                        "operation needs an arithmetic or pointer type");
8446                 return;
8447         }
8448         if (!is_lvalue(expression->value)) {
8449                 /* TODO: improve error message */
8450                 errorf(&expression->base.source_position, "lvalue required as operand");
8451         }
8452         expression->base.type = orig_type;
8453 }
8454
8455 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8456 {
8457         type_t *const orig_type = expression->value->base.type;
8458         type_t *const type      = skip_typeref(orig_type);
8459         if (!is_type_arithmetic(type)) {
8460                 if (is_type_valid(type)) {
8461                         /* TODO: improve error message */
8462                         errorf(&expression->base.source_position,
8463                                 "operation needs an arithmetic type");
8464                 }
8465                 return;
8466         }
8467
8468         expression->base.type = orig_type;
8469 }
8470
8471 static void semantic_unexpr_plus(unary_expression_t *expression)
8472 {
8473         semantic_unexpr_arithmetic(expression);
8474         if (warning.traditional)
8475                 warningf(&expression->base.source_position,
8476                         "traditional C rejects the unary plus operator");
8477 }
8478
8479 static void semantic_not(unary_expression_t *expression)
8480 {
8481         /* Â§6.5.3.3:1  The operand [...] of the ! operator, scalar type. */
8482         semantic_condition(expression->value, "operand of !");
8483         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8484 }
8485
8486 static void semantic_unexpr_integer(unary_expression_t *expression)
8487 {
8488         type_t *const orig_type = expression->value->base.type;
8489         type_t *const type      = skip_typeref(orig_type);
8490         if (!is_type_integer(type)) {
8491                 if (is_type_valid(type)) {
8492                         errorf(&expression->base.source_position,
8493                                "operand of ~ must be of integer type");
8494                 }
8495                 return;
8496         }
8497
8498         expression->base.type = orig_type;
8499 }
8500
8501 static void semantic_dereference(unary_expression_t *expression)
8502 {
8503         type_t *const orig_type = expression->value->base.type;
8504         type_t *const type      = skip_typeref(orig_type);
8505         if (!is_type_pointer(type)) {
8506                 if (is_type_valid(type)) {
8507                         errorf(&expression->base.source_position,
8508                                "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8509                 }
8510                 return;
8511         }
8512
8513         type_t *result_type   = type->pointer.points_to;
8514         result_type           = automatic_type_conversion(result_type);
8515         expression->base.type = result_type;
8516 }
8517
8518 /**
8519  * Record that an address is taken (expression represents an lvalue).
8520  *
8521  * @param expression       the expression
8522  * @param may_be_register  if true, the expression might be an register
8523  */
8524 static void set_address_taken(expression_t *expression, bool may_be_register)
8525 {
8526         if (expression->kind != EXPR_REFERENCE)
8527                 return;
8528
8529         entity_t *const entity = expression->reference.entity;
8530
8531         if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8532                 return;
8533
8534         if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8535                         && !may_be_register) {
8536                 errorf(&expression->base.source_position,
8537                                 "address of register %s '%Y' requested",
8538                                 get_entity_kind_name(entity->kind),     entity->base.symbol);
8539         }
8540
8541         if (entity->kind == ENTITY_VARIABLE) {
8542                 entity->variable.address_taken = true;
8543         } else {
8544                 assert(entity->kind == ENTITY_PARAMETER);
8545                 entity->parameter.address_taken = true;
8546         }
8547 }
8548
8549 /**
8550  * Check the semantic of the address taken expression.
8551  */
8552 static void semantic_take_addr(unary_expression_t *expression)
8553 {
8554         expression_t *value = expression->value;
8555         value->base.type    = revert_automatic_type_conversion(value);
8556
8557         type_t *orig_type = value->base.type;
8558         type_t *type      = skip_typeref(orig_type);
8559         if (!is_type_valid(type))
8560                 return;
8561
8562         /* Â§6.5.3.2 */
8563         if (!is_lvalue(value)) {
8564                 errorf(&expression->base.source_position, "'&' requires an lvalue");
8565         }
8566         if (type->kind == TYPE_BITFIELD) {
8567                 errorf(&expression->base.source_position,
8568                        "'&' not allowed on object with bitfield type '%T'",
8569                        type);
8570         }
8571
8572         set_address_taken(value, false);
8573
8574         expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8575 }
8576
8577 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8578 static expression_t *parse_##unexpression_type(void)                         \
8579 {                                                                            \
8580         expression_t *unary_expression                                           \
8581                 = allocate_expression_zero(unexpression_type);                       \
8582         eat(token_type);                                                         \
8583         unary_expression->unary.value = parse_sub_expression(PREC_UNARY);        \
8584                                                                                  \
8585         sfunc(&unary_expression->unary);                                         \
8586                                                                                  \
8587         return unary_expression;                                                 \
8588 }
8589
8590 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8591                                semantic_unexpr_arithmetic)
8592 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8593                                semantic_unexpr_plus)
8594 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8595                                semantic_not)
8596 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8597                                semantic_dereference)
8598 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8599                                semantic_take_addr)
8600 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8601                                semantic_unexpr_integer)
8602 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS,   EXPR_UNARY_PREFIX_INCREMENT,
8603                                semantic_incdec)
8604 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8605                                semantic_incdec)
8606
8607 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8608                                                sfunc)                         \
8609 static expression_t *parse_##unexpression_type(expression_t *left)            \
8610 {                                                                             \
8611         expression_t *unary_expression                                            \
8612                 = allocate_expression_zero(unexpression_type);                        \
8613         eat(token_type);                                                          \
8614         unary_expression->unary.value = left;                                     \
8615                                                                                   \
8616         sfunc(&unary_expression->unary);                                          \
8617                                                                               \
8618         return unary_expression;                                                  \
8619 }
8620
8621 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8622                                        EXPR_UNARY_POSTFIX_INCREMENT,
8623                                        semantic_incdec)
8624 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8625                                        EXPR_UNARY_POSTFIX_DECREMENT,
8626                                        semantic_incdec)
8627
8628 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8629 {
8630         /* TODO: handle complex + imaginary types */
8631
8632         type_left  = get_unqualified_type(type_left);
8633         type_right = get_unqualified_type(type_right);
8634
8635         /* Â§ 6.3.1.8 Usual arithmetic conversions */
8636         if (type_left == type_long_double || type_right == type_long_double) {
8637                 return type_long_double;
8638         } else if (type_left == type_double || type_right == type_double) {
8639                 return type_double;
8640         } else if (type_left == type_float || type_right == type_float) {
8641                 return type_float;
8642         }
8643
8644         type_left  = promote_integer(type_left);
8645         type_right = promote_integer(type_right);
8646
8647         if (type_left == type_right)
8648                 return type_left;
8649
8650         bool const signed_left  = is_type_signed(type_left);
8651         bool const signed_right = is_type_signed(type_right);
8652         int const  rank_left    = get_rank(type_left);
8653         int const  rank_right   = get_rank(type_right);
8654
8655         if (signed_left == signed_right)
8656                 return rank_left >= rank_right ? type_left : type_right;
8657
8658         int     s_rank;
8659         int     u_rank;
8660         type_t *s_type;
8661         type_t *u_type;
8662         if (signed_left) {
8663                 s_rank = rank_left;
8664                 s_type = type_left;
8665                 u_rank = rank_right;
8666                 u_type = type_right;
8667         } else {
8668                 s_rank = rank_right;
8669                 s_type = type_right;
8670                 u_rank = rank_left;
8671                 u_type = type_left;
8672         }
8673
8674         if (u_rank >= s_rank)
8675                 return u_type;
8676
8677         /* casting rank to atomic_type_kind is a bit hacky, but makes things
8678          * easier here... */
8679         if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8680                         > get_atomic_type_size((atomic_type_kind_t) u_rank))
8681                 return s_type;
8682
8683         switch (s_rank) {
8684                 case ATOMIC_TYPE_INT:      return type_unsigned_int;
8685                 case ATOMIC_TYPE_LONG:     return type_unsigned_long;
8686                 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8687
8688                 default: panic("invalid atomic type");
8689         }
8690 }
8691
8692 /**
8693  * Check the semantic restrictions for a binary expression.
8694  */
8695 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8696 {
8697         expression_t *const left            = expression->left;
8698         expression_t *const right           = expression->right;
8699         type_t       *const orig_type_left  = left->base.type;
8700         type_t       *const orig_type_right = right->base.type;
8701         type_t       *const type_left       = skip_typeref(orig_type_left);
8702         type_t       *const type_right      = skip_typeref(orig_type_right);
8703
8704         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8705                 /* TODO: improve error message */
8706                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8707                         errorf(&expression->base.source_position,
8708                                "operation needs arithmetic types");
8709                 }
8710                 return;
8711         }
8712
8713         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8714         expression->left      = create_implicit_cast(left, arithmetic_type);
8715         expression->right     = create_implicit_cast(right, arithmetic_type);
8716         expression->base.type = arithmetic_type;
8717 }
8718
8719 static void warn_div_by_zero(binary_expression_t const *const expression)
8720 {
8721         if (!warning.div_by_zero ||
8722             !is_type_integer(expression->base.type))
8723                 return;
8724
8725         expression_t const *const right = expression->right;
8726         /* The type of the right operand can be different for /= */
8727         if (is_type_integer(right->base.type) &&
8728             is_constant_expression(right)     &&
8729             fold_constant(right) == 0) {
8730                 warningf(&expression->base.source_position, "division by zero");
8731         }
8732 }
8733
8734 /**
8735  * Check the semantic restrictions for a div/mod expression.
8736  */
8737 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8738         semantic_binexpr_arithmetic(expression);
8739         warn_div_by_zero(expression);
8740 }
8741
8742 static void semantic_shift_op(binary_expression_t *expression)
8743 {
8744         expression_t *const left            = expression->left;
8745         expression_t *const right           = expression->right;
8746         type_t       *const orig_type_left  = left->base.type;
8747         type_t       *const orig_type_right = right->base.type;
8748         type_t       *      type_left       = skip_typeref(orig_type_left);
8749         type_t       *      type_right      = skip_typeref(orig_type_right);
8750
8751         if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8752                 /* TODO: improve error message */
8753                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8754                         errorf(&expression->base.source_position,
8755                                "operands of shift operation must have integer types");
8756                 }
8757                 return;
8758         }
8759
8760         type_left  = promote_integer(type_left);
8761         type_right = promote_integer(type_right);
8762
8763         expression->left      = create_implicit_cast(left, type_left);
8764         expression->right     = create_implicit_cast(right, type_right);
8765         expression->base.type = type_left;
8766 }
8767
8768 static void semantic_add(binary_expression_t *expression)
8769 {
8770         expression_t *const left            = expression->left;
8771         expression_t *const right           = expression->right;
8772         type_t       *const orig_type_left  = left->base.type;
8773         type_t       *const orig_type_right = right->base.type;
8774         type_t       *const type_left       = skip_typeref(orig_type_left);
8775         type_t       *const type_right      = skip_typeref(orig_type_right);
8776
8777         /* Â§ 6.5.6 */
8778         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8779                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8780                 expression->left  = create_implicit_cast(left, arithmetic_type);
8781                 expression->right = create_implicit_cast(right, arithmetic_type);
8782                 expression->base.type = arithmetic_type;
8783                 return;
8784         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8785                 check_pointer_arithmetic(&expression->base.source_position,
8786                                          type_left, orig_type_left);
8787                 expression->base.type = type_left;
8788         } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8789                 check_pointer_arithmetic(&expression->base.source_position,
8790                                          type_right, orig_type_right);
8791                 expression->base.type = type_right;
8792         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8793                 errorf(&expression->base.source_position,
8794                        "invalid operands to binary + ('%T', '%T')",
8795                        orig_type_left, orig_type_right);
8796         }
8797 }
8798
8799 static void semantic_sub(binary_expression_t *expression)
8800 {
8801         expression_t            *const left            = expression->left;
8802         expression_t            *const right           = expression->right;
8803         type_t                  *const orig_type_left  = left->base.type;
8804         type_t                  *const orig_type_right = right->base.type;
8805         type_t                  *const type_left       = skip_typeref(orig_type_left);
8806         type_t                  *const type_right      = skip_typeref(orig_type_right);
8807         source_position_t const *const pos             = &expression->base.source_position;
8808
8809         /* Â§ 5.6.5 */
8810         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8811                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8812                 expression->left        = create_implicit_cast(left, arithmetic_type);
8813                 expression->right       = create_implicit_cast(right, arithmetic_type);
8814                 expression->base.type =  arithmetic_type;
8815                 return;
8816         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8817                 check_pointer_arithmetic(&expression->base.source_position,
8818                                          type_left, orig_type_left);
8819                 expression->base.type = type_left;
8820         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8821                 type_t *const unqual_left  = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8822                 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8823                 if (!types_compatible(unqual_left, unqual_right)) {
8824                         errorf(pos,
8825                                "subtracting pointers to incompatible types '%T' and '%T'",
8826                                orig_type_left, orig_type_right);
8827                 } else if (!is_type_object(unqual_left)) {
8828                         if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8829                                 errorf(pos, "subtracting pointers to non-object types '%T'",
8830                                        orig_type_left);
8831                         } else if (warning.other) {
8832                                 warningf(pos, "subtracting pointers to void");
8833                         }
8834                 }
8835                 expression->base.type = type_ptrdiff_t;
8836         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8837                 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8838                        orig_type_left, orig_type_right);
8839         }
8840 }
8841
8842 static void warn_string_literal_address(expression_t const* expr)
8843 {
8844         while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8845                 expr = expr->unary.value;
8846                 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8847                         return;
8848                 expr = expr->unary.value;
8849         }
8850
8851         if (expr->kind == EXPR_STRING_LITERAL ||
8852             expr->kind == EXPR_WIDE_STRING_LITERAL) {
8853                 warningf(&expr->base.source_position,
8854                         "comparison with string literal results in unspecified behaviour");
8855         }
8856 }
8857
8858 /**
8859  * Check the semantics of comparison expressions.
8860  *
8861  * @param expression   The expression to check.
8862  */
8863 static void semantic_comparison(binary_expression_t *expression)
8864 {
8865         expression_t *left  = expression->left;
8866         expression_t *right = expression->right;
8867
8868         if (warning.address) {
8869                 warn_string_literal_address(left);
8870                 warn_string_literal_address(right);
8871
8872                 expression_t const* const func_left = get_reference_address(left);
8873                 if (func_left != NULL && is_null_pointer_constant(right)) {
8874                         warningf(&expression->base.source_position,
8875                                  "the address of '%Y' will never be NULL",
8876                                  func_left->reference.entity->base.symbol);
8877                 }
8878
8879                 expression_t const* const func_right = get_reference_address(right);
8880                 if (func_right != NULL && is_null_pointer_constant(right)) {
8881                         warningf(&expression->base.source_position,
8882                                  "the address of '%Y' will never be NULL",
8883                                  func_right->reference.entity->base.symbol);
8884                 }
8885         }
8886
8887         type_t *orig_type_left  = left->base.type;
8888         type_t *orig_type_right = right->base.type;
8889         type_t *type_left       = skip_typeref(orig_type_left);
8890         type_t *type_right      = skip_typeref(orig_type_right);
8891
8892         /* TODO non-arithmetic types */
8893         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8894                 /* test for signed vs unsigned compares */
8895                 if (warning.sign_compare &&
8896                     (expression->base.kind != EXPR_BINARY_EQUAL &&
8897                      expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8898                     (is_type_signed(type_left) != is_type_signed(type_right))) {
8899
8900                         /* check if 1 of the operands is a constant, in this case we just
8901                          * check wether we can safely represent the resulting constant in
8902                          * the type of the other operand. */
8903                         expression_t *const_expr = NULL;
8904                         expression_t *other_expr = NULL;
8905
8906                         if (is_constant_expression(left)) {
8907                                 const_expr = left;
8908                                 other_expr = right;
8909                         } else if (is_constant_expression(right)) {
8910                                 const_expr = right;
8911                                 other_expr = left;
8912                         }
8913
8914                         if (const_expr != NULL) {
8915                                 type_t *other_type = skip_typeref(other_expr->base.type);
8916                                 long    val        = fold_constant(const_expr);
8917                                 /* TODO: check if val can be represented by other_type */
8918                                 (void) other_type;
8919                                 (void) val;
8920                         }
8921                         warningf(&expression->base.source_position,
8922                                  "comparison between signed and unsigned");
8923                 }
8924                 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8925                 expression->left        = create_implicit_cast(left, arithmetic_type);
8926                 expression->right       = create_implicit_cast(right, arithmetic_type);
8927                 expression->base.type   = arithmetic_type;
8928                 if (warning.float_equal &&
8929                     (expression->base.kind == EXPR_BINARY_EQUAL ||
8930                      expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8931                     is_type_float(arithmetic_type)) {
8932                         warningf(&expression->base.source_position,
8933                                  "comparing floating point with == or != is unsafe");
8934                 }
8935         } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8936                 /* TODO check compatibility */
8937         } else if (is_type_pointer(type_left)) {
8938                 expression->right = create_implicit_cast(right, type_left);
8939         } else if (is_type_pointer(type_right)) {
8940                 expression->left = create_implicit_cast(left, type_right);
8941         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8942                 type_error_incompatible("invalid operands in comparison",
8943                                         &expression->base.source_position,
8944                                         type_left, type_right);
8945         }
8946         expression->base.type = c_mode & _CXX ? type_bool : type_int;
8947 }
8948
8949 /**
8950  * Checks if a compound type has constant fields.
8951  */
8952 static bool has_const_fields(const compound_type_t *type)
8953 {
8954         compound_t *compound = type->compound;
8955         entity_t   *entry    = compound->members.entities;
8956
8957         for (; entry != NULL; entry = entry->base.next) {
8958                 if (!is_declaration(entry))
8959                         continue;
8960
8961                 const type_t *decl_type = skip_typeref(entry->declaration.type);
8962                 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8963                         return true;
8964         }
8965
8966         return false;
8967 }
8968
8969 static bool is_valid_assignment_lhs(expression_t const* const left)
8970 {
8971         type_t *const orig_type_left = revert_automatic_type_conversion(left);
8972         type_t *const type_left      = skip_typeref(orig_type_left);
8973
8974         if (!is_lvalue(left)) {
8975                 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8976                        left);
8977                 return false;
8978         }
8979
8980         if (left->kind == EXPR_REFERENCE
8981                         && left->reference.entity->kind == ENTITY_FUNCTION) {
8982                 errorf(HERE, "cannot assign to function '%E'", left);
8983                 return false;
8984         }
8985
8986         if (is_type_array(type_left)) {
8987                 errorf(HERE, "cannot assign to array '%E'", left);
8988                 return false;
8989         }
8990         if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8991                 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8992                        orig_type_left);
8993                 return false;
8994         }
8995         if (is_type_incomplete(type_left)) {
8996                 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8997                        left, orig_type_left);
8998                 return false;
8999         }
9000         if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9001                 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9002                        left, orig_type_left);
9003                 return false;
9004         }
9005
9006         return true;
9007 }
9008
9009 static void semantic_arithmetic_assign(binary_expression_t *expression)
9010 {
9011         expression_t *left            = expression->left;
9012         expression_t *right           = expression->right;
9013         type_t       *orig_type_left  = left->base.type;
9014         type_t       *orig_type_right = right->base.type;
9015
9016         if (!is_valid_assignment_lhs(left))
9017                 return;
9018
9019         type_t *type_left  = skip_typeref(orig_type_left);
9020         type_t *type_right = skip_typeref(orig_type_right);
9021
9022         if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9023                 /* TODO: improve error message */
9024                 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9025                         errorf(&expression->base.source_position,
9026                                "operation needs arithmetic types");
9027                 }
9028                 return;
9029         }
9030
9031         /* combined instructions are tricky. We can't create an implicit cast on
9032          * the left side, because we need the uncasted form for the store.
9033          * The ast2firm pass has to know that left_type must be right_type
9034          * for the arithmetic operation and create a cast by itself */
9035         type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9036         expression->right       = create_implicit_cast(right, arithmetic_type);
9037         expression->base.type   = type_left;
9038 }
9039
9040 static void semantic_divmod_assign(binary_expression_t *expression)
9041 {
9042         semantic_arithmetic_assign(expression);
9043         warn_div_by_zero(expression);
9044 }
9045
9046 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9047 {
9048         expression_t *const left            = expression->left;
9049         expression_t *const right           = expression->right;
9050         type_t       *const orig_type_left  = left->base.type;
9051         type_t       *const orig_type_right = right->base.type;
9052         type_t       *const type_left       = skip_typeref(orig_type_left);
9053         type_t       *const type_right      = skip_typeref(orig_type_right);
9054
9055         if (!is_valid_assignment_lhs(left))
9056                 return;
9057
9058         if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9059                 /* combined instructions are tricky. We can't create an implicit cast on
9060                  * the left side, because we need the uncasted form for the store.
9061                  * The ast2firm pass has to know that left_type must be right_type
9062                  * for the arithmetic operation and create a cast by itself */
9063                 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9064                 expression->right     = create_implicit_cast(right, arithmetic_type);
9065                 expression->base.type = type_left;
9066         } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9067                 check_pointer_arithmetic(&expression->base.source_position,
9068                                          type_left, orig_type_left);
9069                 expression->base.type = type_left;
9070         } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9071                 errorf(&expression->base.source_position,
9072                        "incompatible types '%T' and '%T' in assignment",
9073                        orig_type_left, orig_type_right);
9074         }
9075 }
9076
9077 /**
9078  * Check the semantic restrictions of a logical expression.
9079  */
9080 static void semantic_logical_op(binary_expression_t *expression)
9081 {
9082         /* Â§6.5.13:2  Each of the operands shall have scalar type.
9083          * Â§6.5.14:2  Each of the operands shall have scalar type. */
9084         semantic_condition(expression->left,   "left operand of logical operator");
9085         semantic_condition(expression->right, "right operand of logical operator");
9086         expression->base.type = c_mode & _CXX ? type_bool : type_int;
9087 }
9088
9089 /**
9090  * Check the semantic restrictions of a binary assign expression.
9091  */
9092 static void semantic_binexpr_assign(binary_expression_t *expression)
9093 {
9094         expression_t *left           = expression->left;
9095         type_t       *orig_type_left = left->base.type;
9096
9097         if (!is_valid_assignment_lhs(left))
9098                 return;
9099
9100         assign_error_t error = semantic_assign(orig_type_left, expression->right);
9101         report_assign_error(error, orig_type_left, expression->right,
9102                         "assignment", &left->base.source_position);
9103         expression->right = create_implicit_cast(expression->right, orig_type_left);
9104         expression->base.type = orig_type_left;
9105 }
9106
9107 /**
9108  * Determine if the outermost operation (or parts thereof) of the given
9109  * expression has no effect in order to generate a warning about this fact.
9110  * Therefore in some cases this only examines some of the operands of the
9111  * expression (see comments in the function and examples below).
9112  * Examples:
9113  *   f() + 23;    // warning, because + has no effect
9114  *   x || f();    // no warning, because x controls execution of f()
9115  *   x ? y : f(); // warning, because y has no effect
9116  *   (void)x;     // no warning to be able to suppress the warning
9117  * This function can NOT be used for an "expression has definitely no effect"-
9118  * analysis. */
9119 static bool expression_has_effect(const expression_t *const expr)
9120 {
9121         switch (expr->kind) {
9122                 case EXPR_UNKNOWN:                   break;
9123                 case EXPR_INVALID:                   return true; /* do NOT warn */
9124                 case EXPR_REFERENCE:                 return false;
9125                 case EXPR_REFERENCE_ENUM_VALUE:      return false;
9126                 /* suppress the warning for microsoft __noop operations */
9127                 case EXPR_CONST:                     return expr->conste.is_ms_noop;
9128                 case EXPR_CHARACTER_CONSTANT:        return false;
9129                 case EXPR_WIDE_CHARACTER_CONSTANT:   return false;
9130                 case EXPR_STRING_LITERAL:            return false;
9131                 case EXPR_WIDE_STRING_LITERAL:       return false;
9132                 case EXPR_LABEL_ADDRESS:             return false;
9133
9134                 case EXPR_CALL: {
9135                         const call_expression_t *const call = &expr->call;
9136                         if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9137                                 return true;
9138
9139                         switch (call->function->builtin_symbol.symbol->ID) {
9140                                 case T___builtin_va_end: return true;
9141                                 default:                 return false;
9142                         }
9143                 }
9144
9145                 /* Generate the warning if either the left or right hand side of a
9146                  * conditional expression has no effect */
9147                 case EXPR_CONDITIONAL: {
9148                         const conditional_expression_t *const cond = &expr->conditional;
9149                         return
9150                                 expression_has_effect(cond->true_expression) &&
9151                                 expression_has_effect(cond->false_expression);
9152                 }
9153
9154                 case EXPR_SELECT:                    return false;
9155                 case EXPR_ARRAY_ACCESS:              return false;
9156                 case EXPR_SIZEOF:                    return false;
9157                 case EXPR_CLASSIFY_TYPE:             return false;
9158                 case EXPR_ALIGNOF:                   return false;
9159
9160                 case EXPR_FUNCNAME:                  return false;
9161                 case EXPR_BUILTIN_SYMBOL:            break; /* handled in EXPR_CALL */
9162                 case EXPR_BUILTIN_CONSTANT_P:        return false;
9163                 case EXPR_BUILTIN_PREFETCH:          return true;
9164                 case EXPR_OFFSETOF:                  return false;
9165                 case EXPR_VA_START:                  return true;
9166                 case EXPR_VA_ARG:                    return true;
9167                 case EXPR_STATEMENT:                 return true; // TODO
9168                 case EXPR_COMPOUND_LITERAL:          return false;
9169
9170                 case EXPR_UNARY_NEGATE:              return false;
9171                 case EXPR_UNARY_PLUS:                return false;
9172                 case EXPR_UNARY_BITWISE_NEGATE:      return false;
9173                 case EXPR_UNARY_NOT:                 return false;
9174                 case EXPR_UNARY_DEREFERENCE:         return false;
9175                 case EXPR_UNARY_TAKE_ADDRESS:        return false;
9176                 case EXPR_UNARY_POSTFIX_INCREMENT:   return true;
9177                 case EXPR_UNARY_POSTFIX_DECREMENT:   return true;
9178                 case EXPR_UNARY_PREFIX_INCREMENT:    return true;
9179                 case EXPR_UNARY_PREFIX_DECREMENT:    return true;
9180
9181                 /* Treat void casts as if they have an effect in order to being able to
9182                  * suppress the warning */
9183                 case EXPR_UNARY_CAST: {
9184                         type_t *const type = skip_typeref(expr->base.type);
9185                         return is_type_atomic(type, ATOMIC_TYPE_VOID);
9186                 }
9187
9188                 case EXPR_UNARY_CAST_IMPLICIT:       return true;
9189                 case EXPR_UNARY_ASSUME:              return true;
9190                 case EXPR_UNARY_DELETE:              return true;
9191                 case EXPR_UNARY_DELETE_ARRAY:        return true;
9192                 case EXPR_UNARY_THROW:               return true;
9193
9194                 case EXPR_BINARY_ADD:                return false;
9195                 case EXPR_BINARY_SUB:                return false;
9196                 case EXPR_BINARY_MUL:                return false;
9197                 case EXPR_BINARY_DIV:                return false;
9198                 case EXPR_BINARY_MOD:                return false;
9199                 case EXPR_BINARY_EQUAL:              return false;
9200                 case EXPR_BINARY_NOTEQUAL:           return false;
9201                 case EXPR_BINARY_LESS:               return false;
9202                 case EXPR_BINARY_LESSEQUAL:          return false;
9203                 case EXPR_BINARY_GREATER:            return false;
9204                 case EXPR_BINARY_GREATEREQUAL:       return false;
9205                 case EXPR_BINARY_BITWISE_AND:        return false;
9206                 case EXPR_BINARY_BITWISE_OR:         return false;
9207                 case EXPR_BINARY_BITWISE_XOR:        return false;
9208                 case EXPR_BINARY_SHIFTLEFT:          return false;
9209                 case EXPR_BINARY_SHIFTRIGHT:         return false;
9210                 case EXPR_BINARY_ASSIGN:             return true;
9211                 case EXPR_BINARY_MUL_ASSIGN:         return true;
9212                 case EXPR_BINARY_DIV_ASSIGN:         return true;
9213                 case EXPR_BINARY_MOD_ASSIGN:         return true;
9214                 case EXPR_BINARY_ADD_ASSIGN:         return true;
9215                 case EXPR_BINARY_SUB_ASSIGN:         return true;
9216                 case EXPR_BINARY_SHIFTLEFT_ASSIGN:   return true;
9217                 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:  return true;
9218                 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9219                 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9220                 case EXPR_BINARY_BITWISE_OR_ASSIGN:  return true;
9221
9222                 /* Only examine the right hand side of && and ||, because the left hand
9223                  * side already has the effect of controlling the execution of the right
9224                  * hand side */
9225                 case EXPR_BINARY_LOGICAL_AND:
9226                 case EXPR_BINARY_LOGICAL_OR:
9227                 /* Only examine the right hand side of a comma expression, because the left
9228                  * hand side has a separate warning */
9229                 case EXPR_BINARY_COMMA:
9230                         return expression_has_effect(expr->binary.right);
9231
9232                 case EXPR_BINARY_BUILTIN_EXPECT:     return true;
9233                 case EXPR_BINARY_ISGREATER:          return false;
9234                 case EXPR_BINARY_ISGREATEREQUAL:     return false;
9235                 case EXPR_BINARY_ISLESS:             return false;
9236                 case EXPR_BINARY_ISLESSEQUAL:        return false;
9237                 case EXPR_BINARY_ISLESSGREATER:      return false;
9238                 case EXPR_BINARY_ISUNORDERED:        return false;
9239         }
9240
9241         internal_errorf(HERE, "unexpected expression");
9242 }
9243
9244 static void semantic_comma(binary_expression_t *expression)
9245 {
9246         if (warning.unused_value) {
9247                 const expression_t *const left = expression->left;
9248                 if (!expression_has_effect(left)) {
9249                         warningf(&left->base.source_position,
9250                                  "left-hand operand of comma expression has no effect");
9251                 }
9252         }
9253         expression->base.type = expression->right->base.type;
9254 }
9255
9256 /**
9257  * @param prec_r precedence of the right operand
9258  */
9259 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9260 static expression_t *parse_##binexpression_type(expression_t *left)          \
9261 {                                                                            \
9262         expression_t *binexpr = allocate_expression_zero(binexpression_type);    \
9263         binexpr->binary.left  = left;                                            \
9264         eat(token_type);                                                         \
9265                                                                              \
9266         expression_t *right = parse_sub_expression(prec_r);                      \
9267                                                                              \
9268         binexpr->binary.right = right;                                           \
9269         sfunc(&binexpr->binary);                                                 \
9270                                                                              \
9271         return binexpr;                                                          \
9272 }
9273
9274 CREATE_BINEXPR_PARSER('*',                    EXPR_BINARY_MUL,                PREC_CAST,           semantic_binexpr_arithmetic)
9275 CREATE_BINEXPR_PARSER('/',                    EXPR_BINARY_DIV,                PREC_CAST,           semantic_divmod_arithmetic)
9276 CREATE_BINEXPR_PARSER('%',                    EXPR_BINARY_MOD,                PREC_CAST,           semantic_divmod_arithmetic)
9277 CREATE_BINEXPR_PARSER('+',                    EXPR_BINARY_ADD,                PREC_MULTIPLICATIVE, semantic_add)
9278 CREATE_BINEXPR_PARSER('-',                    EXPR_BINARY_SUB,                PREC_MULTIPLICATIVE, semantic_sub)
9279 CREATE_BINEXPR_PARSER(T_LESSLESS,             EXPR_BINARY_SHIFTLEFT,          PREC_ADDITIVE,       semantic_shift_op)
9280 CREATE_BINEXPR_PARSER(T_GREATERGREATER,       EXPR_BINARY_SHIFTRIGHT,         PREC_ADDITIVE,       semantic_shift_op)
9281 CREATE_BINEXPR_PARSER('<',                    EXPR_BINARY_LESS,               PREC_SHIFT,          semantic_comparison)
9282 CREATE_BINEXPR_PARSER('>',                    EXPR_BINARY_GREATER,            PREC_SHIFT,          semantic_comparison)
9283 CREATE_BINEXPR_PARSER(T_LESSEQUAL,            EXPR_BINARY_LESSEQUAL,          PREC_SHIFT,          semantic_comparison)
9284 CREATE_BINEXPR_PARSER(T_GREATEREQUAL,         EXPR_BINARY_GREATEREQUAL,       PREC_SHIFT,          semantic_comparison)
9285 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL,           PREC_RELATIONAL,     semantic_comparison)
9286 CREATE_BINEXPR_PARSER(T_EQUALEQUAL,           EXPR_BINARY_EQUAL,              PREC_RELATIONAL,     semantic_comparison)
9287 CREATE_BINEXPR_PARSER('&',                    EXPR_BINARY_BITWISE_AND,        PREC_EQUALITY,       semantic_binexpr_arithmetic)
9288 CREATE_BINEXPR_PARSER('^',                    EXPR_BINARY_BITWISE_XOR,        PREC_AND,            semantic_binexpr_arithmetic)
9289 CREATE_BINEXPR_PARSER('|',                    EXPR_BINARY_BITWISE_OR,         PREC_XOR,            semantic_binexpr_arithmetic)
9290 CREATE_BINEXPR_PARSER(T_ANDAND,               EXPR_BINARY_LOGICAL_AND,        PREC_OR,             semantic_logical_op)
9291 CREATE_BINEXPR_PARSER(T_PIPEPIPE,             EXPR_BINARY_LOGICAL_OR,         PREC_LOGICAL_AND,    semantic_logical_op)
9292 CREATE_BINEXPR_PARSER('=',                    EXPR_BINARY_ASSIGN,             PREC_ASSIGNMENT,     semantic_binexpr_assign)
9293 CREATE_BINEXPR_PARSER(T_PLUSEQUAL,            EXPR_BINARY_ADD_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9294 CREATE_BINEXPR_PARSER(T_MINUSEQUAL,           EXPR_BINARY_SUB_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_addsubb_assign)
9295 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL,        EXPR_BINARY_MUL_ASSIGN,         PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9296 CREATE_BINEXPR_PARSER(T_SLASHEQUAL,           EXPR_BINARY_DIV_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9297 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL,         EXPR_BINARY_MOD_ASSIGN,         PREC_ASSIGNMENT,     semantic_divmod_assign)
9298 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL,        EXPR_BINARY_SHIFTLEFT_ASSIGN,   PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9299 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL,  EXPR_BINARY_SHIFTRIGHT_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9300 CREATE_BINEXPR_PARSER(T_ANDEQUAL,             EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9301 CREATE_BINEXPR_PARSER(T_PIPEEQUAL,            EXPR_BINARY_BITWISE_OR_ASSIGN,  PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9302 CREATE_BINEXPR_PARSER(T_CARETEQUAL,           EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT,     semantic_arithmetic_assign)
9303 CREATE_BINEXPR_PARSER(',',                    EXPR_BINARY_COMMA,              PREC_ASSIGNMENT,     semantic_comma)
9304
9305
9306 static expression_t *parse_sub_expression(precedence_t precedence)
9307 {
9308         if (token.type < 0) {
9309                 return expected_expression_error();
9310         }
9311
9312         expression_parser_function_t *parser
9313                 = &expression_parsers[token.type];
9314         source_position_t             source_position = token.source_position;
9315         expression_t                 *left;
9316
9317         if (parser->parser != NULL) {
9318                 left = parser->parser();
9319         } else {
9320                 left = parse_primary_expression();
9321         }
9322         assert(left != NULL);
9323         left->base.source_position = source_position;
9324
9325         while (true) {
9326                 if (token.type < 0) {
9327                         return expected_expression_error();
9328                 }
9329
9330                 parser = &expression_parsers[token.type];
9331                 if (parser->infix_parser == NULL)
9332                         break;
9333                 if (parser->infix_precedence < precedence)
9334                         break;
9335
9336                 left = parser->infix_parser(left);
9337
9338                 assert(left != NULL);
9339                 assert(left->kind != EXPR_UNKNOWN);
9340                 left->base.source_position = source_position;
9341         }
9342
9343         return left;
9344 }
9345
9346 /**
9347  * Parse an expression.
9348  */
9349 static expression_t *parse_expression(void)
9350 {
9351         return parse_sub_expression(PREC_EXPRESSION);
9352 }
9353
9354 /**
9355  * Register a parser for a prefix-like operator.
9356  *
9357  * @param parser      the parser function
9358  * @param token_type  the token type of the prefix token
9359  */
9360 static void register_expression_parser(parse_expression_function parser,
9361                                        int token_type)
9362 {
9363         expression_parser_function_t *entry = &expression_parsers[token_type];
9364
9365         if (entry->parser != NULL) {
9366                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9367                 panic("trying to register multiple expression parsers for a token");
9368         }
9369         entry->parser = parser;
9370 }
9371
9372 /**
9373  * Register a parser for an infix operator with given precedence.
9374  *
9375  * @param parser      the parser function
9376  * @param token_type  the token type of the infix operator
9377  * @param precedence  the precedence of the operator
9378  */
9379 static void register_infix_parser(parse_expression_infix_function parser,
9380                 int token_type, unsigned precedence)
9381 {
9382         expression_parser_function_t *entry = &expression_parsers[token_type];
9383
9384         if (entry->infix_parser != NULL) {
9385                 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9386                 panic("trying to register multiple infix expression parsers for a "
9387                       "token");
9388         }
9389         entry->infix_parser     = parser;
9390         entry->infix_precedence = precedence;
9391 }
9392
9393 /**
9394  * Initialize the expression parsers.
9395  */
9396 static void init_expression_parsers(void)
9397 {
9398         memset(&expression_parsers, 0, sizeof(expression_parsers));
9399
9400         register_infix_parser(parse_array_expression,               '[',                    PREC_POSTFIX);
9401         register_infix_parser(parse_call_expression,                '(',                    PREC_POSTFIX);
9402         register_infix_parser(parse_select_expression,              '.',                    PREC_POSTFIX);
9403         register_infix_parser(parse_select_expression,              T_MINUSGREATER,         PREC_POSTFIX);
9404         register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT,   T_PLUSPLUS,             PREC_POSTFIX);
9405         register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT,   T_MINUSMINUS,           PREC_POSTFIX);
9406         register_infix_parser(parse_EXPR_BINARY_MUL,                '*',                    PREC_MULTIPLICATIVE);
9407         register_infix_parser(parse_EXPR_BINARY_DIV,                '/',                    PREC_MULTIPLICATIVE);
9408         register_infix_parser(parse_EXPR_BINARY_MOD,                '%',                    PREC_MULTIPLICATIVE);
9409         register_infix_parser(parse_EXPR_BINARY_ADD,                '+',                    PREC_ADDITIVE);
9410         register_infix_parser(parse_EXPR_BINARY_SUB,                '-',                    PREC_ADDITIVE);
9411         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT,          T_LESSLESS,             PREC_SHIFT);
9412         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT,         T_GREATERGREATER,       PREC_SHIFT);
9413         register_infix_parser(parse_EXPR_BINARY_LESS,               '<',                    PREC_RELATIONAL);
9414         register_infix_parser(parse_EXPR_BINARY_GREATER,            '>',                    PREC_RELATIONAL);
9415         register_infix_parser(parse_EXPR_BINARY_LESSEQUAL,          T_LESSEQUAL,            PREC_RELATIONAL);
9416         register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL,       T_GREATEREQUAL,         PREC_RELATIONAL);
9417         register_infix_parser(parse_EXPR_BINARY_EQUAL,              T_EQUALEQUAL,           PREC_EQUALITY);
9418         register_infix_parser(parse_EXPR_BINARY_NOTEQUAL,           T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9419         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND,        '&',                    PREC_AND);
9420         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR,        '^',                    PREC_XOR);
9421         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR,         '|',                    PREC_OR);
9422         register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND,        T_ANDAND,               PREC_LOGICAL_AND);
9423         register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR,         T_PIPEPIPE,             PREC_LOGICAL_OR);
9424         register_infix_parser(parse_conditional_expression,         '?',                    PREC_CONDITIONAL);
9425         register_infix_parser(parse_EXPR_BINARY_ASSIGN,             '=',                    PREC_ASSIGNMENT);
9426         register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN,         T_PLUSEQUAL,            PREC_ASSIGNMENT);
9427         register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN,         T_MINUSEQUAL,           PREC_ASSIGNMENT);
9428         register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN,         T_ASTERISKEQUAL,        PREC_ASSIGNMENT);
9429         register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN,         T_SLASHEQUAL,           PREC_ASSIGNMENT);
9430         register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN,         T_PERCENTEQUAL,         PREC_ASSIGNMENT);
9431         register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN,   T_LESSLESSEQUAL,        PREC_ASSIGNMENT);
9432         register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN,  T_GREATERGREATEREQUAL,  PREC_ASSIGNMENT);
9433         register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL,             PREC_ASSIGNMENT);
9434         register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN,  T_PIPEEQUAL,            PREC_ASSIGNMENT);
9435         register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL,           PREC_ASSIGNMENT);
9436         register_infix_parser(parse_EXPR_BINARY_COMMA,              ',',                    PREC_EXPRESSION);
9437
9438         register_expression_parser(parse_EXPR_UNARY_NEGATE,           '-');
9439         register_expression_parser(parse_EXPR_UNARY_PLUS,             '+');
9440         register_expression_parser(parse_EXPR_UNARY_NOT,              '!');
9441         register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE,   '~');
9442         register_expression_parser(parse_EXPR_UNARY_DEREFERENCE,      '*');
9443         register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS,     '&');
9444         register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9445         register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9446         register_expression_parser(parse_sizeof,                      T_sizeof);
9447         register_expression_parser(parse_alignof,                     T___alignof__);
9448         register_expression_parser(parse_extension,                   T___extension__);
9449         register_expression_parser(parse_builtin_classify_type,       T___builtin_classify_type);
9450         register_expression_parser(parse_delete,                      T_delete);
9451         register_expression_parser(parse_throw,                       T_throw);
9452 }
9453
9454 /**
9455  * Parse a asm statement arguments specification.
9456  */
9457 static asm_argument_t *parse_asm_arguments(bool is_out)
9458 {
9459         asm_argument_t  *result = NULL;
9460         asm_argument_t **anchor = &result;
9461
9462         while (token.type == T_STRING_LITERAL || token.type == '[') {
9463                 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9464                 memset(argument, 0, sizeof(argument[0]));
9465
9466                 if (token.type == '[') {
9467                         eat('[');
9468                         if (token.type != T_IDENTIFIER) {
9469                                 parse_error_expected("while parsing asm argument",
9470                                                      T_IDENTIFIER, NULL);
9471                                 return NULL;
9472                         }
9473                         argument->symbol = token.v.symbol;
9474
9475                         expect(']');
9476                 }
9477
9478                 argument->constraints = parse_string_literals();
9479                 expect('(');
9480                 add_anchor_token(')');
9481                 expression_t *expression = parse_expression();
9482                 rem_anchor_token(')');
9483                 if (is_out) {
9484                         /* Ugly GCC stuff: Allow lvalue casts.  Skip casts, when they do not
9485                          * change size or type representation (e.g. int -> long is ok, but
9486                          * int -> float is not) */
9487                         if (expression->kind == EXPR_UNARY_CAST) {
9488                                 type_t      *const type = expression->base.type;
9489                                 type_kind_t  const kind = type->kind;
9490                                 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9491                                         unsigned flags;
9492                                         unsigned size;
9493                                         if (kind == TYPE_ATOMIC) {
9494                                                 atomic_type_kind_t const akind = type->atomic.akind;
9495                                                 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9496                                                 size  = get_atomic_type_size(akind);
9497                                         } else {
9498                                                 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9499                                                 size  = get_atomic_type_size(get_intptr_kind());
9500                                         }
9501
9502                                         do {
9503                                                 expression_t *const value      = expression->unary.value;
9504                                                 type_t       *const value_type = value->base.type;
9505                                                 type_kind_t   const value_kind = value_type->kind;
9506
9507                                                 unsigned value_flags;
9508                                                 unsigned value_size;
9509                                                 if (value_kind == TYPE_ATOMIC) {
9510                                                         atomic_type_kind_t const value_akind = value_type->atomic.akind;
9511                                                         value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9512                                                         value_size  = get_atomic_type_size(value_akind);
9513                                                 } else if (value_kind == TYPE_POINTER) {
9514                                                         value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9515                                                         value_size  = get_atomic_type_size(get_intptr_kind());
9516                                                 } else {
9517                                                         break;
9518                                                 }
9519
9520                                                 if (value_flags != flags || value_size != size)
9521                                                         break;
9522
9523                                                 expression = value;
9524                                         } while (expression->kind == EXPR_UNARY_CAST);
9525                                 }
9526                         }
9527
9528                         if (!is_lvalue(expression)) {
9529                                 errorf(&expression->base.source_position,
9530                                        "asm output argument is not an lvalue");
9531                         }
9532
9533                         if (argument->constraints.begin[0] == '+')
9534                                 mark_vars_read(expression, NULL);
9535                 } else {
9536                         mark_vars_read(expression, NULL);
9537                 }
9538                 argument->expression = expression;
9539                 expect(')');
9540
9541                 set_address_taken(expression, true);
9542
9543                 *anchor = argument;
9544                 anchor  = &argument->next;
9545
9546                 if (token.type != ',')
9547                         break;
9548                 eat(',');
9549         }
9550
9551         return result;
9552 end_error:
9553         return NULL;
9554 }
9555
9556 /**
9557  * Parse a asm statement clobber specification.
9558  */
9559 static asm_clobber_t *parse_asm_clobbers(void)
9560 {
9561         asm_clobber_t *result = NULL;
9562         asm_clobber_t *last   = NULL;
9563
9564         while (token.type == T_STRING_LITERAL) {
9565                 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9566                 clobber->clobber       = parse_string_literals();
9567
9568                 if (last != NULL) {
9569                         last->next = clobber;
9570                 } else {
9571                         result = clobber;
9572                 }
9573                 last = clobber;
9574
9575                 if (token.type != ',')
9576                         break;
9577                 eat(',');
9578         }
9579
9580         return result;
9581 }
9582
9583 /**
9584  * Parse an asm statement.
9585  */
9586 static statement_t *parse_asm_statement(void)
9587 {
9588         statement_t     *statement     = allocate_statement_zero(STATEMENT_ASM);
9589         asm_statement_t *asm_statement = &statement->asms;
9590
9591         eat(T_asm);
9592
9593         if (token.type == T_volatile) {
9594                 next_token();
9595                 asm_statement->is_volatile = true;
9596         }
9597
9598         expect('(');
9599         add_anchor_token(')');
9600         add_anchor_token(':');
9601         asm_statement->asm_text = parse_string_literals();
9602
9603         if (token.type != ':') {
9604                 rem_anchor_token(':');
9605                 goto end_of_asm;
9606         }
9607         eat(':');
9608
9609         asm_statement->outputs = parse_asm_arguments(true);
9610         if (token.type != ':') {
9611                 rem_anchor_token(':');
9612                 goto end_of_asm;
9613         }
9614         eat(':');
9615
9616         asm_statement->inputs = parse_asm_arguments(false);
9617         if (token.type != ':') {
9618                 rem_anchor_token(':');
9619                 goto end_of_asm;
9620         }
9621         rem_anchor_token(':');
9622         eat(':');
9623
9624         asm_statement->clobbers = parse_asm_clobbers();
9625
9626 end_of_asm:
9627         rem_anchor_token(')');
9628         expect(')');
9629         expect(';');
9630
9631         if (asm_statement->outputs == NULL) {
9632                 /* GCC: An 'asm' instruction without any output operands will be treated
9633                  * identically to a volatile 'asm' instruction. */
9634                 asm_statement->is_volatile = true;
9635         }
9636
9637         return statement;
9638 end_error:
9639         return create_invalid_statement();
9640 }
9641
9642 /**
9643  * Parse a case statement.
9644  */
9645 static statement_t *parse_case_statement(void)
9646 {
9647         statement_t       *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9648         source_position_t *const pos       = &statement->base.source_position;
9649
9650         eat(T_case);
9651
9652         expression_t *const expression   = parse_expression();
9653         statement->case_label.expression = expression;
9654         if (!is_constant_expression(expression)) {
9655                 /* This check does not prevent the error message in all cases of an
9656                  * prior error while parsing the expression.  At least it catches the
9657                  * common case of a mistyped enum entry. */
9658                 if (is_type_valid(skip_typeref(expression->base.type))) {
9659                         errorf(pos, "case label does not reduce to an integer constant");
9660                 }
9661                 statement->case_label.is_bad = true;
9662         } else {
9663                 long const val = fold_constant(expression);
9664                 statement->case_label.first_case = val;
9665                 statement->case_label.last_case  = val;
9666         }
9667
9668         if (GNU_MODE) {
9669                 if (token.type == T_DOTDOTDOT) {
9670                         next_token();
9671                         expression_t *const end_range   = parse_expression();
9672                         statement->case_label.end_range = end_range;
9673                         if (!is_constant_expression(end_range)) {
9674                                 /* This check does not prevent the error message in all cases of an
9675                                  * prior error while parsing the expression.  At least it catches the
9676                                  * common case of a mistyped enum entry. */
9677                                 if (is_type_valid(skip_typeref(end_range->base.type))) {
9678                                         errorf(pos, "case range does not reduce to an integer constant");
9679                                 }
9680                                 statement->case_label.is_bad = true;
9681                         } else {
9682                                 long const val = fold_constant(end_range);
9683                                 statement->case_label.last_case = val;
9684
9685                                 if (warning.other && val < statement->case_label.first_case) {
9686                                         statement->case_label.is_empty_range = true;
9687                                         warningf(pos, "empty range specified");
9688                                 }
9689                         }
9690                 }
9691         }
9692
9693         PUSH_PARENT(statement);
9694
9695         expect(':');
9696 end_error:
9697
9698         if (current_switch != NULL) {
9699                 if (! statement->case_label.is_bad) {
9700                         /* Check for duplicate case values */
9701                         case_label_statement_t *c = &statement->case_label;
9702                         for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9703                                 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9704                                         continue;
9705
9706                                 if (c->last_case < l->first_case || c->first_case > l->last_case)
9707                                         continue;
9708
9709                                 errorf(pos, "duplicate case value (previously used %P)",
9710                                        &l->base.source_position);
9711                                 break;
9712                         }
9713                 }
9714                 /* link all cases into the switch statement */
9715                 if (current_switch->last_case == NULL) {
9716                         current_switch->first_case      = &statement->case_label;
9717                 } else {
9718                         current_switch->last_case->next = &statement->case_label;
9719                 }
9720                 current_switch->last_case = &statement->case_label;
9721         } else {
9722                 errorf(pos, "case label not within a switch statement");
9723         }
9724
9725         statement_t *const inner_stmt = parse_statement();
9726         statement->case_label.statement = inner_stmt;
9727         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9728                 errorf(&inner_stmt->base.source_position, "declaration after case label");
9729         }
9730
9731         POP_PARENT;
9732         return statement;
9733 }
9734
9735 /**
9736  * Parse a default statement.
9737  */
9738 static statement_t *parse_default_statement(void)
9739 {
9740         statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9741
9742         eat(T_default);
9743
9744         PUSH_PARENT(statement);
9745
9746         expect(':');
9747         if (current_switch != NULL) {
9748                 const case_label_statement_t *def_label = current_switch->default_label;
9749                 if (def_label != NULL) {
9750                         errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9751                                &def_label->base.source_position);
9752                 } else {
9753                         current_switch->default_label = &statement->case_label;
9754
9755                         /* link all cases into the switch statement */
9756                         if (current_switch->last_case == NULL) {
9757                                 current_switch->first_case      = &statement->case_label;
9758                         } else {
9759                                 current_switch->last_case->next = &statement->case_label;
9760                         }
9761                         current_switch->last_case = &statement->case_label;
9762                 }
9763         } else {
9764                 errorf(&statement->base.source_position,
9765                         "'default' label not within a switch statement");
9766         }
9767
9768         statement_t *const inner_stmt = parse_statement();
9769         statement->case_label.statement = inner_stmt;
9770         if (inner_stmt->kind == STATEMENT_DECLARATION) {
9771                 errorf(&inner_stmt->base.source_position, "declaration after default label");
9772         }
9773
9774         POP_PARENT;
9775         return statement;
9776 end_error:
9777         POP_PARENT;
9778         return create_invalid_statement();
9779 }
9780
9781 /**
9782  * Parse a label statement.
9783  */
9784 static statement_t *parse_label_statement(void)
9785 {
9786         assert(token.type == T_IDENTIFIER);
9787         symbol_t *symbol = token.v.symbol;
9788         label_t  *label  = get_label(symbol);
9789
9790         statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9791         statement->label.label       = label;
9792
9793         next_token();
9794
9795         PUSH_PARENT(statement);
9796
9797         /* if statement is already set then the label is defined twice,
9798          * otherwise it was just mentioned in a goto/local label declaration so far
9799          */
9800         if (label->statement != NULL) {
9801                 errorf(HERE, "duplicate label '%Y' (declared %P)",
9802                        symbol, &label->base.source_position);
9803         } else {
9804                 label->base.source_position = token.source_position;
9805                 label->statement            = statement;
9806         }
9807
9808         eat(':');
9809
9810         if (token.type == '}') {
9811                 /* TODO only warn? */
9812                 if (warning.other && false) {
9813                         warningf(HERE, "label at end of compound statement");
9814                         statement->label.statement = create_empty_statement();
9815                 } else {
9816                         errorf(HERE, "label at end of compound statement");
9817                         statement->label.statement = create_invalid_statement();
9818                 }
9819         } else if (token.type == ';') {
9820                 /* Eat an empty statement here, to avoid the warning about an empty
9821                  * statement after a label.  label:; is commonly used to have a label
9822                  * before a closing brace. */
9823                 statement->label.statement = create_empty_statement();
9824                 next_token();
9825         } else {
9826                 statement_t *const inner_stmt = parse_statement();
9827                 statement->label.statement = inner_stmt;
9828                 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9829                         errorf(&inner_stmt->base.source_position, "declaration after label");
9830                 }
9831         }
9832
9833         /* remember the labels in a list for later checking */
9834         *label_anchor = &statement->label;
9835         label_anchor  = &statement->label.next;
9836
9837         POP_PARENT;
9838         return statement;
9839 }
9840
9841 /**
9842  * Parse an if statement.
9843  */
9844 static statement_t *parse_if(void)
9845 {
9846         statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9847
9848         eat(T_if);
9849
9850         PUSH_PARENT(statement);
9851
9852         add_anchor_token('{');
9853
9854         expect('(');
9855         add_anchor_token(')');
9856         expression_t *const expr = parse_expression();
9857         statement->ifs.condition = expr;
9858         /* Â§6.8.4.1:1  The controlling expression of an if statement shall have
9859          *             scalar type. */
9860         semantic_condition(expr, "condition of 'if'-statment");
9861         mark_vars_read(expr, NULL);
9862         rem_anchor_token(')');
9863         expect(')');
9864
9865 end_error:
9866         rem_anchor_token('{');
9867
9868         add_anchor_token(T_else);
9869         statement->ifs.true_statement = parse_statement();
9870         rem_anchor_token(T_else);
9871
9872         if (token.type == T_else) {
9873                 next_token();
9874                 statement->ifs.false_statement = parse_statement();
9875         }
9876
9877         POP_PARENT;
9878         return statement;
9879 }
9880
9881 /**
9882  * Check that all enums are handled in a switch.
9883  *
9884  * @param statement  the switch statement to check
9885  */
9886 static void check_enum_cases(const switch_statement_t *statement) {
9887         const type_t *type = skip_typeref(statement->expression->base.type);
9888         if (! is_type_enum(type))
9889                 return;
9890         const enum_type_t *enumt = &type->enumt;
9891
9892         /* if we have a default, no warnings */
9893         if (statement->default_label != NULL)
9894                 return;
9895
9896         /* FIXME: calculation of value should be done while parsing */
9897         /* TODO: quadratic algorithm here. Change to an n log n one */
9898         long            last_value = -1;
9899         const entity_t *entry      = enumt->enume->base.next;
9900         for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9901              entry = entry->base.next) {
9902                 const expression_t *expression = entry->enum_value.value;
9903                 long                value      = expression != NULL ? fold_constant(expression) : last_value + 1;
9904                 bool                found      = false;
9905                 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9906                         if (l->expression == NULL)
9907                                 continue;
9908                         if (l->first_case <= value && value <= l->last_case) {
9909                                 found = true;
9910                                 break;
9911                         }
9912                 }
9913                 if (! found) {
9914                         warningf(&statement->base.source_position,
9915                                  "enumeration value '%Y' not handled in switch",
9916                                  entry->base.symbol);
9917                 }
9918                 last_value = value;
9919         }
9920 }
9921
9922 /**
9923  * Parse a switch statement.
9924  */
9925 static statement_t *parse_switch(void)
9926 {
9927         statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9928
9929         eat(T_switch);
9930
9931         PUSH_PARENT(statement);
9932
9933         expect('(');
9934         add_anchor_token(')');
9935         expression_t *const expr = parse_expression();
9936         mark_vars_read(expr, NULL);
9937         type_t       *      type = skip_typeref(expr->base.type);
9938         if (is_type_integer(type)) {
9939                 type = promote_integer(type);
9940                 if (warning.traditional) {
9941                         if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9942                                 warningf(&expr->base.source_position,
9943                                         "'%T' switch expression not converted to '%T' in ISO C",
9944                                         type, type_int);
9945                         }
9946                 }
9947         } else if (is_type_valid(type)) {
9948                 errorf(&expr->base.source_position,
9949                        "switch quantity is not an integer, but '%T'", type);
9950                 type = type_error_type;
9951         }
9952         statement->switchs.expression = create_implicit_cast(expr, type);
9953         expect(')');
9954         rem_anchor_token(')');
9955
9956         switch_statement_t *rem = current_switch;
9957         current_switch          = &statement->switchs;
9958         statement->switchs.body = parse_statement();
9959         current_switch          = rem;
9960
9961         if (warning.switch_default &&
9962             statement->switchs.default_label == NULL) {
9963                 warningf(&statement->base.source_position, "switch has no default case");
9964         }
9965         if (warning.switch_enum)
9966                 check_enum_cases(&statement->switchs);
9967
9968         POP_PARENT;
9969         return statement;
9970 end_error:
9971         POP_PARENT;
9972         return create_invalid_statement();
9973 }
9974
9975 static statement_t *parse_loop_body(statement_t *const loop)
9976 {
9977         statement_t *const rem = current_loop;
9978         current_loop = loop;
9979
9980         statement_t *const body = parse_statement();
9981
9982         current_loop = rem;
9983         return body;
9984 }
9985
9986 /**
9987  * Parse a while statement.
9988  */
9989 static statement_t *parse_while(void)
9990 {
9991         statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9992
9993         eat(T_while);
9994
9995         PUSH_PARENT(statement);
9996
9997         expect('(');
9998         add_anchor_token(')');
9999         expression_t *const cond = parse_expression();
10000         statement->whiles.condition = cond;
10001         /* Â§6.8.5:2    The controlling expression of an iteration statement shall
10002          *             have scalar type. */
10003         semantic_condition(cond, "condition of 'while'-statement");
10004         mark_vars_read(cond, NULL);
10005         rem_anchor_token(')');
10006         expect(')');
10007
10008         statement->whiles.body = parse_loop_body(statement);
10009
10010         POP_PARENT;
10011         return statement;
10012 end_error:
10013         POP_PARENT;
10014         return create_invalid_statement();
10015 }
10016
10017 /**
10018  * Parse a do statement.
10019  */
10020 static statement_t *parse_do(void)
10021 {
10022         statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10023
10024         eat(T_do);
10025
10026         PUSH_PARENT(statement);
10027
10028         add_anchor_token(T_while);
10029         statement->do_while.body = parse_loop_body(statement);
10030         rem_anchor_token(T_while);
10031
10032         expect(T_while);
10033         expect('(');
10034         add_anchor_token(')');
10035         expression_t *const cond = parse_expression();
10036         statement->do_while.condition = cond;
10037         /* Â§6.8.5:2    The controlling expression of an iteration statement shall
10038          *             have scalar type. */
10039         semantic_condition(cond, "condition of 'do-while'-statement");
10040         mark_vars_read(cond, NULL);
10041         rem_anchor_token(')');
10042         expect(')');
10043         expect(';');
10044
10045         POP_PARENT;
10046         return statement;
10047 end_error:
10048         POP_PARENT;
10049         return create_invalid_statement();
10050 }
10051
10052 /**
10053  * Parse a for statement.
10054  */
10055 static statement_t *parse_for(void)
10056 {
10057         statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10058
10059         eat(T_for);
10060
10061         PUSH_PARENT(statement);
10062
10063         size_t const  top       = environment_top();
10064         scope_t      *old_scope = scope_push(&statement->fors.scope);
10065
10066         expect('(');
10067         add_anchor_token(')');
10068
10069         if (token.type == ';') {
10070                 next_token();
10071         } else if (is_declaration_specifier(&token, false)) {
10072                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10073         } else {
10074                 add_anchor_token(';');
10075                 expression_t *const init = parse_expression();
10076                 statement->fors.initialisation = init;
10077                 mark_vars_read(init, ENT_ANY);
10078                 if (warning.unused_value && !expression_has_effect(init)) {
10079                         warningf(&init->base.source_position,
10080                                         "initialisation of 'for'-statement has no effect");
10081                 }
10082                 rem_anchor_token(';');
10083                 expect(';');
10084         }
10085
10086         if (token.type != ';') {
10087                 add_anchor_token(';');
10088                 expression_t *const cond = parse_expression();
10089                 statement->fors.condition = cond;
10090                 /* Â§6.8.5:2    The controlling expression of an iteration statement
10091                  *             shall have scalar type. */
10092                 semantic_condition(cond, "condition of 'for'-statement");
10093                 mark_vars_read(cond, NULL);
10094                 rem_anchor_token(';');
10095         }
10096         expect(';');
10097         if (token.type != ')') {
10098                 expression_t *const step = parse_expression();
10099                 statement->fors.step = step;
10100                 mark_vars_read(step, ENT_ANY);
10101                 if (warning.unused_value && !expression_has_effect(step)) {
10102                         warningf(&step->base.source_position,
10103                                  "step of 'for'-statement has no effect");
10104                 }
10105         }
10106         expect(')');
10107         rem_anchor_token(')');
10108         statement->fors.body = parse_loop_body(statement);
10109
10110         assert(current_scope == &statement->fors.scope);
10111         scope_pop(old_scope);
10112         environment_pop_to(top);
10113
10114         POP_PARENT;
10115         return statement;
10116
10117 end_error:
10118         POP_PARENT;
10119         rem_anchor_token(')');
10120         assert(current_scope == &statement->fors.scope);
10121         scope_pop(old_scope);
10122         environment_pop_to(top);
10123
10124         return create_invalid_statement();
10125 }
10126
10127 /**
10128  * Parse a goto statement.
10129  */
10130 static statement_t *parse_goto(void)
10131 {
10132         statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10133         eat(T_goto);
10134
10135         if (GNU_MODE && token.type == '*') {
10136                 next_token();
10137                 expression_t *expression = parse_expression();
10138                 mark_vars_read(expression, NULL);
10139
10140                 /* Argh: although documentation says the expression must be of type void*,
10141                  * gcc accepts anything that can be casted into void* without error */
10142                 type_t *type = expression->base.type;
10143
10144                 if (type != type_error_type) {
10145                         if (!is_type_pointer(type) && !is_type_integer(type)) {
10146                                 errorf(&expression->base.source_position,
10147                                         "cannot convert to a pointer type");
10148                         } else if (warning.other && type != type_void_ptr) {
10149                                 warningf(&expression->base.source_position,
10150                                         "type of computed goto expression should be 'void*' not '%T'", type);
10151                         }
10152                         expression = create_implicit_cast(expression, type_void_ptr);
10153                 }
10154
10155                 statement->gotos.expression = expression;
10156         } else {
10157                 if (token.type != T_IDENTIFIER) {
10158                         if (GNU_MODE)
10159                                 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10160                         else
10161                                 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10162                         eat_until_anchor();
10163                         goto end_error;
10164                 }
10165                 symbol_t *symbol = token.v.symbol;
10166                 next_token();
10167
10168                 statement->gotos.label = get_label(symbol);
10169         }
10170
10171         /* remember the goto's in a list for later checking */
10172         *goto_anchor = &statement->gotos;
10173         goto_anchor  = &statement->gotos.next;
10174
10175         expect(';');
10176
10177         return statement;
10178 end_error:
10179         return create_invalid_statement();
10180 }
10181
10182 /**
10183  * Parse a continue statement.
10184  */
10185 static statement_t *parse_continue(void)
10186 {
10187         if (current_loop == NULL) {
10188                 errorf(HERE, "continue statement not within loop");
10189         }
10190
10191         statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10192
10193         eat(T_continue);
10194         expect(';');
10195
10196 end_error:
10197         return statement;
10198 }
10199
10200 /**
10201  * Parse a break statement.
10202  */
10203 static statement_t *parse_break(void)
10204 {
10205         if (current_switch == NULL && current_loop == NULL) {
10206                 errorf(HERE, "break statement not within loop or switch");
10207         }
10208
10209         statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10210
10211         eat(T_break);
10212         expect(';');
10213
10214 end_error:
10215         return statement;
10216 }
10217
10218 /**
10219  * Parse a __leave statement.
10220  */
10221 static statement_t *parse_leave_statement(void)
10222 {
10223         if (current_try == NULL) {
10224                 errorf(HERE, "__leave statement not within __try");
10225         }
10226
10227         statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10228
10229         eat(T___leave);
10230         expect(';');
10231
10232 end_error:
10233         return statement;
10234 }
10235
10236 /**
10237  * Check if a given entity represents a local variable.
10238  */
10239 static bool is_local_variable(const entity_t *entity)
10240 {
10241         if (entity->kind != ENTITY_VARIABLE)
10242                 return false;
10243
10244         switch ((storage_class_tag_t) entity->declaration.storage_class) {
10245         case STORAGE_CLASS_AUTO:
10246         case STORAGE_CLASS_REGISTER: {
10247                 const type_t *type = skip_typeref(entity->declaration.type);
10248                 if (is_type_function(type)) {
10249                         return false;
10250                 } else {
10251                         return true;
10252                 }
10253         }
10254         default:
10255                 return false;
10256         }
10257 }
10258
10259 /**
10260  * Check if a given expression represents a local variable.
10261  */
10262 static bool expression_is_local_variable(const expression_t *expression)
10263 {
10264         if (expression->base.kind != EXPR_REFERENCE) {
10265                 return false;
10266         }
10267         const entity_t *entity = expression->reference.entity;
10268         return is_local_variable(entity);
10269 }
10270
10271 /**
10272  * Check if a given expression represents a local variable and
10273  * return its declaration then, else return NULL.
10274  */
10275 entity_t *expression_is_variable(const expression_t *expression)
10276 {
10277         if (expression->base.kind != EXPR_REFERENCE) {
10278                 return NULL;
10279         }
10280         entity_t *entity = expression->reference.entity;
10281         if (entity->kind != ENTITY_VARIABLE)
10282                 return NULL;
10283
10284         return entity;
10285 }
10286
10287 /**
10288  * Parse a return statement.
10289  */
10290 static statement_t *parse_return(void)
10291 {
10292         eat(T_return);
10293
10294         statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10295
10296         expression_t *return_value = NULL;
10297         if (token.type != ';') {
10298                 return_value = parse_expression();
10299                 mark_vars_read(return_value, NULL);
10300         }
10301
10302         const type_t *const func_type = skip_typeref(current_function->base.type);
10303         assert(is_type_function(func_type));
10304         type_t *const return_type = skip_typeref(func_type->function.return_type);
10305
10306         if (return_value != NULL) {
10307                 type_t *return_value_type = skip_typeref(return_value->base.type);
10308
10309                 if (is_type_atomic(return_type,        ATOMIC_TYPE_VOID) &&
10310                                 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10311                         if (warning.other) {
10312                                 warningf(&statement->base.source_position,
10313                                                 "'return' with a value, in function returning void");
10314                         }
10315                         return_value = NULL;
10316                 } else {
10317                         assign_error_t error = semantic_assign(return_type, return_value);
10318                         report_assign_error(error, return_type, return_value, "'return'",
10319                                             &statement->base.source_position);
10320                         return_value = create_implicit_cast(return_value, return_type);
10321                 }
10322                 /* check for returning address of a local var */
10323                 if (warning.other && return_value != NULL
10324                                 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10325                         const expression_t *expression = return_value->unary.value;
10326                         if (expression_is_local_variable(expression)) {
10327                                 warningf(&statement->base.source_position,
10328                                          "function returns address of local variable");
10329                         }
10330                 }
10331         } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10332                 warningf(&statement->base.source_position,
10333                                 "'return' without value, in function returning non-void");
10334         }
10335         statement->returns.value = return_value;
10336
10337         expect(';');
10338
10339 end_error:
10340         return statement;
10341 }
10342
10343 /**
10344  * Parse a declaration statement.
10345  */
10346 static statement_t *parse_declaration_statement(void)
10347 {
10348         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10349
10350         entity_t *before = current_scope->last_entity;
10351         if (GNU_MODE) {
10352                 parse_external_declaration();
10353         } else {
10354                 parse_declaration(record_entity, DECL_FLAGS_NONE);
10355         }
10356
10357         if (before == NULL) {
10358                 statement->declaration.declarations_begin = current_scope->entities;
10359         } else {
10360                 statement->declaration.declarations_begin = before->base.next;
10361         }
10362         statement->declaration.declarations_end = current_scope->last_entity;
10363
10364         return statement;
10365 }
10366
10367 /**
10368  * Parse an expression statement, ie. expr ';'.
10369  */
10370 static statement_t *parse_expression_statement(void)
10371 {
10372         statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10373
10374         expression_t *const expr         = parse_expression();
10375         statement->expression.expression = expr;
10376         mark_vars_read(expr, ENT_ANY);
10377
10378         expect(';');
10379
10380 end_error:
10381         return statement;
10382 }
10383
10384 /**
10385  * Parse a microsoft __try { } __finally { } or
10386  * __try{ } __except() { }
10387  */
10388 static statement_t *parse_ms_try_statment(void)
10389 {
10390         statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10391         eat(T___try);
10392
10393         PUSH_PARENT(statement);
10394
10395         ms_try_statement_t *rem = current_try;
10396         current_try = &statement->ms_try;
10397         statement->ms_try.try_statement = parse_compound_statement(false);
10398         current_try = rem;
10399
10400         POP_PARENT;
10401
10402         if (token.type == T___except) {
10403                 eat(T___except);
10404                 expect('(');
10405                 add_anchor_token(')');
10406                 expression_t *const expr = parse_expression();
10407                 mark_vars_read(expr, NULL);
10408                 type_t       *      type = skip_typeref(expr->base.type);
10409                 if (is_type_integer(type)) {
10410                         type = promote_integer(type);
10411                 } else if (is_type_valid(type)) {
10412                         errorf(&expr->base.source_position,
10413                                "__expect expression is not an integer, but '%T'", type);
10414                         type = type_error_type;
10415                 }
10416                 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10417                 rem_anchor_token(')');
10418                 expect(')');
10419                 statement->ms_try.final_statement = parse_compound_statement(false);
10420         } else if (token.type == T__finally) {
10421                 eat(T___finally);
10422                 statement->ms_try.final_statement = parse_compound_statement(false);
10423         } else {
10424                 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10425                 return create_invalid_statement();
10426         }
10427         return statement;
10428 end_error:
10429         return create_invalid_statement();
10430 }
10431
10432 static statement_t *parse_empty_statement(void)
10433 {
10434         if (warning.empty_statement) {
10435                 warningf(HERE, "statement is empty");
10436         }
10437         statement_t *const statement = create_empty_statement();
10438         eat(';');
10439         return statement;
10440 }
10441
10442 static statement_t *parse_local_label_declaration(void)
10443 {
10444         statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10445
10446         eat(T___label__);
10447
10448         entity_t *begin = NULL, *end = NULL;
10449
10450         while (true) {
10451                 if (token.type != T_IDENTIFIER) {
10452                         parse_error_expected("while parsing local label declaration",
10453                                 T_IDENTIFIER, NULL);
10454                         goto end_error;
10455                 }
10456                 symbol_t *symbol = token.v.symbol;
10457                 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10458                 if (entity != NULL && entity->base.parent_scope == current_scope) {
10459                         errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10460                                symbol, &entity->base.source_position);
10461                 } else {
10462                         entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10463
10464                         entity->base.parent_scope    = current_scope;
10465                         entity->base.namespc         = NAMESPACE_LABEL;
10466                         entity->base.source_position = token.source_position;
10467                         entity->base.symbol          = symbol;
10468
10469                         if (end != NULL)
10470                                 end->base.next = entity;
10471                         end = entity;
10472                         if (begin == NULL)
10473                                 begin = entity;
10474
10475                         environment_push(entity);
10476                 }
10477                 next_token();
10478
10479                 if (token.type != ',')
10480                         break;
10481                 next_token();
10482         }
10483         eat(';');
10484 end_error:
10485         statement->declaration.declarations_begin = begin;
10486         statement->declaration.declarations_end   = end;
10487         return statement;
10488 }
10489
10490 static void parse_namespace_definition(void)
10491 {
10492         eat(T_namespace);
10493
10494         entity_t *entity = NULL;
10495         symbol_t *symbol = NULL;
10496
10497         if (token.type == T_IDENTIFIER) {
10498                 symbol = token.v.symbol;
10499                 next_token();
10500
10501                 entity = get_entity(symbol, NAMESPACE_NORMAL);
10502                 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10503                                 && entity->base.parent_scope == current_scope) {
10504                         error_redefined_as_different_kind(&token.source_position,
10505                                                           entity, ENTITY_NAMESPACE);
10506                         entity = NULL;
10507                 }
10508         }
10509
10510         if (entity == NULL) {
10511                 entity                       = allocate_entity_zero(ENTITY_NAMESPACE);
10512                 entity->base.symbol          = symbol;
10513                 entity->base.source_position = token.source_position;
10514                 entity->base.namespc         = NAMESPACE_NORMAL;
10515                 entity->base.parent_scope    = current_scope;
10516         }
10517
10518         if (token.type == '=') {
10519                 /* TODO: parse namespace alias */
10520                 panic("namespace alias definition not supported yet");
10521         }
10522
10523         environment_push(entity);
10524         append_entity(current_scope, entity);
10525
10526         size_t const  top       = environment_top();
10527         scope_t      *old_scope = scope_push(&entity->namespacee.members);
10528
10529         expect('{');
10530         parse_externals();
10531         expect('}');
10532
10533 end_error:
10534         assert(current_scope == &entity->namespacee.members);
10535         scope_pop(old_scope);
10536         environment_pop_to(top);
10537 }
10538
10539 /**
10540  * Parse a statement.
10541  * There's also parse_statement() which additionally checks for
10542  * "statement has no effect" warnings
10543  */
10544 static statement_t *intern_parse_statement(void)
10545 {
10546         statement_t *statement = NULL;
10547
10548         /* declaration or statement */
10549         add_anchor_token(';');
10550         switch (token.type) {
10551         case T_IDENTIFIER: {
10552                 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10553                 if (la1_type == ':') {
10554                         statement = parse_label_statement();
10555                 } else if (is_typedef_symbol(token.v.symbol)) {
10556                         statement = parse_declaration_statement();
10557                 } else {
10558                         /* it's an identifier, the grammar says this must be an
10559                          * expression statement. However it is common that users mistype
10560                          * declaration types, so we guess a bit here to improve robustness
10561                          * for incorrect programs */
10562                         switch (la1_type) {
10563                         case '&':
10564                         case '*':
10565                                 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10566                                         goto expression_statment;
10567                                 /* FALLTHROUGH */
10568
10569                         DECLARATION_START
10570                         case T_IDENTIFIER:
10571                                 statement = parse_declaration_statement();
10572                                 break;
10573
10574                         default:
10575 expression_statment:
10576                                 statement = parse_expression_statement();
10577                                 break;
10578                         }
10579                 }
10580                 break;
10581         }
10582
10583         case T___extension__:
10584                 /* This can be a prefix to a declaration or an expression statement.
10585                  * We simply eat it now and parse the rest with tail recursion. */
10586                 do {
10587                         next_token();
10588                 } while (token.type == T___extension__);
10589                 bool old_gcc_extension = in_gcc_extension;
10590                 in_gcc_extension       = true;
10591                 statement = intern_parse_statement();
10592                 in_gcc_extension = old_gcc_extension;
10593                 break;
10594
10595         DECLARATION_START
10596                 statement = parse_declaration_statement();
10597                 break;
10598
10599         case T___label__:
10600                 statement = parse_local_label_declaration();
10601                 break;
10602
10603         case ';':         statement = parse_empty_statement();         break;
10604         case '{':         statement = parse_compound_statement(false); break;
10605         case T___leave:   statement = parse_leave_statement();         break;
10606         case T___try:     statement = parse_ms_try_statment();         break;
10607         case T_asm:       statement = parse_asm_statement();           break;
10608         case T_break:     statement = parse_break();                   break;
10609         case T_case:      statement = parse_case_statement();          break;
10610         case T_continue:  statement = parse_continue();                break;
10611         case T_default:   statement = parse_default_statement();       break;
10612         case T_do:        statement = parse_do();                      break;
10613         case T_for:       statement = parse_for();                     break;
10614         case T_goto:      statement = parse_goto();                    break;
10615         case T_if:        statement = parse_if();                      break;
10616         case T_return:    statement = parse_return();                  break;
10617         case T_switch:    statement = parse_switch();                  break;
10618         case T_while:     statement = parse_while();                   break;
10619
10620         EXPRESSION_START
10621                 statement = parse_expression_statement();
10622                 break;
10623
10624         default:
10625                 errorf(HERE, "unexpected token '%K' while parsing statement", &token);
10626                 statement = create_invalid_statement();
10627                 if (!at_anchor())
10628                         next_token();
10629                 break;
10630         }
10631         rem_anchor_token(';');
10632
10633         assert(statement != NULL
10634                         && statement->base.source_position.input_name != NULL);
10635
10636         return statement;
10637 }
10638
10639 /**
10640  * parse a statement and emits "statement has no effect" warning if needed
10641  * (This is really a wrapper around intern_parse_statement with check for 1
10642  *  single warning. It is needed, because for statement expressions we have
10643  *  to avoid the warning on the last statement)
10644  */
10645 static statement_t *parse_statement(void)
10646 {
10647         statement_t *statement = intern_parse_statement();
10648
10649         if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10650                 expression_t *expression = statement->expression.expression;
10651                 if (!expression_has_effect(expression)) {
10652                         warningf(&expression->base.source_position,
10653                                         "statement has no effect");
10654                 }
10655         }
10656
10657         return statement;
10658 }
10659
10660 /**
10661  * Parse a compound statement.
10662  */
10663 static statement_t *parse_compound_statement(bool inside_expression_statement)
10664 {
10665         statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10666
10667         PUSH_PARENT(statement);
10668
10669         eat('{');
10670         add_anchor_token('}');
10671
10672         size_t const  top       = environment_top();
10673         scope_t      *old_scope = scope_push(&statement->compound.scope);
10674
10675         statement_t **anchor            = &statement->compound.statements;
10676         bool          only_decls_so_far = true;
10677         while (token.type != '}') {
10678                 if (token.type == T_EOF) {
10679                         errorf(&statement->base.source_position,
10680                                "EOF while parsing compound statement");
10681                         break;
10682                 }
10683                 statement_t *sub_statement = intern_parse_statement();
10684                 if (is_invalid_statement(sub_statement)) {
10685                         /* an error occurred. if we are at an anchor, return */
10686                         if (at_anchor())
10687                                 goto end_error;
10688                         continue;
10689                 }
10690
10691                 if (warning.declaration_after_statement) {
10692                         if (sub_statement->kind != STATEMENT_DECLARATION) {
10693                                 only_decls_so_far = false;
10694                         } else if (!only_decls_so_far) {
10695                                 warningf(&sub_statement->base.source_position,
10696                                          "ISO C90 forbids mixed declarations and code");
10697                         }
10698                 }
10699
10700                 *anchor = sub_statement;
10701
10702                 while (sub_statement->base.next != NULL)
10703                         sub_statement = sub_statement->base.next;
10704
10705                 anchor = &sub_statement->base.next;
10706         }
10707         next_token();
10708
10709         /* look over all statements again to produce no effect warnings */
10710         if (warning.unused_value) {
10711                 statement_t *sub_statement = statement->compound.statements;
10712                 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10713                         if (sub_statement->kind != STATEMENT_EXPRESSION)
10714                                 continue;
10715                         /* don't emit a warning for the last expression in an expression
10716                          * statement as it has always an effect */
10717                         if (inside_expression_statement && sub_statement->base.next == NULL)
10718                                 continue;
10719
10720                         expression_t *expression = sub_statement->expression.expression;
10721                         if (!expression_has_effect(expression)) {
10722                                 warningf(&expression->base.source_position,
10723                                          "statement has no effect");
10724                         }
10725                 }
10726         }
10727
10728 end_error:
10729         rem_anchor_token('}');
10730         assert(current_scope == &statement->compound.scope);
10731         scope_pop(old_scope);
10732         environment_pop_to(top);
10733
10734         POP_PARENT;
10735         return statement;
10736 }
10737
10738 /**
10739  * Check for unused global static functions and variables
10740  */
10741 static void check_unused_globals(void)
10742 {
10743         if (!warning.unused_function && !warning.unused_variable)
10744                 return;
10745
10746         for (const entity_t *entity = file_scope->entities; entity != NULL;
10747              entity = entity->base.next) {
10748                 if (!is_declaration(entity))
10749                         continue;
10750
10751                 const declaration_t *declaration = &entity->declaration;
10752                 if (declaration->used                  ||
10753                     declaration->modifiers & DM_UNUSED ||
10754                     declaration->modifiers & DM_USED   ||
10755                     declaration->storage_class != STORAGE_CLASS_STATIC)
10756                         continue;
10757
10758                 type_t *const type = declaration->type;
10759                 const char *s;
10760                 if (entity->kind == ENTITY_FUNCTION) {
10761                         /* inhibit warning for static inline functions */
10762                         if (entity->function.is_inline)
10763                                 continue;
10764
10765                         s = entity->function.statement != NULL ? "defined" : "declared";
10766                 } else {
10767                         s = "defined";
10768                 }
10769
10770                 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10771                         type, declaration->base.symbol, s);
10772         }
10773 }
10774
10775 static void parse_global_asm(void)
10776 {
10777         statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10778
10779         eat(T_asm);
10780         expect('(');
10781
10782         statement->asms.asm_text = parse_string_literals();
10783         statement->base.next     = unit->global_asm;
10784         unit->global_asm         = statement;
10785
10786         expect(')');
10787         expect(';');
10788
10789 end_error:;
10790 }
10791
10792 static void parse_linkage_specification(void)
10793 {
10794         eat(T_extern);
10795         assert(token.type == T_STRING_LITERAL);
10796
10797         const char *linkage = parse_string_literals().begin;
10798
10799         linkage_kind_t old_linkage = current_linkage;
10800         linkage_kind_t new_linkage;
10801         if (strcmp(linkage, "C") == 0) {
10802                 new_linkage = LINKAGE_C;
10803         } else if (strcmp(linkage, "C++") == 0) {
10804                 new_linkage = LINKAGE_CXX;
10805         } else {
10806                 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10807                 new_linkage = LINKAGE_INVALID;
10808         }
10809         current_linkage = new_linkage;
10810
10811         if (token.type == '{') {
10812                 next_token();
10813                 parse_externals();
10814                 expect('}');
10815         } else {
10816                 parse_external();
10817         }
10818
10819 end_error:
10820         assert(current_linkage == new_linkage);
10821         current_linkage = old_linkage;
10822 }
10823
10824 static void parse_external(void)
10825 {
10826         switch (token.type) {
10827                 DECLARATION_START_NO_EXTERN
10828                 case T_IDENTIFIER:
10829                 case T___extension__:
10830                 /* tokens below are for implicit int */
10831                 case '&': /* & x; -> int& x; (and error later, because C++ has no
10832                              implicit int) */
10833                 case '*': /* * x; -> int* x; */
10834                 case '(': /* (x); -> int (x); */
10835                         parse_external_declaration();
10836                         return;
10837
10838                 case T_extern:
10839                         if (look_ahead(1)->type == T_STRING_LITERAL) {
10840                                 parse_linkage_specification();
10841                         } else {
10842                                 parse_external_declaration();
10843                         }
10844                         return;
10845
10846                 case T_asm:
10847                         parse_global_asm();
10848                         return;
10849
10850                 case T_namespace:
10851                         parse_namespace_definition();
10852                         return;
10853
10854                 case ';':
10855                         if (!strict_mode) {
10856                                 if (warning.other)
10857                                         warningf(HERE, "stray ';' outside of function");
10858                                 next_token();
10859                                 return;
10860                         }
10861                         /* FALLTHROUGH */
10862
10863                 default:
10864                         errorf(HERE, "stray '%K' outside of function", &token);
10865                         if (token.type == '(' || token.type == '{' || token.type == '[')
10866                                 eat_until_matching_token(token.type);
10867                         next_token();
10868                         return;
10869         }
10870 }
10871
10872 static void parse_externals(void)
10873 {
10874         add_anchor_token('}');
10875         add_anchor_token(T_EOF);
10876
10877 #ifndef NDEBUG
10878         unsigned char token_anchor_copy[T_LAST_TOKEN];
10879         memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10880 #endif
10881
10882         while (token.type != T_EOF && token.type != '}') {
10883 #ifndef NDEBUG
10884                 bool anchor_leak = false;
10885                 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10886                         unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10887                         if (count != 0) {
10888                                 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10889                                 anchor_leak = true;
10890                         }
10891                 }
10892                 if (in_gcc_extension) {
10893                         errorf(HERE, "Leaked __extension__");
10894                         anchor_leak = true;
10895                 }
10896
10897                 if (anchor_leak)
10898                         abort();
10899 #endif
10900
10901                 parse_external();
10902         }
10903
10904         rem_anchor_token(T_EOF);
10905         rem_anchor_token('}');
10906 }
10907
10908 /**
10909  * Parse a translation unit.
10910  */
10911 static void parse_translation_unit(void)
10912 {
10913         add_anchor_token(T_EOF);
10914
10915         while (true) {
10916                 parse_externals();
10917
10918                 if (token.type == T_EOF)
10919                         break;
10920
10921                 errorf(HERE, "stray '%K' outside of function", &token);
10922                 if (token.type == '(' || token.type == '{' || token.type == '[')
10923                         eat_until_matching_token(token.type);
10924                 next_token();
10925         }
10926 }
10927
10928 /**
10929  * Parse the input.
10930  *
10931  * @return  the translation unit or NULL if errors occurred.
10932  */
10933 void start_parsing(void)
10934 {
10935         environment_stack = NEW_ARR_F(stack_entry_t, 0);
10936         label_stack       = NEW_ARR_F(stack_entry_t, 0);
10937         diagnostic_count  = 0;
10938         error_count       = 0;
10939         warning_count     = 0;
10940
10941         type_set_output(stderr);
10942         ast_set_output(stderr);
10943
10944         assert(unit == NULL);
10945         unit = allocate_ast_zero(sizeof(unit[0]));
10946
10947         assert(file_scope == NULL);
10948         file_scope = &unit->scope;
10949
10950         assert(current_scope == NULL);
10951         scope_push(&unit->scope);
10952 }
10953
10954 translation_unit_t *finish_parsing(void)
10955 {
10956         assert(current_scope == &unit->scope);
10957         scope_pop(NULL);
10958
10959         assert(file_scope == &unit->scope);
10960         check_unused_globals();
10961         file_scope = NULL;
10962
10963         DEL_ARR_F(environment_stack);
10964         DEL_ARR_F(label_stack);
10965
10966         translation_unit_t *result = unit;
10967         unit = NULL;
10968         return result;
10969 }
10970
10971 void parse(void)
10972 {
10973         lookahead_bufpos = 0;
10974         for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10975                 next_token();
10976         }
10977         current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10978         parse_translation_unit();
10979 }
10980
10981 /**
10982  * Initialize the parser.
10983  */
10984 void init_parser(void)
10985 {
10986         sym_anonymous = symbol_table_insert("<anonymous>");
10987
10988         if (c_mode & _MS) {
10989                 /* add predefined symbols for extended-decl-modifier */
10990                 sym_align      = symbol_table_insert("align");
10991                 sym_allocate   = symbol_table_insert("allocate");
10992                 sym_dllimport  = symbol_table_insert("dllimport");
10993                 sym_dllexport  = symbol_table_insert("dllexport");
10994                 sym_naked      = symbol_table_insert("naked");
10995                 sym_noinline   = symbol_table_insert("noinline");
10996                 sym_noreturn   = symbol_table_insert("noreturn");
10997                 sym_nothrow    = symbol_table_insert("nothrow");
10998                 sym_novtable   = symbol_table_insert("novtable");
10999                 sym_property   = symbol_table_insert("property");
11000                 sym_get        = symbol_table_insert("get");
11001                 sym_put        = symbol_table_insert("put");
11002                 sym_selectany  = symbol_table_insert("selectany");
11003                 sym_thread     = symbol_table_insert("thread");
11004                 sym_uuid       = symbol_table_insert("uuid");
11005                 sym_deprecated = symbol_table_insert("deprecated");
11006                 sym_restrict   = symbol_table_insert("restrict");
11007                 sym_noalias    = symbol_table_insert("noalias");
11008         }
11009         memset(token_anchor_set, 0, sizeof(token_anchor_set));
11010
11011         init_expression_parsers();
11012         obstack_init(&temp_obst);
11013
11014         symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11015         type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11016 }
11017
11018 /**
11019  * Terminate the parser.
11020  */
11021 void exit_parser(void)
11022 {
11023         obstack_free(&temp_obst, NULL);
11024 }