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