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