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