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