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