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