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