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