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