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