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