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