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