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