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