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