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