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