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