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