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