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