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