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