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