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