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