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