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