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