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