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