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