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