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