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