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