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