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