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