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