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