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