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