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