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