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