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