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