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