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