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